pub const WGSL: &str = r#"
// IEC 61966-2-1 sRGB OETF — matches three.js `sRGBTransferOETF`.
fn linear_to_srgb_1(c : f32) -> f32 {
if (c <= 0.0031308) {
return c * 12.92;
}
return 1.055 * pow(max(c, 0.0), 1.0 / 2.4) - 0.055;
}
fn linear_to_srgb(c : vec3<f32>) -> vec3<f32> {
let cutoff = vec3<f32>(0.0031308);
let lo = c * 12.92;
let hi = pow(max(c, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4)) * 1.055 - vec3<f32>(0.055);
return mix(hi, lo, step(c, cutoff));
}
// The inverse: what a sampler does for you on an `*Srgb` format, and what you
// have to do yourself when the bytes are sRGB-encoded in a linear format.
fn srgb_to_linear_1(c : f32) -> f32 {
if (c <= 0.04045) {
return c / 12.92;
}
return pow((c + 0.055) / 1.055, 2.4);
}
fn srgb_to_linear(c : vec3<f32>) -> vec3<f32> {
let lo = c / 12.92;
let hi = pow((max(c, vec3<f32>(0.0)) + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
return select(hi, lo, c <= vec3<f32>(0.04045));
}
"#;
pub const WGSL_FUNCTIONS: &[&str] = &[
"linear_to_srgb_1",
"linear_to_srgb",
"srgb_to_linear_1",
"srgb_to_linear",
];
pub fn with_prelude(source: &str) -> String {
if WGSL_FUNCTIONS
.iter()
.any(|f| source.contains(&format!("fn {f}")))
{
return source.to_string();
}
format!("{WGSL}\n{source}")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::srgb;
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_prelude_is_valid_wgsl() {
let source = format!("{WGSL}\n@fragment fn fs() -> @location(0) vec4<f32> {{ return vec4<f32>(srgb_to_linear(vec3<f32>(0.5)), 1.0); }}");
let module =
wgpu::naga::front::wgsl::parse_str(&source).expect("the colour prelude parses");
wgpu::naga::valid::Validator::new(
wgpu::naga::valid::ValidationFlags::all(),
wgpu::naga::valid::Capabilities::all(),
)
.validate(&module)
.expect("the colour prelude validates");
}
#[test]
fn the_prelude_declares_what_it_says_it_does() {
for f in WGSL_FUNCTIONS {
assert!(WGSL.contains(&format!("fn {f}")), "{f} is missing");
}
let mine = "fn linear_to_srgb(c : vec3<f32>) -> vec3<f32> { return c; }";
assert_eq!(with_prelude(mine), mine);
assert!(with_prelude("// nothing").contains("fn linear_to_srgb"));
}
#[test]
fn the_rust_and_the_shader_agree() {
let wgsl_encode = |c: f32| {
if c <= 0.0031308 {
c * 12.92
} else {
1.055 * c.max(0.0).powf(1.0 / 2.4) - 0.055
}
};
let wgsl_decode = |c: f32| {
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
};
for i in 0..=255u16 {
let v = i as f32 / 255.0;
assert!(
(wgsl_encode(v) - srgb::linear_to_srgb_f32(v)).abs() < 1e-6,
"encode disagrees at {v}"
);
assert!(
(wgsl_decode(v) - srgb::srgb_to_linear(i as u8)).abs() < 1e-6,
"decode disagrees at {v}"
);
assert!(
(wgsl_decode(wgsl_encode(v)) - v).abs() < 1e-5,
"round trip at {v}"
);
}
}
}