From ee903c96ad133a732fc0c7656898f02281e564cb Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Thu, 5 Nov 2026 06:58:19 -0500 Subject: [PATCH] fix(formats): choose sRGB or linear when reading bitmaps decode() sRGB-decoded every 8/16-bit color bitmap, so an RGB normal map (0.5, 0.5, 1) became (0.214, 0.214, 1). decode now takes a linear flag. The Bitmap node gets a Color space choice (sRGB by default, so existing files cook the same) and graph input preview images can be bound as linear data maps (graph.input.bind linear: true, stored in input_images_linear). Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/graph.rs | 6 +++++- crates/engine/src/file_cmds.rs | 2 +- crates/engine/src/material_cmds.rs | 20 +++++++++++++----- crates/engine/src/session.rs | 11 +++++++--- crates/engine/src/session.test.rs | 26 +++++++++++++++++++++++ crates/eval/src/lib.rs | 33 +++++++++++++++++++++++++++++- crates/formats/src/lib.rs | 25 +++++++++++++++------- crates/image/src/lib.rs | 23 +++++++++++++++++++++ crates/nodes/src/atomic.rs | 5 ++++- 9 files changed, 132 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/session.test.rs diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs index ce317467..adc90b6d 100644 --- a/crates/core/src/graph.rs +++ b/crates/core/src/graph.rs @@ -1,6 +1,6 @@ //! Graphs: nodes, connections, frames, comments, navigation pins and exposed inputs. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; @@ -275,6 +275,9 @@ pub struct Graph { /// baked in TextureCraft, say). Instances feed their inputs from their ports instead. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub input_images: BTreeMap, + /// Identifiers whose preview image is a data map, read as stored rather than sRGB-decoded. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub input_images_linear: BTreeSet, #[serde(default)] pub attributes: Attributes, /// The id the next node, frame, comment or pin gets. @@ -302,6 +305,7 @@ impl Graph { inputs: BTreeMap::new(), presets: Vec::new(), input_images: BTreeMap::new(), + input_images_linear: BTreeSet::new(), attributes: Attributes::default(), next_id: 1, } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index b3cef862..8e201d26 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -325,7 +325,7 @@ fn export(_: &mut Session, _: &J) -> Result { /// Embed image bytes as a resource; returns the resource name. pub fn add_resource(s: &mut Session, file: &str, bytes: Vec, name: Option<&str>) -> Result { - materialcraft_formats::decode(&bytes)?; + materialcraft_formats::decode(&bytes, false)?; s.edit("Import bitmap", |s| Ok(push_resource(&mut s.pkg, file, bytes, name))) } diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index c5902b97..d37f0155 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -40,7 +40,7 @@ pub(crate) fn specs() -> Vec { "Set input preview image", [], None, - "{identifier, resource? | path?} shows a bitmap resource (or an image file, embedded) on the graph's input node `identifier`, e.g. a mesh map baked in TextureCraft", + "{identifier, resource? | path?, linear?} shows a bitmap resource (or an image file, embedded) on the graph's input node `identifier`, e.g. a mesh map baked in TextureCraft; `linear: true` reads a data map (normal, height) as stored instead of sRGB-decoding it", has_graph, bind ), @@ -154,7 +154,7 @@ fn export_material(s: &mut Session, p: &J) -> Result { for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() { let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?; let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?; - o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes)?); + o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes, false)?); } let bytes = material_bytes(s, gi, &o)?; materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?; @@ -215,7 +215,14 @@ fn bind(s: &mut Session, p: &J) -> Result { Some((name, bytes)) => crate::file_cmds::push_resource(&mut s.pkg, &name, bytes, Some(&id)), None => strp(p, "resource").unwrap_or_default().to_string(), }; - s.graph_mut()?.input_images.insert(id.clone(), res.clone()); + let linear = p.get("linear").and_then(J::as_bool).unwrap_or(false); + let g = s.graph_mut()?; + g.input_images.insert(id.clone(), res.clone()); + if linear { + g.input_images_linear.insert(id.clone()); + } else { + g.input_images_linear.remove(&id); + } Ok(json!({"identifier": id, "resource": res})) }) } @@ -223,7 +230,7 @@ fn bind(s: &mut Session, p: &J) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_image_file(cmd: &str, path: &str) -> Result<(String, Vec)> { let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - materialcraft_formats::decode(&bytes)?; + materialcraft_formats::decode(&bytes, false)?; let name = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("input.png").to_string(); Ok((name, bytes)) } @@ -235,7 +242,10 @@ fn read_image_file(cmd: &str, _: &str) -> Result<(String, Vec)> { fn unbind(s: &mut Session, p: &J) -> Result { let id = strp(p, "identifier").ok_or_else(|| bad("graph.input.unbind", "`identifier` is required"))?.to_string(); - s.edit("Clear input preview image", |s| Ok(J::Bool(s.graph_mut()?.input_images.remove(&id).is_some()))) + s.edit("Clear input preview image", |s| { + s.graph_mut()?.input_images_linear.remove(&id); + Ok(J::Bool(s.graph_mut()?.input_images.remove(&id).is_some())) + }) } #[cfg(test)] diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7dbdeaea..a5125098 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -300,13 +300,14 @@ impl Session { pub fn resource_decoder(&self) -> impl Fn(&str) -> Option + Sync + Send + 'static { let res: Vec<(String, Arc>)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); let memo = self.decoded.clone(); - move |name: &str| { + move |requested: &str| { + let (name, linear) = materialcraft_image::split_resource_key(requested); let (_, bytes) = res.iter().find(|(n, _)| n == name)?; - let key = format!("{name}:{}", bytes.len()); + let key = format!("{requested}:{}", bytes.len()); if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { return Some(i.clone()); } - let img = materialcraft_formats::decode(bytes).ok()?; + let img = materialcraft_formats::decode(bytes, linear).ok()?; memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); Some(img) } @@ -402,3 +403,7 @@ impl Session { } } } + +#[cfg(test)] +#[path = "session.test.rs"] +mod tests; diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs new file mode 100644 index 00000000..00be0194 --- /dev/null +++ b/crates/engine/src/session.test.rs @@ -0,0 +1,26 @@ +use std::sync::Arc; + +use materialcraft_core::{Package, Resource}; +use materialcraft_formats::{Depth, encode}; +use materialcraft_image::{Image, Kind, resource_key}; + +use crate::session::Session; + +fn normal_map_session() -> Session { + let mut pkg = Package::new("T"); + let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap(); + pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: Arc::new(png) }); + Session::new(pkg) +} + +#[test] +fn the_resource_decoder_reads_data_maps_as_stored() { + let s = normal_map_session(); + let dec = s.resource_decoder(); + let color = dec(&resource_key("n", false)).unwrap(); + let data = dec(&resource_key("n", true)).unwrap(); + // 8-bit color is sRGB-decoded (0.5 -> ~0.214); a data map keeps 0.5. + assert!((color.get(0, 0, false)[0] - 0.214).abs() < 0.01); + assert!((data.get(0, 0, false)[0] - 0.5).abs() < 0.01); + assert!((data.get(0, 0, false)[2] - 1.0).abs() < 0.01); +} diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 5932bd7e..33248374 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -265,7 +265,11 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook // The top-level graph's input nodes show their preview images; the caller's images win. let bound; let opts = if opts.depth == 0 && !graph.input_images.is_empty() { - let mut inputs: BTreeMap = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect(); + let mut inputs: BTreeMap = graph + .input_images + .iter() + .filter_map(|(id, res)| Some((id.clone(), (opts.resource)(&materialcraft_image::resource_key(res, graph.input_images_linear.contains(id)))?))) + .collect(); inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone()))); bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), ..*opts }; &bound @@ -568,4 +572,31 @@ mod tests { let c = cook(&p, 0, &opts, &mut cache); assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); } + + #[test] + fn linear_input_images_and_bitmap_nodes_request_data_reads() { + // The decoder returns 0.5 for a linear request and 0.2 for an sRGB one. + let res = |k: &str| { + let (name, linear) = materialcraft_image::split_resource_key(k); + (name == "m").then(|| Image::filled(4, 4, Kind::Color, [if linear { 0.5 } else { 0.2 }; 4])) + }; + let mut p = Package::new("p"); + let mut g = Graph::new("g"); + g.size = [4, 4]; + let i = g.add_node("input_color", [0.0, 0.0]); + g.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("n".into())); + let b = g.add_node("bitmap", [0.0, 100.0]); + g.node_mut(b).unwrap().params.insert("resource".into(), Value::Text("m".into())); + g.input_images.insert("n".into(), "m".into()); + p.graphs.push(g); + let first = |p: &Package| { + let mut cache = Cache::default(); + let c = cook(p, 0, &Options::new(&res), &mut cache); + (c.image(i, 0).unwrap().data[0], c.image(b, 0).unwrap().data[0]) + }; + assert_eq!(first(&p), (0.2, 0.2), "default is sRGB, as before"); + p.graphs[0].input_images_linear.insert("n".into()); + p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1)); + assert_eq!(first(&p), (0.5, 0.5)); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index c7f3747d..b7b13887 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -91,9 +91,10 @@ pub fn safe_file_name(name: &str) -> String { if cleaned.is_empty() { "resource".into() } else { cleaned } } -/// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale -/// files stay grayscale). -pub fn decode(bytes: &[u8]) -> Result { +/// Decode image file bytes into a float image. 8/16-bit color is sRGB-decoded to linear, unless +/// `linear` is set (a data map such as a normal map: the file's values are kept as stored); +/// float files and grayscale files are never converted. +pub fn decode(bytes: &[u8], linear: bool) -> Result { // TGA has no signature: try it when the format cannot be guessed. let img = image::load_from_memory(bytes) .or_else(|e| image::load_from_memory_with_format(bytes, image::ImageFormat::Tga).map_err(|_| e)) @@ -114,7 +115,7 @@ pub fn decode(bytes: &[u8]) -> Result { .pixels() .flat_map(|p| { let [r, g, b, a] = p.0; - if float { [r, g, b, a] } else { [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a] } + if float || linear { [r, g, b, a] } else { [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a] } }) .collect(); Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) }) @@ -245,7 +246,7 @@ mod tests { let q = load_package(&bytes).unwrap(); assert_eq!(q.graphs, p.graphs); assert_eq!(q.resources[0].bytes, p.resources[0].bytes); - let img = decode(&q.resources[0].bytes).unwrap(); + let img = decode(&q.resources[0].bytes, false).unwrap(); assert!((img.get(0, 0, false)[1] - 0.5).abs() < 0.01); assert!(load_package(b"not a zip").is_err()); } @@ -258,13 +259,23 @@ mod tests { for depth in [Depth::U8, Depth::U16, Depth::F32] { for i in [&img, &gray] { let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); - let back = decode(&b).unwrap_or_else(|e| panic!("{ext} decode: {e}")); + let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}")); assert_eq!((back.w, back.h), (8, 8)); } } } let png16 = encode(&gray, "png", Depth::U16, false).unwrap(); - assert!((decode(&png16).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); + assert!((decode(&png16, false).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); + } + + #[test] + fn linear_decode_keeps_data_map_values() { + let normal = Image::filled(2, 2, Kind::Color, [0.5, 0.5, 1.0, 1.0]); + let png = encode(&normal, "png", Depth::U8, false).unwrap(); + let data = decode(&png, true).unwrap(); + assert!((data.get(0, 0, false)[0] - 0.5).abs() < 0.01); + let color = decode(&png, false).unwrap(); + assert!((color.get(0, 0, false)[0] - 0.214).abs() < 0.01); } #[test] diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs index 426562e4..01cd0afe 100644 --- a/crates/image/src/lib.rs +++ b/crates/image/src/lib.rs @@ -300,10 +300,33 @@ pub fn srgb_to_linear(v: f32) -> f32 { if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } } +/// Marker appended to a bitmap resource name asking the resource decoder for the file's values +/// as stored (a data map such as a normal map), instead of sRGB-decoding 8/16-bit color. +const LINEAR_MARK: &str = "\u{1}linear"; + +/// The resource-decoder key for `name`, read as data (`linear`) or as sRGB color. +pub fn resource_key(name: &str, linear: bool) -> String { + if linear { format!("{name}{LINEAR_MARK}") } else { name.to_string() } +} + +/// Split a key made by [`resource_key`] into the resource name and whether it is read as data. +pub fn split_resource_key(key: &str) -> (&str, bool) { + match key.strip_suffix(LINEAR_MARK) { + Some(name) => (name, true), + None => (key, false), + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn resource_keys_round_trip() { + assert_eq!(split_resource_key(&resource_key("n", true)), ("n", true)); + assert_eq!(split_resource_key(&resource_key("n", false)), ("n", false)); + } + #[test] fn sample_wraps_and_clamps() { let img = Image::gray(4, 1, |x, _| x as f32); diff --git a/crates/nodes/src/atomic.rs b/crates/nodes/src/atomic.rs index 7a2bcd64..f7a26daa 100644 --- a/crates/nodes/src/atomic.rs +++ b/crates/nodes/src/atomic.rs @@ -24,6 +24,7 @@ pub(crate) fn defs() -> Vec { .atomic() .generator() .resource("resource", "Bitmap resource") + .choice("colour_space", "Color space", &["sRGB", "Linear (data)"], 0) .color_out() .cook(bitmap), node("blend", "Blend", ATOMIC) @@ -220,7 +221,9 @@ const CHANNEL_SOURCES: &[&str] = fn bitmap(ctx: &Ctx) -> CookResult { let name = ctx.text("resource"); - match (ctx.resource)(name) { + // "Linear (data)" keeps the file's values as stored (normal maps, masks); sRGB decodes color. + let key = materialcraft_image::resource_key(name, ctx.i("colour_space") == 1); + match (ctx.resource)(&key) { Some(img) => Ok(vec![img.resize(ctx.w, ctx.h, ctx.tile)]), None if name.is_empty() => Ok(vec![ctx.gen_color(|u, v| { let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 };