Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Color Lookup: keep the .cube input domain and reject the ones we cannot apply (#1130)

Elvis33LE53985e5f34dd
diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs
index 9ba2f7f06..0a68ef8bc 100644
--- a/crates/cms/src/lutfile.rs
+++ b/crates/cms/src/lutfile.rs
@@ -13,6 +13,12 @@ pub struct LutFile {
pub size: usize,
/// `size`³ × 3 values, red fastest.
pub data: Vec<f32>,
+ /// The input domain the table expects (`.cube` `DOMAIN_MIN`/`DOMAIN_MAX`,
+ /// `LUT_3D_INPUT_RANGE`): an input `c` samples the table at `(c - min) / (max - min)`,
+ /// saturating outside. `[0, 1]` is the identity default; applying a table with any other
+ /// domain is rejected upstream until Color Lookup carries it through.
+ pub domain_min: [f32; 3],
+ pub domain_max: [f32; 3],
}
/// Largest edge length accepted (64³ is Photoshop's practical maximum; 129 leaves headroom while
@@ -61,7 +67,12 @@ impl LutFile {
}
}
}
- LutFile { title: title.to_string(), size, data }
+ LutFile { title: title.to_string(), size, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }
+ }
+
+ /// Whether the table expects plain 0..1 inputs (the common case; Photoshop's default).
+ pub fn domain_is_default(&self) -> bool {
+ self.domain_min == [0.0, 0.0, 0.0] && self.domain_max == [1.0, 1.0, 1.0]
}
fn check(self) -> Result<Self, LutError> {
@@ -131,17 +142,24 @@ pub fn parse_cube(text: &str) -> Result<LutFile, LutError> {
_ => {}
}
}
- let _ = (dmin, dmax); // Domain other than 0..1 only shifts input sampling; we assume 0..1 inputs.
+ let domain_ok = (0..3).all(|k| dmin[k] < dmax[k] && dmin[k].is_finite() && dmax[k].is_finite());
+ if (size3 > 0 || size1 >= 2) && !domain_ok {
+ return err(format!("DOMAIN_MIN {:?} must lie below DOMAIN_MAX {:?}", dmin, dmax));
+ }
if size3 > 0 {
- return LutFile { title, size: size3, data: rows }.check();
+ return LutFile { title, size: size3, data: rows, domain_min: dmin, domain_max: dmax }.check();
}
if size1 >= 2 {
let expected_rows = size1.checked_mul(3).ok_or_else(|| LutError(format!("unsupported 1D LUT size {size1}")))?;
if rows.len() != expected_rows {
return err("no LUT_3D_SIZE in .cube file");
}
+ // The 1D table is resampled onto a 0..1 cube anyway, so its input domain
+ // (`DOMAIN_MIN`/`MAX`, `LUT_1D_INPUT_RANGE`) is baked into the resample: an input `v`
+ // reads the table at `(v - min) / (max - min)`, saturating outside.
let curve = |ch: usize, v: f32| {
- let x = v.clamp(0.0, 1.0) * (size1 - 1) as f32;
+ let t = (v - dmin[ch]) / (dmax[ch] - dmin[ch]);
+ let x = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 } * (size1 - 1) as f32;
let i = (x.floor() as usize).min(size1 - 2);
let f = x - i as f32;
rows[i * 3 + ch] * (1.0 - f) + rows[(i + 1) * 3 + ch] * f
@@ -182,7 +200,7 @@ pub fn parse_3dl(text: &str) -> Result<LutFile, LutError> {
data[at + k] = (row[k] / scale) as f32;
}
}
- LutFile { title: String::new(), size: n, data }.check()
+ LutFile { title: String::new(), size: n, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }.check()
}
/// SpeedGrade `.look`: `<size>` and a hex `<data>` string of little-endian float32 RGB triplets
@@ -202,7 +220,7 @@ pub fn parse_look(text: &str) -> Result<LutFile, LutError> {
let floats: Vec<f32> = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
let rgba_entries = entries.checked_mul(4).ok_or_else(|| LutError(format!("unsupported LUT size {size}")))?;
let data = if floats.len() == rgba_entries { floats.as_chunks::<4>().0.iter().flat_map(|c| [c[0], c[1], c[2]]).collect() } else { floats };
- LutFile { title: tag("title").unwrap_or_default(), size, data }.check()
+ LutFile { title: tag("title").unwrap_or_default(), size, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }.check()
}
/// Writes a `.cube` file (what Photoshop embeds in a Color Lookup layer).
@@ -283,6 +301,65 @@ pub fn builtin(id: &str) -> Option<LutFile> {
mod tests {
use super::*;
+ #[test]
+ fn cube_domain_is_kept_and_validated() {
+ let base = "TITLE \"t\"
+LUT_3D_SIZE 2
+";
+ let rows = "0 0 0
+0 0 1
+0 1 0
+0 1 1
+1 0 0
+1 0 1
+1 1 0
+1 1 1
+";
+ // The default domain parses as default.
+ let d = parse_cube(&format!("{base}{rows}")).expect("default domain");
+ assert!(d.domain_is_default());
+ // DOMAIN_MIN/MAX are kept for the caller to act on.
+ let d = parse_cube(&format!(
+ "DOMAIN_MIN 0.1 0.2 0.3
+DOMAIN_MAX 0.9 0.8 0.7
+{base}{rows}"
+ ))
+ .expect("custom domain");
+ assert_eq!(d.domain_min, [0.1, 0.2, 0.3]);
+ assert_eq!(d.domain_max, [0.9, 0.8, 0.7]);
+ assert!(!d.domain_is_default());
+ // A degenerate domain is a parse error, not a division by zero later.
+ let e = parse_cube(&format!(
+ "DOMAIN_MIN 0.5 0.5 0.5
+DOMAIN_MAX 0.5 1 1
+{base}{rows}"
+ ))
+ .unwrap_err();
+ assert!(e.0.contains("below DOMAIN_MAX"), "{e}");
+ }
+
+ #[test]
+ fn cube_1d_domain_is_baked_into_the_resample() {
+ // An identity ramp over the domain 0.25..0.75: 0.25 maps to 0, 0.5 to 0.5, 0.75 to 1.
+ let table = "LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 0.25 0.75\n0 0 0\n1 1 1\n";
+ let l = parse_cube(table).expect("1D with input range");
+ assert!(l.domain_is_default(), "the domain is baked in, so the cube is plain 0..1");
+ let at = |r: usize| l.data[r * 3];
+ // 33-point grid, red fastest: entry r on the red axis is input r / 32.
+ assert!(at(0).abs() < 1e-6, "below the domain saturates to 0");
+ assert!((at(16) - 0.5).abs() < 1e-5, "0.5 is the middle of 0.25..0.75: {}", at(16));
+ assert!((at(8) - 0.0).abs() < 1e-5, "0.25 maps to 0: {}", at(8));
+ assert!((at(24) - 1.0).abs() < 1e-5, "0.75 maps to 1: {}", at(24));
+ assert!((at(32) - 1.0).abs() < 1e-6, "above the domain saturates to 1");
+ // Per-channel DOMAIN_MIN/MAX work the same way.
+ let l = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0.5\nDOMAIN_MAX 1 1 1\n0 0 0\n1 1 1\n").expect("1D domain");
+ let blue_mid = l.data[(16 * 33 * 33) * 3 + 2];
+ assert!(blue_mid.abs() < 1e-5, "blue 0.5 is the bottom of its domain: {blue_mid}");
+ // A degenerate 1D domain is rejected like the 3D one.
+ let e = parse_cube("LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 1 1\n0 0 0\n1 1 1\n").unwrap_err();
+ assert!(e.0.contains("below DOMAIN_MAX"), "{e}");
+ }
+
#[test]
fn cube_roundtrip_and_identity() {
let id = LutFile::identity(5);
diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs
index e2f90b1ed..a9483ee62 100644
--- a/crates/engine/src/adjust_cmds.rs
+++ b/crates/engine/src/adjust_cmds.rs
@@ -96,6 +96,15 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
loaded = Some((f, base_name(path)));
}
if let Some((f, label)) = loaded {
+ if !f.domain_is_default() {
+ return Err(bad(
+ CMD,
+ format!(
+ "`{}` declares DOMAIN_MIN {:?} / DOMAIN_MAX {:?}: Color Lookup applies the plain 0..1 domain, so the look would shift; honouring a custom domain is not supported yet",
+ label, f.domain_min, f.domain_max
+ ),
+ ));
+ }
name = label;
size = f.size as u32;
lut = Some(std::sync::Arc::new(f.data));
diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs
index 96874681f..67719afbc 100644
--- a/crates/engine/src/adjust_cmds/tests.rs
+++ b/crates/engine/src/adjust_cmds/tests.rs
@@ -194,6 +194,25 @@ fn color_lookup_builtin_data_and_errors() {
}
}
assert!(s.execute("image.adjustments.colorLookup", json!({"lut": "nope"})).is_err());
+ // A custom input domain is rejected with the reason instead of silently shifting the look.
+ // (A fresh pixel layer: this `s` still has the adjustment layer active, and the command is
+ // disabled there - the domain rejection itself needs a pixel layer to reach.)
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let domained = "TITLE \"d\"
+DOMAIN_MIN 0.1 0.1 0.1
+DOMAIN_MAX 0.9 0.9 0.9
+LUT_3D_SIZE 2
+0 0 0
+0 0 1
+0 1 0
+0 1 1
+1 0 0
+1 0 1
+1 1 0
+1 1 1
+";
+ let e = s.execute("image.adjustments.colorLookup", json!({"data": domained, "fileName": "log.cube"})).unwrap_err();
+ assert!(e.to_string().contains("DOMAIN_MIN"), "{e}");
assert!(s.execute("image.adjustments.colorLookup", json!({"data": "LUT_3D_SIZE 3\n0 0 0\n"})).is_err());
assert!(s.execute("layer.newAdjustmentLayer.colorLookup", json!({"file": "/nonexistent/x.cube"})).is_err());
let looks = s.execute("image.adjustments.colorLookup.list", json!({})).unwrap();
diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs
index 61d869ac8..02315426f 100644
--- a/crates/io/src/adjust_map.rs
+++ b/crates/io/src/adjust_map.rs
@@ -607,7 +607,10 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {
let n = *size as usize;
let cube = lut.as_deref().zip(photocraft_doc::adjust::lut3d_len(*size)).and_then(|(table, len)| table.get(..len)).filter(|_| n <= 256);
let (file, dither) = match cube {
- Some(cube) => (photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec() }, *dither),
+ Some(cube) => (
+ photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec(), domain_min: [0.0; 3], domain_max: [1.0; 3] },
+ *dither,
+ ),
_ => (photocraft_cms::lutfile::LutFile { title: String::new(), ..photocraft_cms::lutfile::LutFile::identity(2) }, false),
};
let en =