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 e386d125..91b23b62 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -339,7 +339,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/inspect.rs b/crates/engine/src/inspect.rs index c002d4d8..16f9409b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -19,6 +19,8 @@ pub fn session(s: &Session, graph: Option) -> J { "exposed": g.exposed, "presets": g.presets, "inputs": g.inputs, + "inputImages": g.input_images, + "inputImagesLinear": g.input_images_linear, "nodes": g.nodes.iter().map(|n| { let r = cooked.and_then(|c| c.nodes.get(&n.id)); let (ins, outs) = materialcraft_eval::ports(&s.pkg, n); diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index 0f7f51e2..f643429a 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 ), @@ -159,7 +159,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)?; @@ -220,7 +220,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})) }) } @@ -228,7 +235,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)) } @@ -240,7 +247,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)] @@ -276,13 +286,20 @@ mod tests { let png = encode(&Image::filled(4, 4, materialcraft_image::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap(); let res = crate::file_cmds::add_resource(&mut s, "curv.png", png, None).unwrap(); assert!(crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "nope", "resource": res})).is_err()); - crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res})).unwrap(); + crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res, "linear": true})).unwrap(); assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res)); + let inspected = crate::inspect::session(&s, None); + assert_eq!(inspected["graph"]["inputImages"]["curvature"], res); + assert_eq!(inspected["graph"]["inputImagesLinear"], json!(["curvature"])); + let saved = materialcraft_formats::save_package(&s.pkg).unwrap(); + let reopened = materialcraft_formats::load_package(&saved).unwrap(); + assert!(reopened.graphs[s.graph].input_images_linear.contains("curvature")); let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(16), ..Default::default() }).unwrap(); let (m, _) = read_material(&bytes).unwrap(); assert!(m.inputs.iter().any(|i| i.identifier == "curvature" && i.kind == "gray")); assert_eq!(crate::execute(&mut s, "graph.input.unbind", &json!({"identifier": "curvature"})).unwrap(), J::Bool(true)); assert!(s.graph().unwrap().input_images.is_empty()); + assert!(s.graph().unwrap().input_images_linear.is_empty()); } #[test] diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 6be6363f..ef4efb04 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -167,7 +167,7 @@ pub struct Session { redo: Vec, /// Edits with the same key coalesce into one undo step (slider drags). merge_key: Option, - decoded: Arc>>, + decoded: Arc>>, } impl Session { @@ -311,14 +311,15 @@ impl Session { let res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); let memo = self.decoded.clone(); // Free images of resources that were deleted or replaced. - memo.lock().unwrap_or_else(PoisonError::into_inner).retain(|k, _| res.iter().any(|(_, b)| b.content_hash() == *k)); - move |name: &str| { + memo.lock().unwrap_or_else(PoisonError::into_inner).retain(|(k, _), _| res.iter().any(|(_, b)| b.content_hash() == *k)); + move |requested: &str| { + let (name, linear) = materialcraft_image::split_resource_key(requested); let (_, bytes) = res.iter().find(|(n, _)| n == name)?; - let key = bytes.content_hash(); + let key = (bytes.content_hash(), linear); if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { return Some(i.clone()); } - let img = materialcraft_formats::decode(bytes.as_slice()).ok()?; + let img = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?; memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); Some(img) } diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs index de09274a..18cb0e2d 100644 --- a/crates/engine/src/session.test.rs +++ b/crates/engine/src/session.test.rs @@ -11,3 +11,28 @@ mod session_tests { assert_ne!(s.cook_epoch, before); } } + +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: materialcraft_core::ResourceBytes::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/engine/tests/session.rs b/crates/engine/tests/session.rs index 3d019a6e..d50d0680 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -86,7 +86,7 @@ fn package_save_and_open_round_trip() { let small = dir.join("small"); run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); - let img = materialcraft_formats::decode(&std::fs::read(file).unwrap()).unwrap(); + let img = materialcraft_formats::decode(&std::fs::read(file).unwrap(), false).unwrap(); assert_eq!((img.w, img.h), (64, 64)); let _ = std::fs::remove_dir_all(&dir); } @@ -99,7 +99,7 @@ fn export_size_keeps_proportions_and_clamps() { let dims = |s: &Session, size: Value| { let (gi, ext, pattern, depth, size) = materialcraft_engine::file_cmds::export_params(s, &json!({"size": size})).unwrap(); let files = materialcraft_engine::file_cmds::export_outputs(s, gi, &ext, &pattern, depth, size).unwrap(); - files.iter().map(|f| materialcraft_formats::decode(&f.bytes).unwrap()).map(|i| (i.w, i.h)).collect::>() + files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.w, i.h)).collect::>() }; for size in [json!(0), json!(null)] { assert!(dims(&s, size).iter().all(|d| *d == (128, 64))); diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 80f54197..2a5fce79 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -273,7 +273,11 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex) -> C // 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(), graph_stack: opts.graph_stack.clone(), ..*opts }; &bound @@ -814,6 +818,33 @@ mod tests { 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 cache = Mutex::new(Cache::default()); + let c = cook(p, 0, &Options::new(&res), &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)); + } + #[test] fn input_change_recooks_only_readers() { use materialcraft_core::function::{FnGraph, FnNode}; diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index aced96aa..b5e6ad8b 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -171,9 +171,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 { let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Image(e.to_string()))?; if reader.format().is_none() { // TGA has no signature: try it when the format cannot be guessed. @@ -205,7 +206,7 @@ pub fn decode(bytes: &[u8]) -> Result { return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); } let mut data = img.into_rgba32f().into_raw(); - if !float { + if !(float || linear) { for px in data.chunks_exact_mut(4) { for c in px.iter_mut().take(3) { *c = srgb_to_linear(*c); @@ -340,7 +341,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.as_slice()).unwrap(); + let img = decode(q.resources[0].bytes.as_slice(), false).unwrap(); assert!((img.get(0, 0, false)[1] - 0.5).abs() < 0.01); assert!(load_package(b"not a zip").is_err()); } @@ -413,13 +414,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] @@ -480,7 +491,7 @@ mod tests { fn oversized_images_are_refused_before_decoding() { let mut png = Cursor::new(Vec::new()); image::GrayImage::new(8193, 1).write_to(&mut png, image::ImageFormat::Png).unwrap(); - let err = decode(png.get_ref()).unwrap_err().to_string(); + let err = decode(png.get_ref(), false).unwrap_err().to_string(); assert!(err.contains("8192"), "{err}"); } @@ -488,7 +499,7 @@ mod tests { fn tga_still_decodes() { let mut tga = Cursor::new(Vec::new()); image::RgbaImage::new(2, 2).write_to(&mut tga, image::ImageFormat::Tga).unwrap(); - let img = decode(tga.get_ref()).unwrap(); + let img = decode(tga.get_ref(), false).unwrap(); assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); } @@ -496,7 +507,7 @@ mod tests { fn decode_matches_previous_values() { let mut png = Cursor::new(Vec::new()); image::RgbImage::from_pixel(2, 2, image::Rgb([128, 128, 128])).write_to(&mut png, image::ImageFormat::Png).unwrap(); - let img = decode(png.get_ref()).unwrap(); + let img = decode(png.get_ref(), false).unwrap(); let want = srgb_to_linear(128.0 / 255.0); assert!((img.get(1, 1, false)[0] - want).abs() < 1e-4); } diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs index e0be053a..396f1e5a 100644 --- a/crates/image/src/lib.rs +++ b/crates/image/src/lib.rs @@ -302,6 +302,29 @@ pub fn srgb_to_linear(v: f32) -> f32 { if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } } +/// Encode the bitmap name and its requested color space without ambiguity. +/// Plain sRGB names remain readable by simple resource callbacks. +pub fn resource_key(name: &str, linear: bool) -> String { + if linear { + format!("\u{1}L{name}") + } else if name.starts_with('\u{1}') { + format!("\u{1}S{name}") + } else { + name.to_string() + } +} + +/// Split a key made by [`resource_key`] into its name and data-map flag. +pub fn split_resource_key(key: &str) -> (&str, bool) { + if let Some(name) = key.strip_prefix("\u{1}L") { + (name, true) + } else if let Some(name) = key.strip_prefix("\u{1}S") { + (name, false) + } else { + (key, false) + } +} + #[cfg(test)] mod tests { use super::*; @@ -317,6 +340,15 @@ mod tests { } } + #[test] + fn resource_keys_round_trip() { + for name in ["n", "", "\u{1}Lnormal", "\u{1}Sn", "n\u{1}linear"] { + for linear in [false, true] { + assert_eq!(split_resource_key(&resource_key(name, linear)), (name, linear)); + } + } + } + #[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 }; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a6b5ed4b..92ab7325 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -127,7 +127,7 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k |---|---| | `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.mcraft file.exportMaterial {...}` to re-cook at its texture set's resolution with its own values and baked mesh maps | | `file.sendToTextureCraft` | `{graph?}`: export into TextureCraft's library folder (`Documents/TextureCraft/library`), where its shelf lists it | -| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | +| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package; `linear: true` preserves data-map values without sRGB conversion | | `file.open` | opens `.sbs` (by content) and `.mcraft` packages, and a `.mcmat`'s source package, on its graph, with no file name. Returns `warnings`: what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders); also in `session.inspect` as `package.warnings` | | `file.save` | `{path?}`: SBS unless the file is `.mcraft`; `.sbs` is appended when `path` has no package extension |