diff --git a/AGENTS.md b/AGENTS.md index 41d9b45..10f0c90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,7 @@ file first, then `docs/`. ```text crates/ - core image geom L0 document model (package, graphs, nodes, values, function graphs); float images; meshes, BVH, camera + core geom L0 document model (package, graphs, nodes, values, function graphs); meshes, BVH, camera nodes L1 the node library: native primitive definitions + CPU cooks, function evaluator and pattern graphs eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); native .sbs packages, bitmaps, texture export engine render L3 Session + command registry (every action is a command), inspect, samples; the 3D preview renderer (CPU PBR + IBL) diff --git a/Cargo.lock b/Cargo.lock index fb4df87..cf56723 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -832,7 +832,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "rustix 1.1.6", ] @@ -845,7 +845,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -858,12 +858,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -920,7 +920,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "egui", "serde", @@ -930,7 +930,7 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "craft-zip", "serde", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "craft-keymap", "craft-quit", @@ -984,7 +984,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "dispatch2", "egui", @@ -1021,6 +1021,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1033,7 +1042,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1054,7 +1063,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "chrono", "dunce", @@ -1081,7 +1090,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "egui", "objc2 0.6.5", @@ -1112,7 +1121,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d#92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2817,9 +2826,7 @@ dependencies = [ "getrandom 0.3.4", "image", "materialcraft-engine", - "materialcraft-formats", "materialcraft-render", - "rayon", "rmcp", "rustix 1.1.6", "schemars", @@ -2853,11 +2860,11 @@ dependencies = [ name = "materialcraft-engine" version = "0.4.1" dependencies = [ + "craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)", "materialcraft-core", "materialcraft-eval", "materialcraft-formats", "materialcraft-geom", - "materialcraft-image", "materialcraft-nodes", "serde", "serde_json", @@ -2869,9 +2876,9 @@ dependencies = [ name = "materialcraft-eval" version = "0.4.1" dependencies = [ + "craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)", "half", "materialcraft-core", - "materialcraft-image", "materialcraft-nodes", "serde", "serde_json", @@ -2887,14 +2894,14 @@ dependencies = [ "craft-mesh", "craft-mime", "craft-svg", - "craft-texture", + "craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=726ad0f8290bedb6ced60fa06200a6b574f9990d)", + "craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627)", "dds", "flate2", "image", "materialcraft-core", "materialcraft-geom", - "materialcraft-image", "materialcraft-nodes", "roxmltree 0.20.0", "serde", @@ -2915,20 +2922,12 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "materialcraft-image" -version = "0.4.1" -dependencies = [ - "rayon", - "thiserror 2.0.21", -] - [[package]] name = "materialcraft-nodes" version = "0.4.1" dependencies = [ + "craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)", "materialcraft-core", - "materialcraft-image", "rayon", ] @@ -2936,9 +2935,9 @@ dependencies = [ name = "materialcraft-render" version = "0.4.1" dependencies = [ + "craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d)", "materialcraft-core", "materialcraft-geom", - "materialcraft-image", "rayon", ] diff --git a/Cargo.toml b/Cargo.toml index 17f5590..3274bd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,6 @@ resolver = "3" members = [ "crates/core", - "crates/image", "crates/geom", "crates/nodes", "crates/eval", @@ -20,7 +19,6 @@ exclude = ["vendor"] # The web app only builds for wasm32 (trunk); everything else is the default. default-members = [ "crates/core", - "crates/image", "crates/geom", "crates/nodes", "crates/eval", @@ -53,7 +51,6 @@ craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "57288edafdc45552e30481cc649021de446abfa0", features = ["tree-render"] } # internal materialcraft-core = { path = "crates/core" } -materialcraft-image = { path = "crates/image" } materialcraft-geom = { path = "crates/geom" } materialcraft-nodes = { path = "crates/nodes" } materialcraft-eval = { path = "crates/eval" } @@ -76,7 +73,6 @@ dds = { version = "0.2", default-features = false } half = "2" eframe = { version = "0.37", default-features = false } egui = "0.37" -wgpu = "30" rfd = "0.17" rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] } zip = { version = "2", default-features = false, features = ["deflate"] } @@ -90,25 +86,27 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"] cap-std = "4" getrandom = "0.3" # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, -# MIT OR Apache-2.0, every craft-libs crate pinned to one rev. +# MIT OR Apache-2.0, with each dependency pinned to its reviewed revision egui_kittest = "0.37" -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["serde"] } # Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0. -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["egui"] } # Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0. -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" } # The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0. -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["egui"] } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" } # Who draws the window frame, and an app-drawn strip as the title bar: storytold/craft-libs, MIT OR Apache-2.0. -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["egui"] } # Release checks and self-updates for the desktop app: storytold/craft-libs, MIT OR Apache-2.0. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["egui"] } # Atomic persistence, at the suite's current revision. -craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" } # Parse the optional shared font catalog at build time; the font repository is not a dependency. -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" } +# Float image planes and texture sampling for node cooking: storytold/craft-libs, MIT OR Apache-2.0. +craft-texture = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["parallel"] } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] @@ -165,7 +163,7 @@ strip = "debuginfo" opt-level = "s" # Node cooking and the vector math under it run per pixel. -[profile.wasm-release.package.materialcraft-image] +[profile.wasm-release.package.craft-texture] opt-level = 3 [profile.wasm-release.package.materialcraft-nodes] opt-level = 3 diff --git a/README.md b/README.md index 9e9fc64..a2155a8 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scop The [catalog status](docs/node-catalog-parity.md) records implemented behavior and remaining work. Full numerical compatibility and arbitrary SBS interoperability remain unestablished. -**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}` +**Workspace:** `crates/{core, geom, nodes, eval, formats, engine, render, automation, ui-egui}` and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own crate, so the UI can be swapped without touching the engine; [`docs/architecture.md`](docs/architecture.md) explains how it fits together. diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index d56a4fb..b938cb4 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -11,12 +11,10 @@ workspace = true [dependencies] materialcraft-engine = { workspace = true } materialcraft-render = { workspace = true } -materialcraft-formats = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } image = { workspace = true } -rayon = { workspace = true } rmcp = { workspace = true } tokio = { workspace = true } schemars = { workspace = true } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 836fcdf..0ddafa9 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -264,15 +264,15 @@ impl Headless { Ok(Rendered { width: w, height: h, png }) } - fn render_2d(&mut self, o: &RenderOptions, max: u32) -> Result<(u32, u32, Vec), AutomationError> { - let img = match o.node { - Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?, + fn render_2d(&mut self, options: &RenderOptions, maximum_side: u32) -> Result<(u32, u32, Vec), AutomationError> { + let image = match options.node { + Some(n) => self.session.cooked.image(NodeId(n), options.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?, None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?, }; - let (w, h) = (o.width.unwrap_or(img.w).clamp(16, max), o.height.unwrap_or(img.h).clamp(16, max)); - let img = img.resize(w, h, true); - Ok((w, h, img.to_rgba8_display())) + let (w, h) = (options.width.unwrap_or(image.width()).clamp(16, maximum_side), options.height.unwrap_or(image.height()).clamp(16, maximum_side)); + let image = image.resize(w, h, true); + Ok((w, h, image.to_rgba8_display())) } fn render_3d(&mut self, o: &RenderOptions, max: u32) -> (u32, u32, Vec) { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index dfada0c..aca81fb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-nodes = { workspace = true } materialcraft-eval = { workspace = true } materialcraft-formats = { workspace = true } diff --git a/crates/engine/src/decoded_images.rs b/crates/engine/src/decoded_images.rs index 1aa16f8..c4e6e01 100644 --- a/crates/engine/src/decoded_images.rs +++ b/crates/engine/src/decoded_images.rs @@ -1,6 +1,6 @@ use std::collections::{HashMap, HashSet}; -use materialcraft_image::Image; +use craft_texture::Image; const DEFAULT_LIMIT_BYTES: usize = 128 << 20; const MAX_ENTRIES: usize = 128; @@ -68,20 +68,20 @@ impl DecodedImages { } fn bytes(image: &Image) -> usize { - image.data.len().saturating_mul(size_of::()) + image.data().len().saturating_mul(size_of::()) } #[cfg(test)] mod tests { use super::*; - use materialcraft_image::Kind; + use craft_texture::Kind; use std::sync::Arc; #[test] fn repeated_decodes_are_bounded_and_evicted_images_are_released() { let mut cache = DecodedImages::new(128); let image = Image::filled(4, 4, Kind::Gray, [0.5; 4]); - let weak = Arc::downgrade(&image.data); + let weak = Arc::downgrade(image.shared_data()); cache.insert((0, false), image); for key in 1..1_000 { cache.insert((key, key % 2 == 0), Image::filled(4, 4, Kind::Gray, [0.5; 4])); @@ -113,7 +113,7 @@ mod tests { assert!(cache.get(&(1, false)).is_none()); let large = Image::filled(16, 16, Kind::Gray, [0.5; 4]); - let weak = Arc::downgrade(&large.data); + let weak = Arc::downgrade(large.shared_data()); cache.insert((3, false), large); assert!(weak.upgrade().is_none()); diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 5f115af..373d151 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -149,26 +149,27 @@ fn format(s: &mut Session, p: &J) -> Result { }) } -fn cook(s: &mut Session, p: &J) -> Result { - let index = match p.get("graph").filter(|graph| !graph.is_null()) { - None => s.graph, +fn cook(session: &mut Session, parameters: &J) -> Result { + let index = match parameters.get("graph").filter(|graph| !graph.is_null()) { + None => session.graph, Some(graph) => { let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?; - let graph = s.pkg.graph(index)?; + let graph = session.pkg.graph(index)?; if graph.function.is_some() { return Err(bad("graph.cook", "a Function Graph has no outputs to compute")); } + index } }; - let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() }; - let g = s.pkg.graph(index)?; + let cooked = if index != session.graph || boolp(parameters, "full") == Some(true) { session.cook_full(index) } else { session.cook().clone() }; + let graph = session.pkg.graph(index)?; Ok(json!({ "ms": cooked.ms, - "nodes": cooked.nodes.iter().map(|(id, r)| { - let n = g.node(*id).ok(); - json!({"id": id.0, "def": n.map(|n| n.def.clone()), "ms": r.ms, "cached": r.cached, "error": r.error, - "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h])}) + "nodes": cooked.nodes.iter().map(|(id, result)| { + let node = graph.node(*id).ok(); + json!({"id": id.0, "def": node.map(|node| node.def.clone()), "ms": result.ms, "cached": result.cached, "error": result.error, + "size": result.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()])}) }).collect::>(), })) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 884218d..12bcf3a 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -32,7 +32,7 @@ pub fn session(session: &Session, requested_graph: Option) -> J { "error": entry.error, "ms": entry.ms, "cached": entry.cached, "base": entry.base, "baseValues": entry.base_values, "parameters": entry.parameters, "value": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value), - "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.w, image.h]), + "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()]), "kind": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| if image.is_gray() { "gray" } else { "color" }), "mean": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| image.mean()), })); @@ -81,7 +81,7 @@ pub fn session(session: &Session, requested_graph: Option) -> J { "assignments": session.material_preview, "channels": session.material_preview.sources(&session.pkg).into_iter().map(|(channel, source)| { let image = session.material_image(&source); - json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())}) + json!({"channel": channel, "source": source, "size": image.map(|image| [image.width(), image.height()]), "mean": image.map(|image| image.mean())}) }).collect::>(), }, "previewSize": session.preview_size, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3ab4364..003b42a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -88,10 +88,10 @@ pub use color_space::ColorSpace; pub use export_request::ExportRequest; pub use export_size::ExportSize; +pub use craft_texture as image; pub use materialcraft_core as core; pub use materialcraft_eval as eval; pub use materialcraft_formats as formats; -pub use materialcraft_image as image; pub use materialcraft_nodes as nodes; mod engine_error; diff --git a/crates/engine/src/library_preview.rs b/crates/engine/src/library_preview.rs index bb8cb5d..4ba0a2e 100644 --- a/crates/engine/src/library_preview.rs +++ b/crates/engine/src/library_preview.rs @@ -4,8 +4,8 @@ use std::collections::BTreeMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use craft_texture::{Image, Kind}; use materialcraft_core::Package; -use materialcraft_image::{Image, Kind}; use crate::{NodeLibrary, Session}; @@ -32,7 +32,7 @@ impl NodeLibrary { let index = source.graphs.iter().position(|candidate| candidate.function.is_none() && candidate.sbs_path() == graph)?; let size = size.clamp(1, COOKED_SIZE); - // A session links the graph's instances and functions to the library, as an opened package gets + // A session resolves library references just as it does for an opened package let mut session = Session::with_library(Package::clone(source), library.clone()); session.limit_preview_caches(); if cancel.load(Ordering::Relaxed) { @@ -43,7 +43,7 @@ impl NodeLibrary { let decode = session.resource_decoder(); let mut options = materialcraft_eval::Options::new(&decode); - // Thin lines and fine grain vanish when cooked at thumbnail size, so the graph cooks larger and is scaled down + // Cook larger before downsampling so fine detail survives in thumbnails let cooked_size = size.max(COOKED_SIZE); options.max_size = Some(cooked_size); options.cancel = Some(cancel); @@ -60,7 +60,7 @@ impl NodeLibrary { let outputs = materialcraft_eval::outputs(graph, &cooked); let base_color = outputs.iter().find(|(_, usage, _, image)| *usage == "baseColor" && image.is_some()); let image = base_color.or_else(|| outputs.iter().find(|output| output.3.is_some()))?.3?; - (!is_flat(image)).then(|| image.resize(size.min(image.w), size.min(image.h), false)) + (!is_flat(image)).then(|| image.resize(size.min(image.width()), size.min(image.height()), false)) } } @@ -101,8 +101,8 @@ fn sample_inputs(graph: &materialcraft_core::Graph, size: u32) -> BTreeMap bool { let mut low = [f32::INFINITY; 3]; let mut high = [f32::NEG_INFINITY; 3]; - for y in 0..i64::from(image.h) { - for x in 0..i64::from(image.w) { + for y in 0..i64::from(image.height()) { + for x in 0..i64::from(image.width()) { let pixel = image.get(x, y, false); for channel in 0..3 { low[channel] = low[channel].min(pixel[channel]); diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index d262c67..1333e35 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -3,14 +3,14 @@ use std::collections::BTreeMap; use serde_json::{Value as J, json}; +#[cfg(test)] +use craft_texture::Image; use materialcraft_core::ComponentUsage; use materialcraft_core::Graph; #[cfg(any(test, not(target_arch = "wasm32")))] use materialcraft_core::Value; use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Parameter, PresetEntry, VERSION, portable, srgb_usage}; use materialcraft_formats::{Depth, encode}; -#[cfg(test)] -use materialcraft_image::Image; #[cfg(not(target_arch = "wasm32"))] use crate::commands::u64p; @@ -54,64 +54,66 @@ pub(crate) fn specs() -> Vec { pub use crate::MaterialOptions; -/// Cook graph `gi` with `o` and pack it as a portable material (`.mcmat` bytes) -pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result> { - let mut pkg = s.pkg.clone(); - let g = pkg.graph_mut(gi)?; - if let Some(px) = o.size { - let log2 = 31 - px.clamp(16, 8192).leading_zeros(); - g.size = [log2, log2]; +/// Cook `graph_index` with `options` and pack it as a portable material (`.mcmat` bytes) +pub fn material_bytes(session: &Session, graph_index: usize, options: &MaterialOptions) -> Result> { + let mut package = session.pkg.clone(); + let graph = package.graph_mut(graph_index)?; + if let Some(side_pixels) = options.size { + let log2 = 31 - side_pixels.clamp(16, 8192).leading_zeros(); + graph.size = [log2, log2]; } - g.inputs.extend(o.values.clone()); - let g = pkg.graph(gi)?; - let dec = s.resource_decoder(); - let mut opts = materialcraft_eval::Options::new(&dec); - opts.environment = s.environment; - opts.inputs = o.inputs.clone(); - let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache); + graph.inputs.extend(options.values.clone()); + let graph = package.graph(graph_index)?; + let decode = session.resource_decoder(); + let mut cook_options = materialcraft_eval::Options::new(&decode); + cook_options.environment = session.environment; + cook_options.inputs = options.inputs.clone(); + let cooked = materialcraft_eval::cook(&package, graph_index, &cook_options, &session.cache); let mut maps: Vec<(String, Vec)> = Vec::new(); let mut entries = Vec::new(); let mut size = [0, 0]; - for (_, usage, _, img) in materialcraft_eval::outputs(g, &cooked) { - let Some(img) = img else { continue }; + for (_, usage, _, image) in materialcraft_eval::outputs(graph, &cooked) { + let Some(image) = image else { continue }; if usage == "any" || entries.iter().any(|e: &MapEntry| e.usage == usage) { continue; } + let srgb = srgb_usage(usage); let file = format!("maps/{usage}.png"); - maps.push((file.clone(), encode(img, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?)); + maps.push((file.clone(), encode(image, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?)); entries.push(MapEntry { usage: usage.into(), file, color_space: if srgb { "srgb" } else { "linear" }.into() }); - size = [img.w, img.h]; + size = [image.width(), image.height()]; } if entries.is_empty() { return Err(bad( "file.exportMaterial", format!( "graph `{}` has no outputs with a material usage ({})", - g.name, + graph.name, ComponentUsage::ALL.iter().filter(|usage| **usage != ComponentUsage::ANY).map(|usage| usage.id).collect::>().join(", ") ), )); } + let manifest = Manifest { format: FORMAT.into(), version: VERSION, - name: g.name.replace('_', " "), - graph: g.name.clone(), + name: graph.name.replace('_', " "), + graph: graph.name.clone(), size, maps: entries, - parameters: g + parameters: graph .exposed .iter() .filter(|e| portable(&e.default)) - .map(|e| Parameter { param: e.clone(), value: g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) }) + .map(|e| Parameter { param: e.clone(), value: graph.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) }) .collect(), - inputs: image_inputs(g), - presets: g.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(), + inputs: image_inputs(graph), + presets: graph.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(), source: String::new(), }; - let source = materialcraft_formats::sbs::write_sbs(&pkg)?; + let source = materialcraft_formats::sbs::write_sbs(&package)?; Ok(materialcraft_formats::material::write_material(&manifest, &maps, &source)?) } @@ -289,17 +291,24 @@ mod tests { fn binds_preview_images_to_input_nodes() { let mut s = crate::sample_session(); crate::execute(&mut s, "graph.node.add", &json!({"def": "input_grayscale", "params": {"identifier": "curvature"}})).unwrap(); - let png = encode(&Image::filled(4, 4, materialcraft_image::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap(); + let png = encode(&Image::filled(4, 4, craft_texture::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, "linear": true})).unwrap(); + assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res)); + let bytes = materialcraft_formats::sbs::write_sbs(&s.pkg).unwrap(); let reopened = materialcraft_formats::sbs::read_sbs(&bytes, "input.sbs", &|_| None).unwrap().pkg; + assert_eq!(reopened.graphs[s.graph].input_images.get("curvature"), Some(&res)); 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()); @@ -329,7 +338,7 @@ mod tests { .unwrap(); crate::execute(&mut s, "graph.connect", &json!({"from": input, "to": output})).unwrap(); - let png = encode(&Image::filled(16, 16, materialcraft_image::Kind::Color, [128.0 / 255.0; 4]), "png", Depth::U16, false).unwrap(); + let png = encode(&Image::filled(16, 16, craft_texture::Kind::Color, [128.0 / 255.0; 4]), "png", Depth::U16, false).unwrap(); let dir = std::env::temp_dir().join(format!("materialcraft-linear-input-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("normal.png"); @@ -338,23 +347,26 @@ mod tests { let output_path = dir.join("out.mcmat").to_str().unwrap().to_string(); let result = crate::execute(&mut s, "file.exportMaterial", &json!({"path": output_path, "size": 16, "inputs": {"normal": input_path}})); + assert!(result.is_ok()); let bytes = std::fs::read(&output_path).unwrap(); let _ = std::fs::remove_dir_all(&dir); - // The material archive stores maps uncompressed; pull the normal map - // out of its local file header and decode it as linear data. + // The uncompressed archive exposes the normal map after its local file header let name = b"maps/normal.png"; let pos = bytes.windows(name.len()).position(|w| w == name).unwrap(); let header = pos - 30; + assert_eq!(&bytes[header..header + 4], b"PK\x03\x04"); + let name_len = u16::from_le_bytes([bytes[header + 26], bytes[header + 27]]) as usize; let extra_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize; let compressed = u32::from_le_bytes([bytes[header + 18], bytes[header + 19], bytes[header + 20], bytes[header + 21]]) as usize; let start = header + 30 + name_len + extra_len; let map = &bytes[start..start + compressed]; let decoded = decode(map, true).unwrap(); + assert!((decoded.get(0, 0, false)[0] - 128.0 / 255.0).abs() < 1e-3, "data inputs must be decoded as linear"); } } diff --git a/crates/engine/src/material_options.rs b/crates/engine/src/material_options.rs index 2471eff..72dad5b 100644 --- a/crates/engine/src/material_options.rs +++ b/crates/engine/src/material_options.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; /// What to cook a portable material with, over the graph's own values diff --git a/crates/engine/src/material_preview.rs b/crates/engine/src/material_preview.rs index e572cb8..0a79a95 100644 --- a/crates/engine/src/material_preview.rs +++ b/crates/engine/src/material_preview.rs @@ -1,8 +1,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::hash::{Hash, Hasher}; +use craft_texture::Image; use materialcraft_core::{MaterialChannel, Package}; -use materialcraft_image::Image; use serde::{Deserialize, Serialize}; use crate::{MaterialSource, Session}; diff --git a/crates/engine/src/node_library.test.rs b/crates/engine/src/node_library.test.rs index f95e846..49be923 100644 --- a/crates/engine/src/node_library.test.rs +++ b/crates/engine/src/node_library.test.rs @@ -345,7 +345,7 @@ fn library_graphs_cook_previews_from_sample_inputs() { let filter = preview("sbs://blur_hq.sbs", "blur_hq").unwrap(); - assert_eq!((filter.w, filter.h), (32, 32)); + assert_eq!((filter.width(), filter.height()), (32, 32)); assert!(preview("sbs://materials/pbr/bricks_001.sbs", "bricks_001").is_some()); assert!(preview("sbs://noise_bnw_spots_1.sbs", "bnw_spots_1").is_some(), "an FX-Map noise reads the variables its size function sets"); assert!(preview("sbs://blur_hq.sbs", "no_such_graph").is_none()); @@ -362,7 +362,7 @@ fn repeated_library_previews_release_images_and_source_references() { [("sbs://blur_hq.sbs", "blur_hq"), ("sbs://noise_clouds_3_v2.sbs", "clouds_3"), ("sbs://materials/pbr/bricks_001.sbs", "bricks_001")] { let image = NodeLibrary::preview(&library, package, graph, 72).unwrap_or_else(|| panic!("missing preview {package}#{graph}")); - let buffer = Arc::downgrade(&image.data); + let buffer = Arc::downgrade(image.shared_data()); drop(image); assert!(buffer.upgrade().is_none(), "a completed thumbnail must release its image after upload"); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e989796..4e77b22 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -3,9 +3,9 @@ use std::sync::{Arc, Mutex, PoisonError}; +use craft_texture::Image; use materialcraft_core::{Graph, NodeId, Package, ResourceBytes}; use materialcraft_eval::{Cache, Cooked, Options}; -use materialcraft_image::Image; use serde::{Deserialize, Serialize}; use crate::snapshot::Snapshot; @@ -426,29 +426,29 @@ impl Session { /// A decoder for the package's bitmap resources (memoized, shareable with worker threads). pub fn resource_decoder(&self) -> impl Fn(&str) -> Option + Sync + Send + 'static { - let mut res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); - res.extend( + let mut resources: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); + resources.extend( self.pkg .dependencies .iter() .flat_map(|(file, package)| package.resources.iter().map(move |resource| (format!("{file}\0{}", resource.name), resource.bytes.clone()))), ); - let memo = self.decoded.clone(); + let decoded = self.decoded.clone(); // Release decoded images of deleted or replaced resources - let hashes = res.iter().map(|(_, bytes)| bytes.content_hash()).collect(); - memo.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes); + let hashes = resources.iter().map(|(_, bytes)| bytes.content_hash()).collect(); + decoded.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes); move |requested: &str| { - let (name, linear) = materialcraft_image::split_resource_key(requested); - let (_, bytes) = res.iter().find(|(n, _)| n == name)?; + let (name, linear) = craft_texture::split_resource_key(requested); + let (_, bytes) = resources.iter().find(|(name_candidate, _)| name_candidate == name)?; let key = (bytes.content_hash(), linear); - if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { - return Some(i); + if let Some(image) = decoded.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return Some(image); } - let img = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?; - memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); - Some(img) + let image = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?; + decoded.lock().unwrap_or_else(PoisonError::into_inner).insert(key, image.clone()); + Some(image) } } diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs index 9b64c36..e854e08 100644 --- a/crates/engine/src/session.test.rs +++ b/crates/engine/src/session.test.rs @@ -1,6 +1,6 @@ +use craft_texture::{Image, Kind, resource_key}; use materialcraft_core::{Package, Resource}; use materialcraft_formats::{Depth, encode}; -use materialcraft_image::{Image, Kind, resource_key}; use crate::session::Session; @@ -187,13 +187,16 @@ fn a_failed_group_recooks_if_it_cooked_a_temporary_document() { s.preview_size = Some(16); let id = NodeId(execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap()); execute(&mut s, "graph.node.param", &json!({"id": id.0, "param": "color_mode", "value": true})).unwrap(); - let before = s.cook().image(id, 0).unwrap().data.clone(); + let before = s.cook().image(id, 0).unwrap().data().to_vec(); let result: crate::Result<()> = s.group("Temporary", |s| { execute(s, "graph.node.param", &json!({"id": id.0, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]}))?; s.cook(); Err(crate::EngineError::Other("failed".into())) }); + assert!(result.is_err()); + s.cook_if_dirty(); - assert_eq!(s.cooked.image(id, 0).unwrap().data, before); + + assert_eq!(s.cooked.image(id, 0).unwrap().data(), before.as_slice()); } diff --git a/crates/engine/tests/it/atomics.rs b/crates/engine/tests/it/atomics.rs index dc5d7ac..fc13c90 100644 --- a/crates/engine/tests/it/atomics.rs +++ b/crates/engine/tests/it/atomics.rs @@ -59,19 +59,28 @@ fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() { assert!(!text.contains(forbidden)); } let read = read_sbs(&bytes, "atomic_sample.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let mut loaded = Session::new(read.pkg); loaded.preview_size = Some(64); loaded.cook(); + assert_eq!(original.graph().unwrap().connections.len(), loaded.graph().unwrap().connections.len()); + for (before, after) in original.graph().unwrap().nodes.iter().zip(&loaded.graph().unwrap().nodes) { assert_eq!(before.def, after.def); + let result = &loaded.cooked.nodes[&after.id]; + assert!(result.error.is_none(), "{}: {:?}", after.def, result.error); + match (original.cooked.image(before.id, 0), loaded.cooked.image(after.id, 0)) { (Some(before), Some(after)) => { - assert_eq!((before.w, before.h, before.kind), (after.w, after.h, after.kind)); - let error = before.data.iter().zip(after.data.iter()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); + assert_eq!((before.width(), before.height(), before.kind()), (after.width(), after.height(), after.kind())); + + let error = before.data().iter().zip(after.data()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max); + assert!(error < 1e-5, "pixel error {error}"); } (None, None) => assert_eq!(original.cooked.value(before.id, 0), loaded.cooked.value(after.id, 0)), @@ -181,11 +190,11 @@ fn exposed_parameter_binding_remains_live_after_saving() { let mut loaded = Session::new(loaded.pkg); loaded.preview_size = Some(32); loaded.cook(); - let before = loaded.cooked.image(blur, 0).unwrap().data.clone(); + let before = loaded.cooked.image(blur, 0).unwrap().data().to_vec(); execute(&mut loaded, "graph.exposed.set", &json!({"id": "radius", "value": 0.0})).unwrap(); loaded.cook(); - assert_ne!(before, loaded.cooked.image(blur, 0).unwrap().data); + assert_ne!(before.as_slice(), loaded.cooked.image(blur, 0).unwrap().data()); } #[test] diff --git a/crates/engine/tests/it/export_names.rs b/crates/engine/tests/it/export_names.rs index c9c8065..5e4b43c 100644 --- a/crates/engine/tests/it/export_names.rs +++ b/crates/engine/tests/it/export_names.rs @@ -101,10 +101,13 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() { let (mut s, _) = session(); let dir = TempDir::new("unique"); let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 2); + for (name, value) in [("first.png", 0.2), ("second.png", 0.8)] { let image = formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), false).unwrap(); - assert_eq!((image.w, image.h), (16, 16)); + + assert_eq!((image.width(), image.height()), (16, 16)); assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}"); } } diff --git a/crates/engine/tests/it/linked_resources.rs b/crates/engine/tests/it/linked_resources.rs index 2968a80..30f1eb9 100644 --- a/crates/engine/tests/it/linked_resources.rs +++ b/crates/engine/tests/it/linked_resources.rs @@ -45,8 +45,8 @@ fn bundled_voronoi_bitmaps_load_the_shared_resource_and_survive_portable_saving( assert!(cooked.nodes[&node.id].error.is_none()); let image = cooked.image(node.id, 0).unwrap(); - let low = image.data.iter().copied().fold(f32::INFINITY, f32::min); - let high = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let low = image.data().iter().copied().fold(f32::INFINITY, f32::min); + let high = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max); assert!(low.is_finite() && high.is_finite() && high > low); } diff --git a/crates/engine/tests/it/node_library.rs b/crates/engine/tests/it/node_library.rs index c54ddd0..db862f3 100644 --- a/crates/engine/tests/it/node_library.rs +++ b/crates/engine/tests/it/node_library.rs @@ -23,8 +23,8 @@ fn bundled_cloud_and_white_noise_parameter_scopes_cook() { for node in nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "fx_map")) { let image = cooked.image(node.id, 0).unwrap(); - let low = image.data.iter().copied().fold(f32::INFINITY, f32::min); - let high = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let low = image.data().iter().copied().fold(f32::INFINITY, f32::min); + let high = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max); assert!(high - low > 0.05, "{file} lost variation: {low}..{high}"); } @@ -51,14 +51,14 @@ fn bundled_brick_material_cooks_without_missing_functions_or_budget_errors() { for output in outputs { let image = cooked.image(output, 0).unwrap(); - assert!(image.data.iter().all(|value| value.is_finite())); + assert!(image.data().iter().all(|value| value.is_finite())); } // Finite output alone missed flat noise, identical tile values and a half-turn hue error for id in [24, 34, 48, 91] { let image = cooked.image(materialcraft_engine::core::NodeId(id), 0).unwrap(); - let low = image.data.iter().copied().fold(f32::INFINITY, f32::min); - let high = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let low = image.data().iter().copied().fold(f32::INFINITY, f32::min); + let high = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max); assert!(high - low > 0.05, "node {id} lost its variation: {low}..{high}"); diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs index 7c68023..aab2fab 100644 --- a/crates/engine/tests/it/parameter_functions.rs +++ b/crates/engine/tests/it/parameter_functions.rs @@ -25,18 +25,22 @@ fn output_size_function_controls_resolution_and_survives_sbs() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (128, 32)); + + assert_eq!((image.width(), image.height()), (128, 32)); assert!(cooked.nodes[&owner].error.is_none()); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); let loaded = formats::sbs::read_sbs(&bytes, "parameter-functions.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); + let mut reopened = Session::new(loaded.pkg); reopened.preview_size = None; let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id; let cooked = reopened.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (128, 32)); + + assert_eq!((image.width(), image.height()), (128, 32)); } #[test] @@ -90,7 +94,8 @@ fn native_dynamic_output_size_is_not_discarded_on_load() { let cooked = session.cook(); let image = cooked.image(owner, 0).unwrap(); - assert_eq!((image.w, image.h), (64, 32)); + + assert_eq!((image.width(), image.height()), (64, 32)); } #[test] @@ -120,7 +125,7 @@ fn inherited_size_functions_use_nominal_input_size_before_preview_capping() { assert_eq!(cooked.nodes[&owner].error, None); assert_eq!(cooked.nodes[&owner].base.size, [256, 64]); assert_eq!(cooked.nodes[&owner].base_values[&BaseParameter::OutputSize], Value::Int2([1, 0])); - assert_eq!((cooked.image(owner, 0).unwrap().w, cooked.image(owner, 0).unwrap().h), (16, 4)); + assert_eq!((cooked.image(owner, 0).unwrap().width(), cooked.image(owner, 0).unwrap().height()), (16, 4)); command( &mut session, @@ -267,7 +272,7 @@ fn instance_parameter_functions_work_without_stored_literals_and_use_instance_si assert_eq!(result.nodes[&owner].error, None); assert!(result.nodes[&owner].outputs.iter().any(|output| output.as_value() == Some(&Value::Float2([64.0, 32.0])))); assert!((result.image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6); - assert_eq!((result.image(owner, 0).unwrap().w, result.image(owner, 0).unwrap().h), (64, 32)); + assert_eq!((result.image(owner, 0).unwrap().width(), result.image(owner, 0).unwrap().height()), (64, 32)); assert!(!session.graph().unwrap().node(owner).unwrap().params.contains_key("amount")); let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); @@ -394,7 +399,8 @@ fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensi let cooked = session.cook(); let image = cooked.image(blend, 0).unwrap(); - assert_eq!((image.w, image.h), (16, 16)); + + assert_eq!((image.width(), image.height()), (16, 16)); assert_eq!(cooked.nodes[&blend].base.size, [32, 32]); assert_eq!(cooked.nodes[&output].base.size, [32, 32]); } diff --git a/crates/engine/tests/it/pattern_graph.rs b/crates/engine/tests/it/pattern_graph.rs index 37895bf..db57904 100644 --- a/crates/engine/tests/it/pattern_graph.rs +++ b/crates/engine/tests/it/pattern_graph.rs @@ -85,7 +85,7 @@ fn dynamic_roughness_survives_native_saving_and_invalidates_the_cook_cache() { let cached = materialcraft_engine::eval::cook(&package, 0, &options, &cache); assert!(cached.nodes[&owner].cached); - assert_eq!(cached.image(owner, 0).unwrap().data, result.image(owner, 0).unwrap().data); + assert_eq!(cached.image(owner, 0).unwrap().data(), result.image(owner, 0).unwrap().data()); } } } diff --git a/crates/engine/tests/it/subgraph_seed.rs b/crates/engine/tests/it/subgraph_seed.rs index 070f5fc..c125139 100644 --- a/crates/engine/tests/it/subgraph_seed.rs +++ b/crates/engine/tests/it/subgraph_seed.rs @@ -23,23 +23,31 @@ fn grouping_noise_preserves_pixels_seed_and_undo() { let before_graphs = s.pkg.graphs.clone(); let before = s.cook().image(output, 0).unwrap().clone(); run(&mut s, "graph.createFromSelection", json!({"name": "Grouped_noise"})); - // Force an actual cook instead of relying on the pre-grouping cache entry. + + // Force an actual cook instead of relying on the pre-grouping cache entry s.cache.lock().unwrap().clear(); let after = s.cook().image(output, 0).unwrap().clone(); - assert!(before.data == after.data, "grouping changed the material at graph seed {seed}"); - assert_eq!((after.w, after.h), (64, 32)); + + assert!(before.data() == after.data(), "grouping changed the material at graph seed {seed}"); + assert_eq!((after.width(), after.height()), (64, 32)); assert_eq!(s.pkg.graphs[1].seed, seed); + let grouped_graphs = s.pkg.graphs.clone(); run(&mut s, "edit.undo", json!({})); + assert_eq!(s.pkg.graphs, before_graphs); - assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.pkg.graphs, grouped_graphs); - assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data()); + let bytes = formats::sbs::write_sbs(&s.pkg).unwrap(); let mut reopened = Session::new(formats::sbs::read_sbs(&bytes, "seed.sbs", &|_| None).unwrap().pkg); reopened.preview_size = None; let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id; - assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data, before.data); + + assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), before.data()); } } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index b440261..c2c0a7a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -79,15 +79,21 @@ fn package_save_and_open_round_trip() { let before = s.pkg.clone(); run(&mut s, "file.newPackage", json!({})); run(&mut s, "file.open", json!({"path": path.to_str().unwrap()})); + assert_eq!(s.pkg.graphs[0].nodes.len(), before.graphs[0].nodes.len()); + let out = dir.join("tex"); let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8})); + assert_eq!(r["files"].as_array().unwrap().len(), 1); + 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(), false).unwrap(); - assert_eq!((img.w, img.h), (64, 64)); + + assert_eq!((img.width(), img.height()), (64, 64)); + let _ = std::fs::remove_dir_all(&dir); } @@ -101,7 +107,7 @@ fn export_size_keeps_proportions_and_clamps() { let dims = |s: &Session, size: Value| { let request = ExportRequest::from_params(s, &json!({"size": size})).unwrap(); let files = materialcraft_engine::file_cmds::export_outputs(s, &request).unwrap(); - files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.w, i.h)).collect::>() + files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.width(), i.height())).collect::>() }; let parsed = |s: &Session, size: Value| ExportRequest::from_params(s, &json!({"size": size})).map(|request| request.size); @@ -113,11 +119,13 @@ fn export_size_keeps_proportions_and_clamps() { assert_eq!(parsed(&s, json!(0)).unwrap(), None); assert_eq!(parsed(&s, json!(u64::MAX)).unwrap(), Some(ExportSize::LargerSide(u32::MAX))); assert_eq!(parsed(&s, json!([1, u64::MAX])).unwrap(), Some(ExportSize::Exact([1, u32::MAX]))); + for invalid in [json!("large"), json!([64]), json!([64, "wide"]), json!([64, 64, 64])] { assert!(parsed(&s, invalid.clone()).is_err(), "{invalid}"); } s.pkg.graphs[0].size = [u32::MAX, u32::MAX]; + assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32))); assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (16, 8192)), "sides clamp to 16..8192"); } @@ -376,17 +384,20 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() { #[test] fn reimported_bitmap_shows_new_pixels() { + use craft_texture::{Image, Kind}; use materialcraft_formats::{Depth, encode}; - use materialcraft_image::{Image, Kind}; let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap(); let (dark, light) = (bmp(0.1), bmp(0.9)); + assert_eq!(dark.len(), light.len(), "same-size files are the case under test"); + let mut s = sample_session(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap(); - let before = s.resource_decoder()("tex").unwrap().data[0]; + let before = s.resource_decoder()("tex").unwrap().data()[0]; s.undo(); materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap(); - let after = s.resource_decoder()("tex").unwrap().data[0]; + let after = s.resource_decoder()("tex").unwrap().data()[0]; + assert!(after - before > 0.5, "{before} -> {after}"); } @@ -422,7 +433,7 @@ fn a_wire_splits_with_a_reroute_dot_and_deletes() { #[test] fn every_template_is_opaque_in_the_3d_view() { - // The 3D view sees through a base color whose alpha is below one: the templates must not + // Template base colors must stay opaque in the 3D view let mut s = sample_session(); s.preview_size = Some(64); for (id, _) in materialcraft_engine::samples::TEMPLATES { @@ -430,7 +441,8 @@ fn every_template_is_opaque_in_the_3d_view() { s.cook(); for (usage, img) in s.material_maps() { if usage == "baseColor" && !img.is_gray() { - let min = img.data.chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); + let min = img.data().chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min); + assert!(min >= 0.999, "{id}: base color alpha goes down to {min}"); } } diff --git a/crates/eval/Cargo.toml b/crates/eval/Cargo.toml index 7aff613..a5ddc9f 100644 --- a/crates/eval/Cargo.toml +++ b/crates/eval/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-nodes = { workspace = true } half = { workspace = true } serde_json = { workspace = true } diff --git a/crates/eval/src/cache.test.rs b/crates/eval/src/cache.test.rs index bbbf4a3..0e26792 100644 --- a/crates/eval/src/cache.test.rs +++ b/crates/eval/src/cache.test.rs @@ -1,5 +1,5 @@ use super::*; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; fn output(side: u32) -> Arc> { Arc::new(vec![NodeOutput::Image(Image::filled(side, side, Kind::Gray, [0.5; 4]))]) diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index f910960..40e0b74 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -1,6 +1,6 @@ use crate::{Cache, identifier}; +use craft_texture::Image; use materialcraft_core::{Node, Package, Value}; -use materialcraft_image::Image; use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Mutex}; @@ -8,21 +8,21 @@ use std::sync::{Arc, Mutex}; const MAX_INPUT_FINGERPRINTS: usize = 128; pub(crate) fn image_key(image: &Image, cache: &Mutex) -> u64 { - let buffer_id = Arc::as_ptr(&image.data) as usize; - let shape = (image.w, image.h, image.kind.channels()); + let buffer_id = Arc::as_ptr(image.shared_data()) as usize; + let shape = (image.width(), image.height(), image.channels()); if let Some(key) = cache .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .input_hashes .get(&buffer_id) - .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, &image.data) && saved.shape == shape).map(|_| saved.key)) + .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, image.shared_data()) && saved.shape == shape).map(|_| saved.key)) { - return key ^ hash_of(&image.integer_sampling); + return key ^ hash_of(&image.integer_sampling()); } let mut hasher = DefaultHasher::new(); - (shape, image.data.len()).hash(&mut hasher); - for value in image.data.iter() { + (shape, image.data().len()).hash(&mut hasher); + for value in image.data() { value.to_bits().hash(&mut hasher); } @@ -35,8 +35,8 @@ pub(crate) fn image_key(image: &Image, cache: &Mutex) -> u64 { } } - cache.input_hashes.insert(buffer_id, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(&image.data), shape, key }); - key ^ hash_of(&image.integer_sampling) + cache.input_hashes.insert(buffer_id, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(image.shared_data()), shape, key }); + key ^ hash_of(&image.integer_sampling()) } pub(crate) fn hash_of(value: &impl Hash) -> u64 { diff --git a/crates/eval/src/cooked.rs b/crates/eval/src/cooked.rs index c64675b..3c7e075 100644 --- a/crates/eval/src/cooked.rs +++ b/crates/eval/src/cooked.rs @@ -1,6 +1,6 @@ use crate::NodeResult; +use craft_texture::Image; use materialcraft_core::NodeId; -use materialcraft_image::Image; use std::collections::BTreeMap; /// Results of a cook, by node diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index 9f1b364..1013b2e 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -1,7 +1,7 @@ use crate::{Cache, Cooked, Options, now_ms}; use crate::{node_execution::cook_node, prepared_graph::PreparedGraph}; +use craft_texture::Image; use materialcraft_core::{Package, Value}; -use materialcraft_image::Image; use std::{ collections::BTreeMap, sync::{Mutex, atomic::Ordering}, @@ -19,7 +19,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu .input_images .iter() .filter_map(|(id, resource)| { - Some((id.clone(), (options.resource)(&materialcraft_image::resource_key(resource, graph.input_images_linear.contains(id)))?)) + Some((id.clone(), (options.resource)(&craft_texture::resource_key(resource, graph.input_images_linear.contains(id)))?)) }) .collect(); inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone()))); @@ -47,6 +47,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu cooked.cancelled = true; break; } + let Some(node) = prepared.index.node(id) else { continue }; let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache); diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index db0fd83..d11e671 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -37,71 +37,76 @@ pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool } pub(crate) fn cook_instance( - pkg: &Package, - gi: usize, + package: &Package, + graph_index: usize, node: &Node, - in_ports: &[Port], - out_ports: &[Port], + input_ports: &[Port], + output_ports: &[Port], inputs: &[Option<&NodeOutput>], params: &BTreeMap, size: (u32, u32), base: crate::resolved_base_parameters::ResolvedBaseParameters, - opts: &Options, + options: &Options, cache: &Mutex, ) -> Result, String> { - if opts.depth >= MAX_DEPTH { + if options.depth >= MAX_DEPTH { return Err("graph instances nest too deep (does a graph use itself?)".into()); } - let registry = opts.registry.unwrap_or(pkg); - let (source, sub_gi, sub) = resolve(registry, pkg, node).ok_or("the instanced graph does not exist")?; - let identity = std::ptr::from_ref(sub) as usize; - if pkg.graphs.get(gi).is_some_and(|graph| std::ptr::eq(graph, sub)) || opts.graph_stack.contains(&identity) { - return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); + + let registry = options.registry.unwrap_or(package); + let (source, source_graph_index, source_graph) = resolve(registry, package, node).ok_or("the instanced graph does not exist")?; + let identity = std::ptr::from_ref(source_graph) as usize; + if package.graphs.get(graph_index).is_some_and(|graph| std::ptr::eq(graph, source_graph)) || options.graph_stack.contains(&identity) { + return Err(format!("graph `{}` uses itself through a graph instance", source_graph.name)); } - if sub.function.is_some() || !sub.nodes.iter().any(|node| node.def == "output") { + + if source_graph.function.is_some() || !source_graph.nodes.iter().any(|node| node.def == "output") { return Err("the referenced graph must be a main graph with an output".into()); } - let root_resource = opts.resource_root.unwrap_or(opts.resource); + + let root_resource = options.resource_root.unwrap_or(options.resource); let resource = |name: &str| match &node.instance { Some(instance) if !instance.package.is_empty() => { - let (name, linear) = materialcraft_image::split_resource_key(name); - root_resource(&materialcraft_image::resource_key(&format!("{}\0{name}", instance.package), linear)) + let (name, linear) = craft_texture::split_resource_key(name); + root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear)) } - _ => (opts.resource)(name), + _ => (options.resource)(name), }; - let mut o = Options::new(&resource); - o.environment = opts.environment; - o.parent_tiling = Some(base.tiling); - o.parent_pixel_ratio = Some(base.pixel_ratio); - o.parent_base = Some(base); - o.registry = Some(registry); - o.resource_root = Some(root_resource); - o.max_size = opts.max_size; - o.cancel = opts.cancel; - o.depth = opts.depth + 1; - o.graph_stack = opts.graph_stack.clone(); - o.graph_stack.push(identity); - o.only = Some(sub.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); - o.inputs = in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect(); - o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); - o.overrides.extend(in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone())))); - let cooked = cook(source, sub_gi, &o, cache); + let mut source_options = Options::new(&resource); + source_options.environment = options.environment; + source_options.parent_tiling = Some(base.tiling); + source_options.parent_pixel_ratio = Some(base.pixel_ratio); + source_options.parent_base = Some(base); + source_options.registry = Some(registry); + source_options.resource_root = Some(root_resource); + source_options.max_size = options.max_size; + source_options.cancel = options.cancel; + source_options.depth = options.depth + 1; + source_options.graph_stack = options.graph_stack.clone(); + source_options.graph_stack.push(identity); + source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); + source_options.inputs = input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect(); + source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + source_options.overrides.extend(input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone())))); + let cooked = cook(source, source_graph_index, &source_options, cache); if cooked.cancelled { return Err("cancelled".into()); } + if let Some(error) = cooked.nodes.values().find_map(|result| result.error.as_deref()) { - return Err(format!("{}: {error}", sub.name)); + return Err(format!("{}: {error}", source_graph.name)); } - out_ports + + output_ports .iter() - .map(|p| { - let output = sub + .map(|port| { + let output = source_graph .nodes .iter() - .find(|n| n.def == "output" && identifier(n) == p.id) + .find(|candidate| candidate.def == "output" && identifier(candidate) == port.id) .and_then(|node| cooked.nodes.get(&node.id)) .and_then(|result| result.outputs.first()) - .ok_or_else(|| format!("the source output `{}` is missing", p.id))?; + .ok_or_else(|| format!("the source output `{}` is missing", port.id))?; Ok(match output { NodeOutput::Image(image) => NodeOutput::Image(image.resize(size.0, size.1, true)), NodeOutput::Value(value) => NodeOutput::Value(value.clone()), diff --git a/crates/eval/src/graph_output.rs b/crates/eval/src/graph_output.rs index e96e0ff..46f0862 100644 --- a/crates/eval/src/graph_output.rs +++ b/crates/eval/src/graph_output.rs @@ -9,7 +9,7 @@ pub fn output_usage(node: &Node) -> &'static str { }; ComponentUsage::from_index(index).id } -use materialcraft_image::Image; +use craft_texture::Image; /// The graph's output nodes with their usage id and image, in node order pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> { diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index b18a509..faa2964 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -6,8 +6,8 @@ use crate::{ prepared_graph::PreparedGraph, value_execution::evaluate_value, }; +use craft_texture::{Image, Kind}; use materialcraft_core::{Node, Package, Value}; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find}; use std::{ collections::BTreeMap, @@ -177,7 +177,7 @@ pub(crate) fn cook_node( } else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) { incoming.first().copied().flatten().cloned().map(|output| vec![output]).ok_or("missing value input".into()) } else if let Some(image) = input_image { - let mut image = if node.def == "input_grayscale" && image.kind == Kind::Color { + let mut image = if node.def == "input_grayscale" && image.kind() == Kind::Color { // Grayscale bridges use equal RGB weights and preserve fused float order let weight = 1.0 / 3.0; image.map(Kind::Gray, |pixel| [pixel[2].mul_add(weight, pixel[1].mul_add(weight, pixel[0] * weight)), 0.0, 0.0, 0.0]) @@ -189,12 +189,12 @@ pub(crate) fn cook_node( // Bound resources clamp edges through stored factor-two levels // Preserve resampling and storage conversion for HDR bridges - let resized = image.w != w || image.h != h; - while image.w != w || image.h != h { + let resized = image.width() != w || image.height() != h; + while image.width() != w || image.height() != h { let next = |current: u32, target: u32| { if current < target { current.saturating_mul(2).min(target) } else { current.div_ceil(2).max(target) } }; - image = crate::output_precision::apply(image.resize(next(image.w, w), next(image.h, h), false), base.format); + image = crate::output_precision::apply(image.resize(next(image.width(), w), next(image.height(), h), false), base.format); } // Resized inputs already store the final level at the declared precision diff --git a/crates/eval/src/node_output.rs b/crates/eval/src/node_output.rs index d9c6f0e..15d6e66 100644 --- a/crates/eval/src/node_output.rs +++ b/crates/eval/src/node_output.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; #[derive(Clone, Debug, PartialEq)] pub enum NodeOutput { @@ -24,7 +24,7 @@ impl NodeOutput { pub(crate) fn memory_bytes(&self) -> usize { match self { - Self::Image(image) => image.data.len().saturating_mul(size_of::()), + Self::Image(image) => image.data().len().saturating_mul(size_of::()), Self::Value(Value::Text(text)) => size_of::().saturating_add(text.len()), Self::Value(_) => size_of::(), } diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index 8505d4d..9beb3f0 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::{NodeId, Value}; -use materialcraft_image::Image; use std::collections::BTreeMap; use std::sync::atomic::AtomicBool; diff --git a/crates/eval/src/output_precision.rs b/crates/eval/src/output_precision.rs index ec82772..9b1a240 100644 --- a/crates/eval/src/output_precision.rs +++ b/crates/eval/src/output_precision.rs @@ -1,43 +1,61 @@ +use craft_texture::{Image, Limits}; use materialcraft_core::OutputFormat; -use materialcraft_image::Image; use std::sync::Arc; -pub(crate) fn apply(mut image: Image, format: OutputFormat) -> Image { +pub(crate) fn apply(image: Image, format: OutputFormat) -> Image { const HALF_FLOAT_MAX: f32 = 65504.0; const U8_FIXED_SCALE: f64 = 4096.0; const U16_FIXED_SCALE: f64 = 1_048_576.0; - image.integer_sampling = integer_sampling(format); + let integer = integer_sampling(format); if format == OutputFormat::F16 { - for pixel in Arc::make_mut(&mut image.data) { + return with_pixels(image, integer, |pixel| { // Half-float storage saturates finite overflow and truncates toward zero // Leaving the f32 unconverted changes every downstream read and export let value = pixel.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX); let rounded = half::f16::from_f32(value); *pixel = if rounded.to_f32().abs() > value.abs() { half::f16::from_bits(rounded.to_bits().saturating_sub(1)).to_f32() } else { rounded.to_f32() }; - } - - return image; + }); } let (fraction, maximum) = match format { OutputFormat::U8 => (U8_FIXED_SCALE, f64::from(u8::MAX)), OutputFormat::Inherit | OutputFormat::U16 => (U16_FIXED_SCALE, f64::from(u16::MAX)), - OutputFormat::F16 | OutputFormat::F32 => return image, + OutputFormat::F16 | OutputFormat::F32 => return image.with_integer_sampling(integer), }; - for pixel in Arc::make_mut(&mut image.data) { + with_pixels(image, integer, |pixel| { // Integer outputs retain four fractional guard bits before conversion // Halfway-down rounding affects constants and downstream blends let value = if pixel.is_nan() { 0.0 } else { f64::from(*pixel).clamp(0.0, 1.0) }; let fixed = (value * fraction).floor() / fraction; let integer = (fixed * maximum - 0.5).ceil() as u32; *pixel = integer as f32 / maximum as f32; - } - - image + }) } pub(crate) fn integer_sampling(format: OutputFormat) -> bool { matches!(format, OutputFormat::Inherit | OutputFormat::U8 | OutputFormat::U16) } + +/// `image` with `convert` applied to every float and the integer-sampling flag set. The buffer is +/// changed in place when no other image shares it, and copied once otherwise. +fn with_pixels(image: Image, integer_sampling: bool, convert: impl Fn(&mut f32)) -> Image { + let (width, height, kind) = (image.width(), image.height(), image.kind()); + + // Limits that admit any valid image, so one made with raised limits keeps its size + let mut limits = Limits::default(); + limits.max_side = u32::MAX; + limits.max_pixels = u64::MAX; + limits.max_bytes = u64::MAX; + + let mut data = Arc::clone(image.shared_data()); + drop(image); + + Arc::make_mut(&mut data).iter_mut().for_each(convert); + + // `data` keeps the size and kind of a valid image, so `from_data` accepts it + Image::from_data(width, height, kind, data, &limits) + .unwrap_or_else(|_| Image::filled(width, height, kind, [0.0; 4])) + .with_integer_sampling(integer_sampling) +} diff --git a/crates/eval/src/resource_decoder.rs b/crates/eval/src/resource_decoder.rs index 7ddbefa..0ec3781 100644 --- a/crates/eval/src/resource_decoder.rs +++ b/crates/eval/src/resource_decoder.rs @@ -1,4 +1,4 @@ -use materialcraft_image::Image; +use craft_texture::Image; /// Decodes an image resource by name within the current package pub type ResourceDecoder<'a> = dyn Fn(&str) -> Option + Sync + 'a; diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 3f6eb6a..2892244 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -1,6 +1,6 @@ use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach}; +use craft_texture::{Image, Kind, Limits}; use materialcraft_core::{NodeId, Package, Value}; -use materialcraft_image::{Image, Kind}; use std::sync::Mutex; use std::sync::atomic::Ordering; @@ -32,7 +32,7 @@ fn cooks_and_caches() { let a = cook(&p, 0, &opts, &cache); assert!(a.nodes.values().all(|r| r.error.is_none() && !r.cached)); - assert_eq!(a.image(out, 0).map(|i| (i.w, i.h)), Some((64, 64))); + assert_eq!(a.image(out, 0).map(|i| (i.width(), i.height())), Some((64, 64))); // Same graph: everything from the cache let b = cook(&p, 0, &opts, &cache); @@ -121,8 +121,9 @@ fn hostile_param_is_clamped_before_cooking() { p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30)); let cache = Mutex::new(Cache::default()); let c = cook(&p, 0, &Options::new(&no_res), &cache); + assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((64, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((64, 64))); } #[test] @@ -134,7 +135,8 @@ fn preview_cap_and_unknown_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(out, 0).map(|i| i.w), Some(128)); + + assert_eq!(c.image(out, 0).map(|i| i.width()), Some(128)); assert!(c.nodes[&bad].error.is_some()); } @@ -168,7 +170,7 @@ fn graph_instances_cook_their_subgraph() { let c = cook(&p, 0, &Options::new(&no_res), &cache); let img = c.image(inst, 0).unwrap(); - assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]); + assert!((img.data()[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data()[0]); assert!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); } @@ -298,14 +300,14 @@ fn input_nodes_read_bound_preview_images() { let c = cook(&p, 0, &Options::new(&res), &cache); let img = c.image(o, 0).unwrap(); - assert!(img.is_gray() && (img.data[0] - 0.8).abs() < 1e-4, "bound image, as gray"); + assert!(img.is_gray() && (img.data()[0] - 0.8).abs() < 1e-4, "bound image, as gray"); // The caller's image wins over the bound one let mut opts = Options::new(&res); opts.inputs.insert("curvature".into(), Image::filled(4, 4, Kind::Gray, [0.1; 4])); let c = cook(&p, 0, &opts, &cache); - assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); + assert!((c.image(o, 0).unwrap().data()[0] - 0.1).abs() < 1e-4); } #[test] @@ -377,20 +379,29 @@ use std::sync::Arc; #[test] fn cached_input_fingerprint_tracks_copy_on_write_and_shape() { let cache = Mutex::new(Cache::default()); - let mut image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); + let image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); let first = image_key(&image, &cache); + assert_eq!(image_key(&image, &cache), first); - Arc::make_mut(&mut image.data)[1] = 1.0; + + let mut data = image.data().to_vec(); + data[1] = 1.0; + let image = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); let changed = image_key(&image, &cache); + assert_ne!(changed, first); - image.w = 64; - image.h = 256; + + // The same buffer read as another shape + let image = Image::from_data(64, 256, Kind::Gray, Arc::clone(image.shared_data()), &Limits::default()).unwrap(); let reshaped = image_key(&image, &cache); + assert_ne!(reshaped, changed); cache.lock().unwrap().clear(); + assert_eq!(image_key(&image, &cache), reshaped); } + #[test] fn preview_cap_does_not_compound_downscaling() { let (mut p, noise, blur, out) = sample(); @@ -400,10 +411,12 @@ fn preview_cap_does_not_compound_downscaling() { let mut opts = Options::new(&no_res); opts.max_size = Some(512); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((512, 512))); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 128))); - assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 128))); + + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((512, 512))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 128))); + assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 128))); } + #[test] fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { let (mut p, noise, blur, out) = sample(); @@ -414,10 +427,12 @@ fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { let mut opts = Options::new(&no_res); opts.max_size = Some(128); let c = cook(&p, 0, &opts, &cache); - assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((128, 64))); - assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 64))); - assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 64))); + + assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((128, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 64))); + assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 64))); } + #[test] fn changed_unsampled_input_recooks() { let mut g = Graph::new("g"); @@ -430,19 +445,24 @@ fn changed_unsampled_input_recooks() { opts.inputs.insert("input".into(), image.clone()); let cache = Mutex::new(Cache::default()); let first = cook(&p, 0, &opts, &cache); + assert!(!first.nodes[&input].cached); - let mut changed = image; - Arc::make_mut(&mut changed.data)[1] = 1.0; + + let mut data = image.data().to_vec(); + data[1] = 1.0; + let changed = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap(); opts.inputs.insert("input".into(), changed); let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&input].cached); - assert_eq!(second.image(input, 0).unwrap().data[1], 1.0); + assert_eq!(second.image(input, 0).unwrap().data()[1], 1.0); } + #[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); + let (name, linear) = craft_texture::split_resource_key(k); (name == "m").then(|| Image::filled(4, 4, Kind::Color, [if linear { 0.5 } else { 0.2 }; 4])) }; @@ -459,7 +479,7 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() { 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]) + (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"); @@ -522,22 +542,31 @@ fn bound_input_image_linear_flag_change_recooks_instance() { p.graphs = vec![top, sub]; p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100]))); let res = |k: &str| { - let (name, linear) = materialcraft_image::split_resource_key(k); + let (name, linear) = craft_texture::split_resource_key(k); (name == "curv").then(|| Image::filled(4, 4, Kind::Gray, [if linear { 0.5 } else { 0.2 }; 4])) }; let cache = Mutex::new(Cache::default()); let opts = Options::new(&res); let first = cook(&p, 0, &opts, &cache); + assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error); assert!(!first.nodes[&inst].cached); - let first_value = first.image(inst, 0).unwrap().data[0]; + + let first_value = first.image(inst, 0).unwrap().data()[0]; + assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}"); + let second = cook(&p, 0, &opts, &cache); + assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache"); + p.graphs[1].input_images_linear.insert("in".into()); let third = cook(&p, 0, &opts, &cache); + assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance"); - let third_value = third.image(inst, 0).unwrap().data[0]; + + let third_value = third.image(inst, 0).unwrap().data()[0]; + assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); } @@ -620,7 +649,7 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() { assert_eq!(result.error, None, "{definition}"); assert_eq!(result.base.size, [64, 32], "{definition}, dynamic: {dynamic}"); - assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((16, 8))); + assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((16, 8))); assert_eq!(result.base.seed, 0); assert_eq!(result.base.format, OutputFormat::F32); assert_eq!(result.base.tiling, [false, true]); @@ -639,7 +668,7 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() { assert_eq!(cooked.nodes[&generator].error, None); assert_eq!(cooked.nodes[&generator].base.size, cooked.nodes[&background].base.size); - assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((8, 16))); + assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((8, 16))); } } } diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs index 6ed651c..9813f85 100644 --- a/crates/eval/src/value_execution.rs +++ b/crates/eval/src/value_execution.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; pub(crate) fn evaluate_value( diff --git a/crates/eval/tests/filter_tiling.rs b/crates/eval/tests/filter_tiling.rs index 2978b00..4e76a42 100644 --- a/crates/eval/tests/filter_tiling.rs +++ b/crates/eval/tests/filter_tiling.rs @@ -1,6 +1,6 @@ +use craft_texture::Image; use materialcraft_core::{Graph, OutputFormat, Package, ParameterInheritance, Value}; use materialcraft_eval::{Cache, Options, cook}; -use materialcraft_image::Image; use std::sync::Mutex; #[test] diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 5c564a1..f11dc14 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -13,7 +13,7 @@ craft-mime = { workspace = true } craft-xml = { workspace = true } craft-mcmat = { workspace = true } materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } materialcraft-geom = { workspace = true } materialcraft-nodes = { workspace = true } craft-mesh = { workspace = true } diff --git a/crates/formats/examples/sbs_library_build/tests.rs b/crates/formats/examples/sbs_library_build/tests.rs index 37aa4aa..592af38 100644 --- a/crates/formats/examples/sbs_library_build/tests.rs +++ b/crates/formats/examples/sbs_library_build/tests.rs @@ -152,11 +152,11 @@ fn library_art_is_decodable_without_reading_source_assets() { let bytes = resources::load(key).unwrap(); let image = materialcraft_formats::decode(&bytes, true).unwrap(); - assert!(image.w > 0 && image.h > 0); - assert!(image.data.iter().all(|value| value.is_finite())); + assert!(image.width() > 0 && image.height() > 0); + assert!(image.data().iter().all(|value| value.is_finite())); - let min = image.data.iter().copied().fold(f32::INFINITY, f32::min); - let max = image.data.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let min = image.data().iter().copied().fold(f32::INFINITY, f32::min); + let max = image.data().iter().copied().fold(f32::NEG_INFINITY, f32::max); assert!(max > min, "constant replacement {key}"); } diff --git a/crates/formats/src/dds_image.rs b/crates/formats/src/dds_image.rs index 2ff4d0e..84248a6 100644 --- a/crates/formats/src/dds_image.rs +++ b/crates/formats/src/dds_image.rs @@ -1,5 +1,5 @@ use crate::{FormatError, Result}; -use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use craft_texture::{Image, Kind, Limits, MAX_SIDE, srgb_to_linear}; pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result { let error = |message: String| FormatError::Image(message); @@ -18,5 +18,5 @@ pub(crate) fn decode(bytes: &[u8], linear: bool) -> Result { } } - Ok(Image { w: decoded.width, h: decoded.height, kind: Kind::Color, integer_sampling: false, data: std::sync::Arc::new(data) }) + Image::from_data(decoded.width, decoded.height, Kind::Color, data, &Limits::default()).map_err(|e| error(e.to_string())) } diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index edac3d0..a4db566 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -1,7 +1,6 @@ use crate::{Depth, FormatError, Result, guard}; -use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear}; +use craft_texture::{Image, Kind, Limits, MAX_SIDE, linear_to_srgb, srgb_to_linear}; use std::io::Cursor; -use std::sync::Arc; /// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale files stay grayscale) pub fn decode(bytes: &[u8], linear: bool) -> Result { @@ -9,7 +8,10 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { return guard(|| crate::dds_image::decode(bytes, linear), || FormatError::Image("DDS decoder failed".into())); } - if std::str::from_utf8(bytes.get(..bytes.len().min(4096)).unwrap_or_default()).is_ok_and(|text| text.contains(" Result { let mut limits = image::Limits::default(); limits.max_image_width = Some(MAX_SIDE); limits.max_image_height = Some(MAX_SIDE); - limits.max_alloc = Some(1 << 30); + limits.max_alloc = Some(MAX_DECODE_BYTES); reader.limits(limits); Ok(reader) }; @@ -36,16 +38,16 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels"))); } - let img = guard(|| open()?.decode().map_err(image_error), failed)?; - let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16); - let float = matches!(img.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F); + let decoded = guard(|| open()?.decode().map_err(image_error), failed)?; + let gray = matches!(decoded.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16); + let float = matches!(decoded.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F); if gray { - let l = img.into_luma16(); - let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); - return Ok(Image { w, h, kind: Kind::Gray, integer_sampling: false, data: Arc::new(data) }); + let luminance = decoded.into_luma16(); + let data: Vec = luminance.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); + return Image::from_data(w, h, Kind::Gray, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())); } - let mut data = img.into_rgba32f().into_raw(); + let mut data = decoded.into_rgba32f().into_raw(); if !(float || linear) { for px in data.as_chunks_mut::<4>().0 { for c in px.iter_mut().take(3) { @@ -54,27 +56,27 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { } } - Ok(Image { w, h, kind: Kind::Color, integer_sampling: false, data: Arc::new(data) }) + Image::from_data(w, h, Kind::Color, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string())) } -/// Encode `img` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear -pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { +/// Encode `image` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear +pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { let ext = ext.trim_start_matches('.').to_ascii_lowercase(); - let enc = |v: f32| if srgb && img.kind == Kind::Color { linear_to_srgb(v) } else { v }; - let (w, h) = (img.w, img.h); - let color = img.kind == Kind::Color; - let px = |i: usize| -> [f32; 4] { + let encode_channel = |v: f32| if srgb && image.kind() == Kind::Color { linear_to_srgb(v) } else { v }; + let (w, h) = (image.width(), image.height()); + let color = image.kind() == Kind::Color; + let pixel = |i: usize| -> [f32; 4] { if color { - let s = img.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - [enc(s[0]), enc(s[1]), enc(s[2]), s[3]] + let s = image.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + [encode_channel(s[0]), encode_channel(s[1]), encode_channel(s[2]), s[3]] } else { - let v = img.data.get(i).copied().unwrap_or(0.0); + let v = image.data().get(i).copied().unwrap_or(0.0); [v, v, v, 1.0] } }; - let n = (w * h) as usize; - let fmt = match ext.as_str() { + let pixel_count = (w * h) as usize; + let format = match ext.as_str() { "png" => image::ImageFormat::Png, "jpg" | "jpeg" => image::ImageFormat::Jpeg, "tga" => image::ImageFormat::Tga, @@ -85,44 +87,44 @@ pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result return Err(FormatError::Image(format!("unsupported export format `{other}`"))), }; - let float_only = matches!(fmt, image::ImageFormat::OpenExr | image::ImageFormat::Hdr); - let sixteen_ok = fmt == image::ImageFormat::Png; - let q8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let q16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - let dynimg: image::DynamicImage = if float_only { - let data: Vec = (0..n) + let float_only = matches!(format, image::ImageFormat::OpenExr | image::ImageFormat::Hdr); + let sixteen_ok = format == image::ImageFormat::Png; + let quantize_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let quantize_u16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; + let dynamic_image: image::DynamicImage = if float_only { + let data: Vec = (0..pixel_count) .flat_map(|i| { - let p = px(i); + let p = pixel(i); [p[0], p[1], p[2]] }) .collect(); - let buf = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?; - buf.into() + let buffer = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?; + buffer.into() } else if depth != Depth::U8 && sixteen_ok { if color { - let data: Vec = (0..n).flat_map(|i| px(i).map(q16)).collect(); + let data: Vec = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u16)).collect(); image::ImageBuffer::, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } else { - let data: Vec = (0..n).map(|i| q16(px(i)[0])).collect(); + let data: Vec = (0..pixel_count).map(|i| quantize_u16(pixel(i)[0])).collect(); image::ImageBuffer::, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } - } else if color && !matches!(fmt, image::ImageFormat::Jpeg) { - let data: Vec = (0..n).flat_map(|i| px(i).map(q8)).collect(); + } else if color && !matches!(format, image::ImageFormat::Jpeg) { + let data: Vec = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u8)).collect(); image::RgbaImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } else if color { - let data: Vec = (0..n) + let data: Vec = (0..pixel_count) .flat_map(|i| { - let p = px(i); - [q8(p[0]), q8(p[1]), q8(p[2])] + let p = pixel(i); + [quantize_u8(p[0]), quantize_u8(p[1]), quantize_u8(p[2])] }) .collect(); image::RgbImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() } else { - let data: Vec = (0..n).map(|i| q8(px(i)[0])).collect(); + let data: Vec = (0..pixel_count).map(|i| quantize_u8(pixel(i)[0])).collect(); image::GrayImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() }; - let mut out = Cursor::new(Vec::new()); - dynimg.write_to(&mut out, fmt).map_err(|e| FormatError::Image(e.to_string()))?; - Ok(out.into_inner()) + let mut output = Cursor::new(Vec::new()); + dynamic_image.write_to(&mut output, format).map_err(|e| FormatError::Image(e.to_string()))?; + Ok(output.into_inner()) } diff --git a/crates/formats/src/sbs/parameter_array.rs b/crates/formats/src/sbs/parameter_array.rs index 1019302..e38f2f5 100644 --- a/crates/formats/src/sbs/parameter_array.rs +++ b/crates/formats/src/sbs/parameter_array.rs @@ -93,7 +93,7 @@ pub(super) fn write(value: &Value, color_mode: bool, writer: &mut SbsWriter) -> } Value::Gradient(gradient) => { for key in &gradient.keys { - let color = if color_mode { Value::Color(key.color) } else { Value::Float(materialcraft_image::luminance(key.color)) }; + let color = if color_mode { Value::Color(key.color) } else { Value::Float(craft_texture::luminance(key.color)) }; cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(key.midpoint)), ("value", color)]); } } diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index 5a4a7e8..8c895a8 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -82,7 +82,7 @@ fn sample_package() -> Package { }); pkg.graphs.push(graph); - let orange = materialcraft_image::Image::filled(4, 4, materialcraft_image::Kind::Color, [1.0, 0.5, 0.0, 1.0]); + let orange = craft_texture::Image::filled(4, 4, craft_texture::Kind::Color, [1.0, 0.5, 0.0, 1.0]); let png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); pkg diff --git a/crates/formats/src/svg.rs b/crates/formats/src/svg.rs index 0c0b69b..4ab862f 100644 --- a/crates/formats/src/svg.rs +++ b/crates/formats/src/svg.rs @@ -6,7 +6,7 @@ use crate::{FormatError, Result}; use craft_svg::tree::{self, ImageResolver, Limits, draw, usvg}; -use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use craft_texture::{Image, Kind, MAX_SIDE, srgb_to_linear}; /// Largest SVG file (unpacked when SVGZ). const MAX_BYTES: usize = 16 << 20; @@ -82,7 +82,7 @@ mod tests { let left = image.get(0, 0, false); - assert_eq!((image.w, image.h), (4, 2)); + assert_eq!((image.width(), image.height()), (4, 2)); assert!((left[0] - 1.0).abs() < 1e-3 && left[1].abs() < 1e-3 && (left[3] - 1.0).abs() < 1e-3, "{left:?}"); assert_eq!(image.get(3, 1, false)[3], 0.0); } diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs index e8fe792..ea4173f 100644 --- a/crates/formats/src/tests.rs +++ b/crates/formats/src/tests.rs @@ -1,5 +1,5 @@ use super::*; -use materialcraft_image::{Image, Kind, srgb_to_linear}; +use craft_texture::{Image, Kind, srgb_to_linear}; use std::io::Cursor; #[test] @@ -11,11 +11,13 @@ fn export_every_format() { for i in [&img, &gray] { let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}")); - assert_eq!((back.w, back.h), (8, 8)); + + assert_eq!((back.width(), back.height()), (8, 8)); } } } let png16 = encode(&gray, "png", Depth::U16, false).unwrap(); + assert!((decode(&png16, false).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); } @@ -39,7 +41,8 @@ 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(), false).unwrap(); - assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); + + assert_eq!((img.width(), img.height(), img.kind()), (2, 2, Kind::Color)); } #[test] diff --git a/crates/formats/tests/bitmap_imports.rs b/crates/formats/tests/bitmap_imports.rs index 13bb562..d349d4c 100644 --- a/crates/formats/tests/bitmap_imports.rs +++ b/crates/formats/tests/bitmap_imports.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_formats::{BITMAP_EXTENSIONS, BITMAP_FORMATS, Depth, decode, encode}; -use materialcraft_image::{Image, Kind}; use std::io::Cursor; #[test] @@ -23,7 +23,7 @@ fn common_bitmap_formats_decode() { let bytes = encode(&pixels, extension, Depth::U8, true).unwrap(); let image = decode(&bytes, false).unwrap(); - assert_eq!((image.w, image.h), (4, 4), "{extension}"); + assert_eq!((image.width(), image.height()), (4, 4), "{extension}"); } // GIF and TIFF import only, so another writer makes them @@ -31,15 +31,15 @@ fn common_bitmap_formats_decode() { let mut bytes = Cursor::new(Vec::new()); image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut bytes, format).unwrap(); - assert_eq!(decode(bytes.get_ref(), false).unwrap().w, 2, "{format:?}"); + assert_eq!(decode(bytes.get_ref(), false).unwrap().width(), 2, "{format:?}"); } assert!(encode(&pixels, "tif", Depth::U8, true).is_err(), "TIFF is not an export format"); for pgm in [&b"P2\n2 1\n255\n0 255\n"[..], &b"P5\n2 1\n255\n\0\xff"[..]] { let image = decode(pgm, false).unwrap(); - assert_eq!(image.kind, Kind::Gray); - assert_eq!(image.data.as_slice(), &[0.0, 1.0]); + assert_eq!(image.kind(), Kind::Gray); + assert_eq!(image.data(), &[0.0, 1.0]); } } @@ -61,12 +61,12 @@ fn dds_supports_compressed_uncompressed_and_float_textures() { encoder.finish().unwrap(); let image = decode(&bytes, true).unwrap(); - assert_eq!((image.w, image.h), (4, 4)); - assert!(image.data.iter().all(|value| value.is_finite())); - assert!((image.data[0] - 64.0 / 255.0).abs() < 0.05, "{format:?}"); + assert_eq!((image.width(), image.height()), (4, 4)); + assert!(image.data().iter().all(|value| value.is_finite())); + assert!((image.data()[0] - 64.0 / 255.0).abs() < 0.05, "{format:?}"); if format == dds::Format::R32G32B32A32_FLOAT { - assert_eq!(decode(&bytes, false).unwrap().data, image.data, "float DDS stays linear"); + assert_eq!(decode(&bytes, false).unwrap().data(), image.data(), "float DDS stays linear"); } assert!(decode(&bytes[..bytes.len() / 2], true).is_err()); @@ -81,9 +81,9 @@ fn shared_dds_keeps_rgb_transfer_alpha_and_float_range() { let raw = decode(&bytes, true).unwrap(); let converted = decode(&bytes, false).unwrap(); for i in 0..3 { - assert!((converted.data[i] - materialcraft_image::srgb_to_linear(raw.data[i])).abs() < 1e-6); + assert!((converted.data()[i] - craft_texture::srgb_to_linear(raw.data()[i])).abs() < 1e-6); } - assert_eq!(converted.data[3], raw.data[3]); + assert_eq!(converted.data()[3], raw.data()[3]); let mut floats = Vec::new(); dds::header::Header::new_image(1, 1, dds::Format::R32G32B32A32_FLOAT).write(&mut floats).unwrap(); @@ -91,6 +91,6 @@ fn shared_dds_keeps_rgb_transfer_alpha_and_float_range() { floats.extend_from_slice(&v.to_le_bytes()); } for linear in [false, true] { - assert_eq!(decode(&floats, linear).unwrap().data.as_slice(), &[-0.5, 2.0, 0.25, 0.75]); + assert_eq!(decode(&floats, linear).unwrap().data(), &[-0.5, 2.0, 0.25, 0.75]); } } diff --git a/crates/formats/tests/project_packages.rs b/crates/formats/tests/project_packages.rs index 3b4cb69..17ab74b 100644 --- a/crates/formats/tests/project_packages.rs +++ b/crates/formats/tests/project_packages.rs @@ -25,7 +25,7 @@ fn archived_sbs_replaces_surface_references_from_the_shared_library() { fn package() -> Package { let mut package = Package::new("Surface"); - let pixels = materialcraft_image::Image::filled(2, 2, materialcraft_image::Kind::Color, [0.2, 0.4, 0.8, 1.0]); + let pixels = craft_texture::Image::filled(2, 2, craft_texture::Kind::Color, [0.2, 0.4, 0.8, 1.0]); let png = encode(&pixels, "png", Depth::U8, true).unwrap(); package.resources.push(Resource::new("Texture", "texture.png", ResourceBytes::new(png))); package.resources.push(Resource::new("Shape", "shape.svg", ResourceBytes::new(SVG.to_vec()))); diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.toml deleted file mode 100644 index c8f371a..0000000 --- a/crates/image/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "materialcraft-image" -description = "MaterialCraft image buffers: grayscale and color float planes, sampling, resampling, conversions" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lints] -workspace = true - -[dependencies] -rayon = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs deleted file mode 100644 index 3314854..0000000 --- a/crates/image/src/lib.rs +++ /dev/null @@ -1,442 +0,0 @@ -//! # materialcraft-image -//! -//! Image buffers for node cooking, L0: an [`Image`] is a grayscale (1 channel) or color (RGBA) -//! plane of `f32`, shared copy-on-write through an `Arc` so cached node outputs cost nothing to -//! hand around. Values are linear and usually 0..1 (HDR formats may exceed it). Sampling wraps or -//! clamps per axis ("tiling"); everything per pixel runs in parallel rows (rayon). -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::sync::Arc; - -use rayon::prelude::*; - -/// Largest side an image may have (an allocation cap for hostile sizes). -pub const MAX_SIDE: u32 = 8192; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Kind { - Gray, - Color, -} - -impl Kind { - pub fn channels(self) -> usize { - match self { - Kind::Gray => 1, - Kind::Color => 4, - } - } -} - -#[derive(Debug, thiserror::Error)] -pub enum ImageError { - #[error("image size {0}x{1} is outside 1..={MAX_SIDE}")] - BadSize(u32, u32), -} - -#[derive(Clone, Debug)] -pub struct Image { - pub w: u32, - pub h: u32, - pub kind: Kind, - /// Normalized integer textures use 16-bit filtered results in function samplers. - pub integer_sampling: bool, - /// Row-major, `kind.channels()` floats per pixel. - pub data: Arc>, -} - -impl PartialEq for Image { - fn eq(&self, o: &Image) -> bool { - self.w == o.w - && self.h == o.h - && self.kind == o.kind - && self.integer_sampling == o.integer_sampling - && (Arc::ptr_eq(&self.data, &o.data) || self.data == o.data) - } -} - -/// Clamp a requested size into the allowed range. -pub fn clamp_size(w: u32, h: u32) -> (u32, u32) { - (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE)) -} - -#[inline] -fn wrap(i: i64, n: u32, tile: bool) -> usize { - let n = n as i64; - if tile { i.rem_euclid(n) as usize } else { i.clamp(0, n - 1) as usize } -} - -impl Image { - /// A constant image. - pub fn filled(w: u32, h: u32, kind: Kind, v: [f32; 4]) -> Image { - let (w, h) = clamp_size(w, h); - let n = (w * h) as usize; - let data = match kind { - Kind::Gray => vec![v[0]; n], - Kind::Color => v.iter().copied().cycle().take(n * 4).collect(), - }; - - Image { w, h, kind, integer_sampling: false, data: Arc::new(data) } - } - - /// Generate every pixel with `f(x, y)` (pixel indices) in parallel rows. - pub fn generate(w: u32, h: u32, kind: Kind, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { - let (w, h) = clamp_size(w, h); - let c = kind.channels(); - let mut data = vec![0.0f32; (w * h) as usize * c]; - data.par_chunks_mut(w as usize * c).enumerate().for_each(|(y, row)| { - for x in 0..w as usize { - let p = f(x as u32, y as u32); - row[x * c..x * c + c].copy_from_slice(&p[..c]); - } - }); - Image { w, h, kind, integer_sampling: false, data: Arc::new(data) } - } - - /// Generate from normalized coordinates (pixel centers, 0..1). - pub fn generate_uv(w: u32, h: u32, kind: Kind, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { - let (iw, ih) = (1.0 / w.max(1) as f32, 1.0 / h.max(1) as f32); - Image::generate(w, h, kind, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) - } - - pub fn gray(w: u32, h: u32, f: impl Fn(u32, u32) -> f32 + Sync) -> Image { - Image::generate(w, h, Kind::Gray, |x, y| [f(x, y), 0.0, 0.0, 0.0]) - } - - pub fn channels(&self) -> usize { - self.kind.channels() - } - - pub fn is_gray(&self) -> bool { - self.kind == Kind::Gray - } - - /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). - #[inline] - pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { - self.get_axes(x, y, [tile; 2]) - } - - /// Read a texel with independent horizontal and vertical wrapping. - #[inline] - pub fn get_axes(&self, x: i64, y: i64, tiling: [bool; 2]) -> [f32; 4] { - let (x, y) = (wrap(x, self.w, tiling[0]), wrap(y, self.h, tiling[1])); - let i = y * self.w as usize + x; - match self.kind { - Kind::Gray => { - let v = self.data.get(i).copied().unwrap_or(0.0); - [v, v, v, 1.0] - } - Kind::Color => { - let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - [s[0], s[1], s[2], s[3]] - } - } - } - - /// The gray value, or the Rec. 709 luminance of a color image. - #[inline] - pub fn get_gray(&self, x: i64, y: i64, tile: bool) -> f32 { - let p = self.get(x, y, tile); - match self.kind { - Kind::Gray => p[0], - Kind::Color => luminance(p), - } - } - - /// Bilinear sample at normalized `(u, v)`; pixel centers sit at `(i + 0.5) / w`. - #[inline] - pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - self.sample_axes(u, v, [tile; 2]) - } - - /// Bilinear sample with independent horizontal and vertical wrapping. - #[inline] - pub fn sample_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { - self.sample_filtered(u, v, tiling, false) - } - - #[inline] - fn sample_filtered(&self, u: f32, v: f32, tiling: [bool; 2], fixed_weights: bool) -> [f32; 4] { - let fx = u * self.w as f32 - 0.5; - let fy = v * self.h as f32 - 0.5; - if !fx.is_finite() || !fy.is_finite() { - return [0.0, 0.0, 0.0, 1.0]; - } - - // Huge but finite coordinates would saturate the i64 cast and overflow at `+ 1` - let (fx, fy) = (fx.clamp(-1.0e9, 1.0e9), fy.clamp(-1.0e9, 1.0e9)); - let (x0, y0) = (fx.floor(), fy.floor()); - let (mut tx, mut ty) = (fx - x0, fy - y0); - if fixed_weights { - // Function texture reads use eight fractional bits for filter weights - tx = (tx * 256.0).round() / 256.0; - ty = (ty * 256.0).round() / 256.0; - } - - let (x0, y0) = (x0 as i64, y0 as i64); - let a = self.get_axes(x0, y0, tiling); - let b = self.get_axes(x0 + 1, y0, tiling); - let c = self.get_axes(x0, y0 + 1, tiling); - let d = self.get_axes(x0 + 1, y0 + 1, tiling); - let mut o = [0.0; 4]; - for k in 0..4 { - let top = a[k] + (b[k] - a[k]) * tx; - let bot = c[k] + (d[k] - c[k]) * tx; - o[k] = top + (bot - top) * ty; - } - - o - } - - #[inline] - pub fn sample_gray(&self, u: f32, v: f32, tile: bool) -> f32 { - let p = self.sample(u, v, tile); - match self.kind { - Kind::Gray => p[0], - Kind::Color => luminance(p), - } - } - - /// Function texture reads use fixed filter weights and 16-bit integer results. - #[inline] - pub fn sample_stored(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let pixel = self.sample_filtered(u, v, [tile; 2], true); - if self.integer_sampling { - // Eight-bit sources also retain sixteen bits after interpolation - pixel.map(|value| (value.clamp(0.0, 1.0) * 65535.0).round() / 65535.0) - } else { - pixel - } - } - - /// Nearest sample at normalized `(u, v)`. - #[inline] - pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - self.sample_nearest_axes(u, v, [tile; 2]) - } - - /// Nearest sample with independent horizontal and vertical wrapping. - #[inline] - pub fn sample_nearest_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { - let x = (u * self.w as f32).floor(); - let y = (v * self.h as f32).floor(); - if !x.is_finite() || !y.is_finite() { - return [0.0, 0.0, 0.0, 1.0]; - } - - self.get_axes(x as i64, y as i64, tiling) - } - - /// Map every pixel (as RGBA) to a new image of `kind`, same size. - pub fn map(&self, kind: Kind, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Image { - Image::generate(self.w, self.h, kind, |x, y| f(self.get(x as i64, y as i64, false))) - } - - /// This image as grayscale (luminance of a color image). - pub fn to_gray(&self) -> Image { - match self.kind { - Kind::Gray => self.clone(), - Kind::Color => self.map(Kind::Gray, |p| [luminance(p), 0.0, 0.0, 0.0]), - } - } - - /// This image as RGBA (gray copied to RGB, alpha 1). - pub fn to_color(&self) -> Image { - match self.kind { - Kind::Color => self.clone(), - Kind::Gray => self.map(Kind::Color, |p| p), - } - } - - pub fn to_kind(&self, kind: Kind) -> Image { - match kind { - Kind::Gray => self.to_gray(), - Kind::Color => self.to_color(), - } - } - - /// Resample to `w × h` (bilinear when enlarging, box-filtered when shrinking). - pub fn resize(&self, w: u32, h: u32, tile: bool) -> Image { - let (w, h) = clamp_size(w, h); - if w == self.w && h == self.h { - return self.clone(); - } - - if w <= self.w && h <= self.h && self.w.is_multiple_of(w) && self.h.is_multiple_of(h) { - let (fx, fy) = ((self.w / w) as i64, (self.h / h) as i64); - let inv = 1.0 / (fx * fy) as f32; - return Image::generate(w, h, self.kind, |x, y| { - let mut s = [0.0; 4]; - for j in 0..fy { - for i in 0..fx { - let p = self.get(x as i64 * fx + i, y as i64 * fy + j, tile); - for k in 0..4 { - s[k] += p[k]; - } - } - } - - s.map(|v| v * inv) - }); - } - - Image::generate_uv(w, h, self.kind, |u, v| self.sample(u, v, tile)) - } - - /// Raw float access for gray images (`None` for color). - pub fn gray_data(&self) -> Option<&[f32]> { - (self.kind == Kind::Gray).then_some(self.data.as_slice()) - } - - /// 8-bit sRGB-encoded RGBA for display (gray shown as is; color through the sRGB curve). - pub fn to_rgba8_display(&self) -> Vec { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let n = (self.w * self.h) as usize; - let mut out = vec![0u8; n * 4]; - out.par_chunks_mut(4).enumerate().for_each(|(i, px)| match self.kind { - Kind::Gray => { - let v = q(self.data.get(i).copied().unwrap_or(0.0)); - px.copy_from_slice(&[v, v, v, 255]); - } - Kind::Color => { - let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); - px.copy_from_slice(&[q(linear_to_srgb(s[0])), q(linear_to_srgb(s[1])), q(linear_to_srgb(s[2])), q(s[3])]); - } - }); - out - } - - /// Mean of each channel (as RGBA), e.g. for tests and auto levels. - pub fn mean(&self) -> [f32; 4] { - let c = self.channels(); - let n = (self.w * self.h) as f64; - let mut s = [0f64; 4]; - for px in self.data.chunks(c) { - for (k, v) in px.iter().enumerate() { - s[k] += *v as f64; - } - } - - if c == 1 { - let m = (s[0] / n) as f32; - return [m, m, m, 1.0]; - } - - s.map(|v| (v / n) as f32) - } - - /// Minimum and maximum over all channels (alpha excluded). - pub fn range(&self) -> (f32, f32) { - let c = self.channels(); - let mut lo = f32::INFINITY; - let mut hi = f32::NEG_INFINITY; - for px in self.data.chunks(c) { - for v in px.iter().take(c.min(3)) { - lo = lo.min(*v); - hi = hi.max(*v); - } - } - if lo > hi { (0.0, 0.0) } else { (lo, hi) } - } -} - -/// Rec. 709 luminance of a linear RGB(A) pixel. -#[inline] -pub fn luminance(p: [f32; 4]) -> f32 { - 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] -} - -#[inline] -pub fn linear_to_srgb(v: f32) -> f32 { - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 } -} - -#[inline] -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::*; - - #[test] - fn sample_survives_huge_coordinates() { - let img = Image::gray(8, 8, |x, _| x as f32); - for u in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN] { - for tile in [true, false] { - let p = img.sample(u, u, tile); - assert!(p.iter().all(|c| c.is_finite())); - } - } - } - - #[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); - - assert_eq!(img.get(-1, 0, true)[0], 3.0); - assert_eq!(img.get(-1, 0, false)[0], 0.0); - - // Halfway between the last and the (wrapped) first pixel - assert!((img.sample(1.0, 0.5, true)[0] - 1.5).abs() < 1e-5); - } - - #[test] - fn resize_box_and_bilinear() { - let img = Image::gray(4, 4, |x, _| if x < 2 { 0.0 } else { 1.0 }); - let small = img.resize(2, 2, true); - assert_eq!(small.data.as_slice(), &[0.0, 1.0, 0.0, 1.0]); - let big = small.resize(8, 8, false); - assert_eq!(big.w, 8); - assert!(big.data[0] < big.data[7]); - } - - #[test] - fn hostile_sizes_are_clamped() { - let img = Image::filled(0, u32::MAX, Kind::Gray, [0.5; 4]); - assert_eq!((img.w, img.h), (1, MAX_SIDE)); - assert_eq!(img.sample(f32::NAN, 0.0, true), [0.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn conversions() { - let c = Image::filled(2, 2, Kind::Color, [1.0, 1.0, 1.0, 1.0]); - assert!((c.to_gray().data[0] - 1.0).abs() < 1e-5); - assert_eq!(c.to_rgba8_display()[0], 255); - } -} diff --git a/crates/nodes/Cargo.toml b/crates/nodes/Cargo.toml index 437bb96..daf743e 100644 --- a/crates/nodes/Cargo.toml +++ b/crates/nodes/Cargo.toml @@ -10,5 +10,5 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } rayon = { workspace = true } diff --git a/crates/nodes/examples/filter_timing.rs b/crates/nodes/examples/filter_timing.rs index 5e03703..6d5a7ad 100644 --- a/crates/nodes/examples/filter_timing.rs +++ b/crates/nodes/examples/filter_timing.rs @@ -1,8 +1,8 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +use craft_texture::{Image, Kind}; use materialcraft_core::{OutputFormat, Value}; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; use std::{collections::BTreeMap, time::Instant}; diff --git a/crates/nodes/src/atomic/bitmap.rs b/crates/nodes/src/atomic/bitmap.rs index 1a98ada..ab07409 100644 --- a/crates/nodes/src/atomic/bitmap.rs +++ b/crates/nodes/src/atomic/bitmap.rs @@ -15,7 +15,7 @@ pub(super) fn definition() -> NodeDefinition { fn bitmap(context: &CookContext) -> CookResult { let name = context.text("resource"); - let image = match (context.resource)(&materialcraft_image::resource_key(name, context.i("colour_space") == 1)) { + let image = match (context.resource)(&craft_texture::resource_key(name, context.i("colour_space") == 1)) { Some(image) => image.resize(context.w, context.h, context.tile), None if name.is_empty() => context.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/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs index 4705939..3437fdb 100644 --- a/crates/nodes/src/atomic/blend.rs +++ b/crates/nodes/src/atomic/blend.rs @@ -2,7 +2,7 @@ use super::ATOMIC; use crate::ops; use crate::ops::BLEND_MODES; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("blend", "Blend", ATOMIC) @@ -21,19 +21,19 @@ pub(super) fn definition() -> NodeDefinition { } fn blend(context: &CookContext) -> CookResult { - let (fg, bg) = (context.sized(0), context.sized(1)); - let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; - let fg = fg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0])); - let bg = bg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0])); + let (foreground, background) = (context.sized(0), context.sized(1)); + let kind = if [&foreground, &background].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; + let foreground = foreground.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0])); + let background = background.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0])); let mask = context.sized(2).map(|m| m.to_gray()); - let (mode, op) = (context.i("mode"), context.f("opacity")); + let (mode, opacity) = (context.i("mode"), context.f("opacity")); let color_blending = context.i("color_blending"); - let blend_alpha = context.b("alpha") && !fg.is_gray(); + let blend_alpha = context.b("alpha") && !foreground.is_gray(); let clamp = matches!(context.format, materialcraft_core::OutputFormat::U8 | materialcraft_core::OutputFormat::U16 | materialcraft_core::OutputFormat::Inherit); Ok(vec![Image::generate(context.w, context.h, kind, |x, y| { let (x, y) = (x as i64, y as i64); let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); - ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, color_blending, blend_alpha, clamp) + ops::blend_px(mode, background.get(x, y, false), foreground.get(x, y, false), opacity * m, color_blending, blend_alpha, clamp) })]) } diff --git a/crates/nodes/src/atomic/blur.rs b/crates/nodes/src/atomic/blur.rs index 41494b8..9691914 100644 --- a/crates/nodes/src/atomic/blur.rs +++ b/crates/nodes/src/atomic/blur.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, box_filter}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("blur", "Blur", ATOMIC) diff --git a/crates/nodes/src/atomic/box_filter.rs b/crates/nodes/src/atomic/box_filter.rs index ddddab8..07436ae 100644 --- a/crates/nodes/src/atomic/box_filter.rs +++ b/crates/nodes/src/atomic/box_filter.rs @@ -1,6 +1,5 @@ -use materialcraft_image::{Image, MAX_SIDE}; +use craft_texture::{Image, Limits, MAX_SIDE}; use rayon::prelude::*; -use std::sync::Arc; pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> Image { if !radius.is_finite() || radius <= 0.5 { @@ -12,44 +11,49 @@ pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> let extent = (radius + 0.5).floor() as i64; let weight = 1.0 / (2.0 * f64::from(radius)); let edge_weight = (0.5 - (extent as f64 - 0.5) * weight).max(0.0); - let (length, lines) = if horizontal { (input.w, input.h) } else { (input.h, input.w) }; + let (length, lines) = if horizontal { (input.width(), input.height()) } else { (input.height(), input.width()) }; let channels = input.channels(); - let results: Vec> = (0..lines) - .into_par_iter() - .map(|line| { - let get = |position: i64| { - if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) } - }; - let mut output = vec![0.0; length as usize * channels]; - for channel in 0..channels { - // Count NaN, positive infinity and negative infinity separately - let mut sum = 0.0_f64; - let mut non_finite = [0_i64; 3]; - for position in (1 - extent)..extent { - accumulate(&mut sum, &mut non_finite, get(position)[channel], 1); - } - - for (position, pixel) in output.chunks_exact_mut(channels).enumerate() { - let position = position as i64; - let mut value = window_total(sum, non_finite) * weight; - if edge_weight > 0.0 { - value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight; - } - pixel[channel] = value as f32; - accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1); - accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1); - } + let fill_line = |line: u32, output: &mut [f32]| { + let get = |position: i64| { + if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) } + }; + for channel in 0..channels { + // Count NaN, positive infinity and negative infinity separately + let mut sum = 0.0_f64; + let mut non_finite = [0_i64; 3]; + for position in (1 - extent)..extent { + accumulate(&mut sum, &mut non_finite, get(position)[channel], 1); } - output - }) - .collect(); + for (position, pixel) in output.chunks_exact_mut(channels).enumerate() { + let position = position as i64; + let mut value = window_total(sum, non_finite) * weight; + if edge_weight > 0.0 { + value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight; + } + + pixel[channel] = value as f32; + accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1); + accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1); + } + } + }; let data = if horizontal { - results.into_iter().flatten().collect() + let mut data = vec![0.0; input.width() as usize * input.height() as usize * channels]; + data.par_chunks_mut(length as usize * channels).enumerate().for_each(|(line, output)| fill_line(line as u32, output)); + data } else { - let mut data = Vec::with_capacity(input.w as usize * input.h as usize * channels); - for y in 0..input.h as usize { + let results: Vec> = (0..lines) + .into_par_iter() + .map(|line| { + let mut output = vec![0.0; length as usize * channels]; + fill_line(line, &mut output); + output + }) + .collect(); + let mut data = Vec::with_capacity(input.width() as usize * input.height() as usize * channels); + for y in 0..input.height() as usize { for line in &results { data.extend_from_slice(line.get(y * channels..(y + 1) * channels).unwrap_or(&[])); } @@ -58,7 +62,13 @@ pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) -> data }; - Image { w: input.w, h: input.h, kind: input.kind, integer_sampling: false, data: Arc::new(data) } + let mut limits = Limits::default(); + limits.max_side = u32::MAX; + limits.max_pixels = u64::MAX; + limits.max_bytes = u64::MAX; + + // `data` keeps the size and kind of a valid image, so `from_data` accepts it + Image::from_data(input.width(), input.height(), input.kind(), data, &limits).unwrap_or_else(|_| input.clone()) } fn accumulate(sum: &mut f64, non_finite: &mut [i64; 3], value: f32, sign: i64) { diff --git a/crates/nodes/src/atomic/channels_shuffle.rs b/crates/nodes/src/atomic/channels_shuffle.rs index edc402e..1f642ad 100644 --- a/crates/nodes/src/atomic/channels_shuffle.rs +++ b/crates/nodes/src/atomic/channels_shuffle.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("channels_shuffle", "Channels shuffle", ATOMIC) diff --git a/crates/nodes/src/atomic/curve.rs b/crates/nodes/src/atomic/curve.rs index da61d43..c3167f4 100644 --- a/crates/nodes/src/atomic/curve.rs +++ b/crates/nodes/src/atomic/curve.rs @@ -1,22 +1,24 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").any_out().cook(curve) } fn curve(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let c = context.curve("curve"); - // A 1024-entry table: the curve is smooth, so linear lookups are exact enough - let lut: Vec = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect(); - let f = |v: f32| { - let t = v.clamp(0.0, 1.0) * 1024.0; - let i = t as usize; - let a = lut.get(i).copied().unwrap_or(0.0); - let b = lut.get(i + 1).copied().unwrap_or(a); - a + (b - a) * (t - i as f32) + let image = context.any_or(0, Kind::Gray, [0.0; 4]); + let curve = context.curve("curve"); + + // Linear interpolation over 1024 intervals approximates the smooth curve + const TABLE_INTERVALS: usize = 1024; + let table: Vec = (0..=TABLE_INTERVALS).map(|i| curve.eval(i as f32 / TABLE_INTERVALS as f32)).collect(); + let lookup = |value: f32| { + let position = value.clamp(0.0, 1.0) * TABLE_INTERVALS as f32; + let i = position as usize; + let a = table.get(i).copied().unwrap_or(0.0); + let b = table.get(i + 1).copied().unwrap_or(a); + a + (b - a) * (position - i as f32) }; - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) + Ok(vec![image.map(image.kind(), |p| [lookup(p[0]), lookup(p[1]), lookup(p[2]), p[3]])]) } diff --git a/crates/nodes/src/atomic/directional_blur.rs b/crates/nodes/src/atomic/directional_blur.rs index 7a088ce..9a5a9d0 100644 --- a/crates/nodes/src/atomic/directional_blur.rs +++ b/crates/nodes/src/atomic/directional_blur.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, box_filter, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("directional_blur", "Directional blur", ATOMIC) @@ -45,7 +45,7 @@ pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult { let edge_weight = (0.5 - (half_samples as f32 - 0.5) * weight).max(0.0); let (inverse_width, inverse_height) = (1.0 / context.w as f32, 1.0 / context.h as f32); - Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, input.kind(), |u, v| { let mut pixel = [0.0; 4]; for i in -half_samples..=half_samples { let sample_weight = if i.abs() == half_samples { edge_weight } else { weight }; diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs index 9489b61..a7be3e0 100644 --- a/crates/nodes/src/atomic/directional_warp.rs +++ b/crates/nodes/src/atomic/directional_warp.rs @@ -1,6 +1,6 @@ use super::{ATOMIC, direction}; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("directional_warp", "Directional warp", ATOMIC) @@ -15,12 +15,13 @@ pub(super) fn definition() -> NodeDefinition { } fn directional_warp(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); + let image = context.any_or(0, Kind::Gray, [0.0; 4]); let map = context.gray_or(1, 0.0); let (dx, dy) = direction(context.f("angle")); - let k = context.f("intensity") / 256.0; - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { - let m = map.sample_gray(u, v, context.tile) * k; - img.sample(u + dx * m, v + dy * m, context.tile) + const BASE_RESOLUTION: f32 = 256.0; + let intensity_scale = context.f("intensity") / BASE_RESOLUTION; + Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| { + let offset = map.sample_gray(u, v, context.tile) * intensity_scale; + image.sample(u + dx * offset, v + dy * offset, context.tile) })]) } diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index 7b5aeb7..92cacb9 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Image; +use craft_texture::Image; pub(super) fn definition() -> NodeDefinition { node("distance", "Distance", ATOMIC) @@ -17,31 +17,38 @@ pub(super) fn definition() -> NodeDefinition { fn distance(context: &CookContext) -> CookResult { let mask = context.gray_or(0, 0.0); - let maxd = (context.f("distance").max(0.0) * context.w as f32 / 256.0).max(1e-3); - let data = mask.data.clone(); + const BASE_RESOLUTION: f32 = 256.0; + const MIN_DISTANCE_PIXELS: f32 = 1e-3; + let maximum_distance = (context.f("distance").max(0.0) * context.w as f32 / BASE_RESOLUTION).max(MIN_DISTANCE_PIXELS); + let data = mask.shared_data().clone(); let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5; - let Some(src) = context.sized(1) else { - let d2 = ops::distance_sq(context.w, context.h, inside, context.tile); - return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); + let Some(source) = context.sized(1) else { + let squared_distances = ops::distance_sq(context.w, context.h, inside, context.tile); + return Ok(vec![ops::gray_from( + context.w, + context.h, + squared_distances.iter().map(|d| (1.0 - d.sqrt() / maximum_distance).clamp(0.0, 1.0)).collect(), + )?]); }; + // Propagate the exact nearest site without gaps from gradient-walk stalls - let (d2, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); + let (squared_distances, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); let combine = context.b("combine"); - Ok(vec![Image::generate(context.w, context.h, src.kind, |x, y| { + Ok(vec![Image::generate(context.w, context.h, source.kind(), |x, y| { let i = y as usize * context.w as usize + x as usize; let site = sites.get(i).copied().unwrap_or(usize::MAX); - let mut c = if site == usize::MAX { - [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }] + let mut pixel = if site == usize::MAX { + [0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }] } else { - src.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false) + source.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false) }; - let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt(); - if d > maxd { - c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]; + let d = squared_distances.get(i).copied().unwrap_or(f32::INFINITY).sqrt(); + if d > maximum_distance { + pixel = [0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }]; } else if combine { - let f = (1.0 - d / maxd).clamp(0.0, 1.0); - c = [c[0] * f, c[1] * f, c[2] * f, c[3]]; + let falloff = (1.0 - d / maximum_distance).clamp(0.0, 1.0); + pixel = [pixel[0] * falloff, pixel[1] * falloff, pixel[2] * falloff, pixel[3]]; } - c + pixel })]) } diff --git a/crates/nodes/src/atomic/dot.rs b/crates/nodes/src/atomic/dot.rs index 73f4293..8938d28 100644 --- a/crates/nodes/src/atomic/dot.rs +++ b/crates/nodes/src/atomic/dot.rs @@ -1,6 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").any_out().cook(passthrough) diff --git a/crates/nodes/src/atomic/emboss.rs b/crates/nodes/src/atomic/emboss.rs index efcf1d3..a765f2f 100644 --- a/crates/nodes/src/atomic/emboss.rs +++ b/crates/nodes/src/atomic/emboss.rs @@ -1,7 +1,7 @@ use super::{ATOMIC, direction}; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("emboss", "Emboss", ATOMIC) @@ -25,7 +25,7 @@ fn emboss(context: &CookContext) -> CookResult { let intensity = context.f("intensity") * context.w as f32 / INTENSITY_REFERENCE_WIDTH; let (highlight, shadow) = (context.v4("highlight"), context.v4("shadow")); - Ok(vec![Image::generate(context.w, context.h, input.kind, |x, y| { + Ok(vec![Image::generate(context.w, context.h, input.kind(), |x, y| { let (gx, gy) = ops::slope(&height_map, x as i64, y as i64, context.tile); let lighting = (-(gx * light_x + gy * light_y) * intensity).clamp(-1.0, 1.0); let pixel = input.get(x as i64, y as i64, false); diff --git a/crates/nodes/src/atomic/gradient_dynamic.rs b/crates/nodes/src/atomic/gradient_dynamic.rs index 4f985cf..d0911bc 100644 --- a/crates/nodes/src/atomic/gradient_dynamic.rs +++ b/crates/nodes/src/atomic/gradient_dynamic.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) @@ -23,7 +23,7 @@ fn gradient_dynamic(context: &CookContext) -> CookResult { let position = context.f("position"); let vertical = context.i("orientation") == 1; - Ok(vec![Image::generate(context.w, context.h, gradient.kind, |x, y| { + Ok(vec![Image::generate(context.w, context.h, gradient.kind(), |x, y| { let intensity = input.get_gray(i64::from(x), i64::from(y), false).clamp(0.0, 1.0); if vertical { gradient.sample(position, intensity, false) } else { gradient.sample(intensity, position, false) } })]) diff --git a/crates/nodes/src/atomic/gradient_map.rs b/crates/nodes/src/atomic/gradient_map.rs index 0ae8e67..413047e 100644 --- a/crates/nodes/src/atomic/gradient_map.rs +++ b/crates/nodes/src/atomic/gradient_map.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Kind, luminance}; use materialcraft_core::{Gradient, OutputFormat}; -use materialcraft_image::{Kind, luminance}; pub(super) fn definition() -> NodeDefinition { node("gradient_map", "Gradient map", ATOMIC) @@ -28,7 +28,7 @@ fn gradient_map(context: &CookContext) -> CookResult { Ok(vec![if gray { input.map(Kind::Gray, |p| [luminance(look(p[0])), 0.0, 0.0, 0.0]) } else { input.map(Kind::Color, |p| look(p[0])) }]) } -fn integer_map(input: &materialcraft_image::Image, mut gradient: Gradient, gray: bool) -> materialcraft_image::Image { +fn integer_map(input: &craft_texture::Image, mut gradient: Gradient, gray: bool) -> craft_texture::Image { // The 16-bit path evaluates a 256-entry table in integer position space // Coarse nearest sampling shifts transitions and downstream noise octaves for key in &mut gradient.keys { diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs index 151ea63..adec69d 100644 --- a/crates/nodes/src/atomic/grayscale_conversion.rs +++ b/crates/nodes/src/atomic/grayscale_conversion.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("grayscale_conversion", "Grayscale conversion", ATOMIC) diff --git a/crates/nodes/src/atomic/hsl.rs b/crates/nodes/src/atomic/hsl.rs index 8846984..c9184a3 100644 --- a/crates/nodes/src/atomic/hsl.rs +++ b/crates/nodes/src/atomic/hsl.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("hsl", "HSL", ATOMIC) diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs index b3dc487..547f49c 100644 --- a/crates/nodes/src/atomic/input_color.rs +++ b/crates/nodes/src/atomic/input_color.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::ComponentUsage; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("input_color", "Input color", GRAPH_ITEMS) diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs index 202263a..cdb941f 100644 --- a/crates/nodes/src/atomic/input_grayscale.rs +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -1,7 +1,7 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::ComponentUsage; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("input_grayscale", "Input grayscale", GRAPH_ITEMS) diff --git a/crates/nodes/src/atomic/levels.rs b/crates/nodes/src/atomic/levels.rs index ecc27ec..f23a118 100644 --- a/crates/nodes/src/atomic/levels.rs +++ b/crates/nodes/src/atomic/levels.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::Kind; +use craft_texture::Kind; pub(super) fn definition() -> NodeDefinition { node("levels", "Levels", ATOMIC) @@ -24,7 +24,7 @@ fn levels(context: &CookContext) -> CookResult { let output_low = context.v4("out_low"); let output_high = context.v4("out_high"); - Ok(vec![image.map(image.kind, |pixel| { + Ok(vec![image.map(image.kind(), |pixel| { std::array::from_fn(|channel| levels_fn(pixel[channel], low[channel], mid[channel], high[channel], output_low[channel], output_high[channel])) })]) } diff --git a/crates/nodes/src/atomic/normal.rs b/crates/nodes/src/atomic/normal.rs index c37dcc6..802c9c0 100644 --- a/crates/nodes/src/atomic/normal.rs +++ b/crates/nodes/src/atomic/normal.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("normal", "Normal", ATOMIC) @@ -23,8 +23,8 @@ fn normal(context: &CookContext) -> CookResult { } pub fn height_to_normal(height_map: &Image, intensity: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { - Image::generate(height_map.w, height_map.h, Kind::Color, |x, y| { - // Backward differences place alpha wrapped discontinuity on its owning pixel + Image::generate(height_map.width(), height_map.height(), Kind::Color, |x, y| { + // Backward differences place a wrapped discontinuity on its owning pixel let height = height_map.get_gray(x as i64, y as i64, tile); let dx = height - height_map.get_gray(x as i64 - 1, y as i64, tile); let dy = height - height_map.get_gray(x as i64, y as i64 - 1, tile); diff --git a/crates/nodes/src/atomic/output.rs b/crates/nodes/src/atomic/output.rs index bfcf847..ca02e3c 100644 --- a/crates/nodes/src/atomic/output.rs +++ b/crates/nodes/src/atomic/output.rs @@ -1,6 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, PortKind, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("output", "Output", GRAPH_ITEMS) @@ -21,6 +21,6 @@ pub fn output_kind(def: &NodeDefinition, port: usize, inputs: &[Option]) match def.outputs.get(port).map(|p| p.kind) { Some(PortKind::Gray) => Kind::Gray, Some(PortKind::Color) => Kind::Color, - _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind), + _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind()), } } diff --git a/crates/nodes/src/atomic/sharpen.rs b/crates/nodes/src/atomic/sharpen.rs index 4542deb..52b4e98 100644 --- a/crates/nodes/src/atomic/sharpen.rs +++ b/crates/nodes/src/atomic/sharpen.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("sharpen", "Sharpen", ATOMIC) @@ -20,7 +20,7 @@ fn sharpen(context: &CookContext) -> CookResult { let horizontal = intensity * short_side / context.w.max(1) as f32; let vertical = intensity * short_side / context.h.max(1) as f32; - Ok(vec![Image::generate(context.w, context.h, input.kind, |x, y| { + Ok(vec![Image::generate(context.w, context.h, input.kind(), |x, y| { let (x, y) = (i64::from(x), i64::from(y)); let center = input.get(x, y, false); let left = input.get_axes(x - 1, y, tile); diff --git a/crates/nodes/src/atomic/text.rs b/crates/nodes/src/atomic/text.rs index 2e18efd..3d07389 100644 --- a/crates/nodes/src/atomic/text.rs +++ b/crates/nodes/src/atomic/text.rs @@ -221,7 +221,7 @@ mod tests { }; let img = &text(&context).unwrap()[0]; - let lit = img.data.iter().filter(|value| **value > 0.5).count(); + let lit = img.data().iter().filter(|value| **value > 0.5).count(); assert!(lit > 300, "{lit} pixels"); diff --git a/crates/nodes/src/atomic/transformation.rs b/crates/nodes/src/atomic/transformation.rs index a320a99..3d4eabd 100644 --- a/crates/nodes/src/atomic/transformation.rs +++ b/crates/nodes/src/atomic/transformation.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; +use craft_texture::{Image, Kind}; use materialcraft_core::OutputFormat; -use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("transformation", "Transformation 2D", ATOMIC) @@ -21,8 +21,9 @@ fn transformation(context: &CookContext) -> CookResult { let input = context.input(0).cloned().unwrap_or_else(|| Image::filled(context.w, context.h, Kind::Gray, [0.0; 4])); let offset = context.v2("offset"); let matrix = context.v4("matrix"); + const MIN_DETERMINANT: f32 = 1e-8; let determinant = matrix[0] * matrix[3] - matrix[1] * matrix[2]; - if !determinant.is_finite() || determinant.abs() < 1e-8 { + if !determinant.is_finite() || determinant.abs() < MIN_DETERMINANT { return Err("transform matrix is singular".into()); } @@ -33,7 +34,7 @@ fn transformation(context: &CookContext) -> CookResult { // Keep independent wrap axes for panoramic images let tiling = context.vars.get("$tiling").and_then(materialcraft_core::Value::as_i32).map_or([context.tile; 2], |mask| [mask & 1 != 0, mask & 2 != 0]); - Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| { + Ok(vec![Image::generate_uv(context.w, context.h, input.kind(), |u, v| { let x = u - 0.5; let y = v - 0.5; @@ -53,8 +54,8 @@ fn transformation(context: &CookContext) -> CookResult { fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Image { let width = context.w.max(1) as f32; let height = context.h.max(1) as f32; - let dx = (matrix[0] * input.w as f32 / width).hypot(matrix[1] * input.h as f32 / width); - let dy = (matrix[2] * input.w as f32 / height).hypot(matrix[3] * input.h as f32 / height); + let dx = (matrix[0] * input.width() as f32 / width).hypot(matrix[1] * input.height() as f32 / width); + let dy = (matrix[2] * input.width() as f32 / height).hypot(matrix[3] * input.height() as f32 / height); // Thirteen reductions cover the maximum supported side of 8192 texels let levels = dx.max(dy).max(1.0).log2().round().clamp(0.0, 13.0) as u32; @@ -65,12 +66,12 @@ fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Ima }; for _ in 0..levels { - if input.w <= 1 && input.h <= 1 { + if input.width() <= 1 && input.height() <= 1 { break; } // Integer mip levels round four-texel averages halfway up - input = Image::generate(input.w.div_ceil(2), input.h.div_ceil(2), input.kind, |x, y| { + input = Image::generate(input.width().div_ceil(2), input.height().div_ceil(2), input.kind(), |x, y| { let (x, y) = (i64::from(x) * 2, i64::from(y) * 2); let pixels = [input.get(x, y, false), input.get(x + 1, y, false), input.get(x, y + 1, false), input.get(x + 1, y + 1, false)]; std::array::from_fn(|channel| { @@ -78,7 +79,8 @@ fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Ima let sum: u32 = pixels.iter().map(|pixel| (pixel[channel].clamp(0.0, 1.0) * maximum).round() as u32).sum(); ((sum + 2) / 4) as f32 / maximum } else { - pixels.iter().map(|pixel| pixel[channel]).sum::() * 0.25 + // Average in f64 so finite HDR texels cannot overflow the sum + (pixels.iter().map(|pixel| f64::from(pixel[channel])).sum::() * 0.25) as f32 } }) }); diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs index b32b54f..97cf298 100644 --- a/crates/nodes/src/atomic/uniform.rs +++ b/crates/nodes/src/atomic/uniform.rs @@ -1,6 +1,6 @@ use super::ATOMIC; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind, luminance}; +use craft_texture::{Image, Kind, luminance}; pub(super) fn definition() -> NodeDefinition { node("uniform", "Uniform color", ATOMIC) diff --git a/crates/nodes/src/atomic/warp.rs b/crates/nodes/src/atomic/warp.rs index bbd1f36..ba9ae42 100644 --- a/crates/nodes/src/atomic/warp.rs +++ b/crates/nodes/src/atomic/warp.rs @@ -1,7 +1,7 @@ use super::ATOMIC; use crate::ops; use crate::{CookContext, CookResult, NodeDefinition, node}; -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { node("warp", "Warp", ATOMIC) @@ -15,12 +15,12 @@ pub(super) fn definition() -> NodeDefinition { } fn warp(context: &CookContext) -> CookResult { - let img = context.any_or(0, Kind::Gray, [0.0; 4]); - let grad = context.gray_or(1, 0.0); - let k = context.f("intensity"); - Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { + let image = context.any_or(0, Kind::Gray, [0.0; 4]); + let gradient = context.gray_or(1, 0.0); + let intensity = context.f("intensity"); + Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| { let (x, y) = ((u * context.w as f32) as i64, (v * context.h as f32) as i64); - let (dx, dy) = ops::slope(&grad, x, y, context.tile); - img.sample(u + dx * k, v + dy * k, context.tile) + let (dx, dy) = ops::slope(&gradient, x, y, context.tile); + image.sample(u + dx * intensity, v + dy * intensity, context.tile) })]) } diff --git a/crates/nodes/src/cook_context.rs b/crates/nodes/src/cook_context.rs index 643129d..889cdf0 100644 --- a/crates/nodes/src/cook_context.rs +++ b/crates/nodes/src/cook_context.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{Curve, FunctionGraph, Gradient, Value}; -use materialcraft_image::{Image, Kind}; use std::collections::BTreeMap; /// Where a cook runs: output size, seed, tiling, inputs and resolved parameters @@ -98,7 +98,7 @@ impl CookContext<'_> { /// The kind an "Any" output takes: the main input's, else `fallback` pub fn main_kind(&self, fallback: Kind) -> Kind { - self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind) + self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind()) } /// A gray image from `f(u, v)` at the output size diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs index 449b685..1a5eba0 100644 --- a/crates/nodes/src/function/evaluation_context.rs +++ b/crates/nodes/src/function/evaluation_context.rs @@ -1,5 +1,5 @@ +use craft_texture::Image; use materialcraft_core::Value; -use materialcraft_image::Image; use std::collections::BTreeMap; /// Inputs shared by one function evaluation diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index 6f01b22..f4f14ad 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -123,7 +123,7 @@ pub(crate) fn evaluate( let index = usize::try_from(setting[0]).map_err(|_| "negative image index")?; let pixel = match context.images.get(index).and_then(Option::as_ref) { Some(image) if setting[1] == 0 => { - image.get((position[0] * image.w as f32).floor() as i64, (position[1] * image.h as f32).floor() as i64, context.tile) + image.get((position[0] * image.width() as f32).floor() as i64, (position[1] * image.height() as f32).floor() as i64, context.tile) } Some(image) => image.sample_stored(position[0], position[1], context.tile), None => [0.0; 4], diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index f31654b..ac7ce22 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -1,9 +1,8 @@ use super::{EvaluationContext, EvaluationState, compile}; use crate::{CookContext, CookResult}; +use craft_texture::{Image, Kind, Limits}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use rayon::prelude::*; -use std::sync::Arc; fn pixel(value: Value, gray: bool, format: materialcraft_core::OutputFormat) -> Result<[f32; 4], String> { let values = super::value_type::floats(&value)?; @@ -41,7 +40,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { let gray = !context.b("color_mode"); let kind = if gray { Kind::Gray } else { Kind::Color }; - let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let (width, height) = craft_texture::clamp_size(context.w, context.h); let channels = kind.channels(); let mut data = vec![0.0; width as usize * height as usize * channels]; data.par_chunks_mut(width as usize * channels).enumerate().try_for_each_init(EvaluationState::default, |state, (y, row)| -> Result<(), String> { @@ -61,5 +60,5 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { Ok(()) })?; - Ok(vec![Image { w: width, h: height, kind, integer_sampling: false, data: Arc::new(data) }]) + Ok(vec![Image::from_data(width, height, kind, data, &Limits::default()).map_err(|e| e.to_string())?]) } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index fb7c7a1..bfea4f8 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{FunctionGraph, Value}; -use materialcraft_image::{Image, Kind}; use std::collections::{BTreeMap, BTreeSet}; use super::{EvaluationContext, EvaluationState, FUNCTIONS, compile, default_value}; @@ -37,7 +37,9 @@ fn every_native_function_executes_with_its_declared_ports() { let mut covered = BTreeSet::new(); for definition in FUNCTIONS { let name = definition.id; + assert!(covered.insert(name), "duplicate {name}"); + let mut graph = FunctionGraph::default(); let mut variables = BTreeMap::new(); let mut setting = default_value(name); @@ -131,11 +133,13 @@ fn branches_are_lazy_and_sequence_orders_side_effects() { let expected = graph.add_constant(Value::Int(17)); let undefined = graph.add("get_integer1", &[], Some(Value::Text("missing".into()))); graph.output = Some(graph.add("ifelse", &[condition, expected, undefined], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17)); let set = graph.add("set", &[expected], Some(Value::Text("stored".into()))); let get = graph.add("get_integer1", &[], Some(Value::Text("stored".into()))); graph.output = Some(graph.add("sequence", &[set, get], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17)); } @@ -153,18 +157,22 @@ fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() { let expected = variables.get(name).unwrap_or(&default); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let program = compile(&graph, 0).unwrap(); + assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), *expected); assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default()).unwrap(), *expected); } assert!(evaluate(&graph, &BTreeMap::from([(name.into(), Value::Bool(false))])).unwrap_err().contains("wrong type")); + graph.output = Some(defined); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Bool(true)); } let mut graph = FunctionGraph::default(); graph.output = Some(graph.add("get_integer1", &[], Some(Value::Text("$tiling".into())))); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: false, variables: &BTreeMap::new() }; + assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Int(0)); } @@ -180,10 +188,12 @@ fn loops_recompute_state_and_have_a_budget() { let add = graph.add("add", &[get, one], None); let body = graph.add("set", &[add], Some(Value::Text("counter".into()))); graph.output = Some(graph.add("while", &[init, condition, body], Some(Value::Int(-1)))); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3)); let condition = graph.add_constant(Value::Bool(false)); graph.output = Some(graph.add("while", &[zero, condition, one], Some(Value::Int(-1)))); + assert!(evaluate(&graph, &BTreeMap::new()).unwrap_err().contains("budget")); } @@ -195,9 +205,12 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { previous = graph.add("passthrough", &[previous], None); } graph.output = Some(graph.add("abs", &[previous], None)); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1.0)); + graph.nodes[0].op = "passthrough".into(); graph.nodes[0].inputs = vec![Some(previous)]; + assert!(compile(&graph, 0).err().unwrap().contains("cycle")); let mut graph = FunctionGraph::constant(Value::Float(1.0)); @@ -206,6 +219,7 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { previous = graph.add("add", &[previous, previous], None); } graph.output = Some(previous); + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0)); } @@ -236,6 +250,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() { let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap(); let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() }; + assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5)); assert!(pixel_state.variables().is_empty()); } @@ -253,6 +268,7 @@ fn pixel_random_seed_and_defined_variables_match_general_evaluation() { for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] { let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap(); + assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected); } } @@ -587,6 +603,7 @@ fn unconnected_ifelse_branches_use_the_value_type_not_the_condition() { node.type_code = declared_type; let selected = if condition_value { 1 } else { 2 }; let expected = if selected == missing { zero.clone() } else { value.clone() }; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), expected); } } @@ -603,6 +620,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t let node = graph.nodes.last_mut().unwrap(); node.inputs = vec![None, Some(branch), None]; node.type_code = 0; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(0.0)); for condition_value in [false, true] { @@ -612,6 +630,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t let node = graph.nodes.last_mut().unwrap(); node.inputs = vec![Some(condition), None, None]; node.type_code = 512; + assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float2([0.0; 2])); } } diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index 8b4c173..caca06f 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -33,7 +33,7 @@ pub use parameter_descriptor::ParameterDescriptor; pub use port_definition::PortDefinition; pub use port_kind::PortKind; -pub type CookResult = Result, String>; +pub type CookResult = Result, String>; pub type Cook = fn(&CookContext<'_>) -> CookResult; #[cfg(test)] diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index 96f2d8d..7fbc4f1 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -1,101 +1,125 @@ //! Image operations shared by many nodes: Gaussian blur, Euclidean distance transform, slopes, //! color space helpers and blend modes. -use std::sync::Arc; - -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind, Limits}; use rayon::prelude::*; /// Gaussian blur with standard deviation `sigma` (pixels). Small sigmas use a sampled kernel; /// larger ones three box passes (a close Gaussian approximation in O(1) per pixel). -pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { - if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() { - return img.clone(); +pub fn gaussian(image: &Image, sigma: f32, tile: bool) -> Image { + const MIN_SIGMA_PIXELS: f32 = 0.05; + const BOX_BLUR_MIN_SIGMA_PIXELS: f32 = 3.0; + const KERNEL_RADIUS_SIGMAS: f32 = 3.0; + + if sigma.is_nan() || sigma <= MIN_SIGMA_PIXELS || !sigma.is_finite() { + return image.clone(); } - let sigma = sigma.min(img.w.max(img.h) as f32); - if sigma < 3.0 { - let r = (sigma * 3.0).ceil() as i64; - let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); - let s: f32 = k.iter().sum(); - let k: Vec = k.iter().map(|v| v / s).collect(); - let pass = |src: &Image, horizontal: bool| convolve_1d(src, &k, r, horizontal, tile); - return pass(&pass(img, true), false); + let sigma = sigma.min(image.width().max(image.height()) as f32); + if sigma < BOX_BLUR_MIN_SIGMA_PIXELS { + let radius = (sigma * KERNEL_RADIUS_SIGMAS).ceil() as i64; + let kernel: Vec = (-radius..=radius).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let kernel_sum: f32 = kernel.iter().sum(); + let kernel: Vec = kernel.iter().map(|v| v / kernel_sum).collect(); + let pass = |src: &Image, horizontal: bool| convolve_1d(src, &kernel, radius, horizontal, tile); + return pass(&pass(image, true), false); } // Box widths for three passes (Kovesi, "Fast almost-Gaussian filtering") - let n = 3.0f32; - let wl = ((12.0 * sigma * sigma / n + 1.0).sqrt()).floor() as i64; - let wl = if wl % 2 == 0 { wl - 1 } else { wl }; - let wu = wl + 2; - let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round() as i64; - let mut out = img.clone(); + let pass_count = 3.0f32; + let lower_width = ((12.0 * sigma * sigma / pass_count + 1.0).sqrt()).floor() as i64; + let lower_width = if lower_width % 2 == 0 { lower_width - 1 } else { lower_width }; + let upper_width = lower_width + 2; + let lower_passes = ((12.0 * sigma * sigma - pass_count * (lower_width * lower_width) as f32 - 4.0 * pass_count * lower_width as f32 - 3.0 * pass_count) + / (-4.0 * lower_width as f32 - 4.0)) + .round() as i64; + let mut output = image.clone(); for i in 0..3 { - let r = (if i < m { wl } else { wu } - 1) / 2; - out = box_1d(&box_1d(&out, r.max(0), true, tile), r.max(0), false, tile); + let radius = (if i < lower_passes { lower_width } else { upper_width } - 1) / 2; + output = box_1d(&box_1d(&output, radius.max(0), true, tile), radius.max(0), false, tile); } - out + output } -fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image { - let c = src.channels(); - Image::generate(src.w, src.h, src.kind, |x, y| { - let mut acc = [0.0f32; 4]; - for (i, kv) in k.iter().enumerate() { - let o = i as i64 - r; - let p = if horizontal { src.get(x as i64 + o, y as i64, tile) } else { src.get(x as i64, y as i64 + o, tile) }; - for ch in 0..c.clamp(1, 4) { - acc[ch] += p[ch] * kv; +/// The default limits, raised to admit `src`, so a pass over an image made with raised limits +/// returns an image of the same size. +fn limits_for(src: &Image) -> Limits { + let mut limits = Limits::default(); + limits.max_side = limits.max_side.max(src.width()).max(src.height()); + limits.max_pixels = limits.max_pixels.max(u64::from(src.width()) * u64::from(src.height())); + limits.max_bytes = limits.max_bytes.max(size_of_val(src.data()) as u64); + limits +} + +fn convolve_1d(src: &Image, kernel: &[f32], radius: i64, horizontal: bool, tile: bool) -> Image { + let channels = src.channels(); + Image::try_generate(src.width(), src.height(), src.kind(), &limits_for(src), |x, y| { + let mut accumulator = [0.0f32; 4]; + for (i, weight) in kernel.iter().enumerate() { + let offset = i as i64 - radius; + let pixel = if horizontal { src.get(x as i64 + offset, y as i64, tile) } else { src.get(x as i64, y as i64 + offset, tile) }; + for channel in 0..channels.clamp(1, 4) { + accumulator[channel] += pixel[channel] * weight; } } - if c == 1 { [acc[0], 0.0, 0.0, 0.0] } else { acc } + if channels == 1 { [accumulator[0], 0.0, 0.0, 0.0] } else { accumulator } }) + .unwrap_or_else(|_| src.clone()) } -/// One running-sum box pass of radius `r`. -fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { - if r <= 0 { +/// One running-sum box pass of radius `radius`. +fn box_1d(src: &Image, radius: i64, horizontal: bool, tile: bool) -> Image { + if radius <= 0 { return src.clone(); } - let (w, h) = (src.w as usize, src.h as usize); - let c = src.channels(); - let inv = 1.0 / (2 * r + 1) as f32; - let mut data = vec![0.0f32; w * h * c]; + let (w, h) = (src.width() as usize, src.height() as usize); + let channels = src.channels(); + let inverse_width = 1.0 / (2 * radius + 1) as f64; + let mut data = vec![0.0f32; w * h * channels]; let line_len = if horizontal { w } else { h }; let lines = if horizontal { h } else { w }; - let get = |line: usize, i: i64, ch: usize| -> f32 { + + // f64 keeps finite HDR windows from overflowing the running sum + let get = |line: usize, i: i64, channel: usize| -> f64 { let n = line_len as i64; let i = if tile { i.rem_euclid(n) } else { i.clamp(0, n - 1) } as usize; let (x, y) = if horizontal { (i, line) } else { (line, i) }; - src.data.get((y * w + x) * c + ch).copied().unwrap_or(0.0) + f64::from(src.data().get((y * w + x) * channels + channel).copied().unwrap_or(0.0)) }; - let results: Vec> = (0..lines) - .into_par_iter() - .map(|line| { - let mut out = vec![0.0f32; line_len * c]; - for ch in 0..c { - let mut sum: f32 = (-r..=r).map(|i| get(line, i, ch)).sum(); - for i in 0..line_len { - out[i * c + ch] = sum * inv; - sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch); - } + let fill_line = |line: usize, output: &mut [f32]| { + for channel in 0..channels { + let mut sum: f64 = (-radius..=radius).map(|i| get(line, i, channel)).sum(); + for i in 0..line_len { + output[i * channels + channel] = (sum * inverse_width) as f32; + sum += get(line, i as i64 + radius + 1, channel) - get(line, i as i64 - radius, channel); } + } + }; - out - }) - .collect(); - for (line, vals) in results.iter().enumerate() { - for i in 0..line_len { - let (x, y) = if horizontal { (i, line) } else { (line, i) }; - let dst = (y * w + x) * c; - data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]); + if horizontal { + data.par_chunks_mut(w * channels).enumerate().for_each(|(line, output)| fill_line(line, output)); + } else { + let results: Vec> = (0..lines) + .into_par_iter() + .map(|line| { + let mut output = vec![0.0f32; line_len * channels]; + fill_line(line, &mut output); + output + }) + .collect(); + for (line, values) in results.into_iter().enumerate() { + for i in 0..line_len { + let destination = (i * w + line) * channels; + data[destination..destination + channels].copy_from_slice(&values[i * channels..i * channels + channels]); + } } } - Image { w: src.w, h: src.h, kind: src.kind, integer_sampling: false, data: Arc::new(data) } + // A valid source has matching dimensions and data length + Image::from_data(src.width(), src.height(), src.kind(), data, &limits_for(src)).unwrap_or_else(|_| src.clone()) } /// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is @@ -376,9 +400,10 @@ pub fn blend_px(mode: i32, bg: [f32; 4], fg: [f32; 4], opacity: f32, color_blend o } -/// A gray image of the output size from per-pixel values. -pub fn gray_from(w: u32, h: u32, v: Vec) -> Image { - Image { w, h, kind: Kind::Gray, integer_sampling: false, data: Arc::new(v) } +/// A gray image of the output size from per-pixel values, or an error when the size is out of +/// range or `v` does not hold one value per pixel. +pub fn gray_from(w: u32, h: u32, v: Vec) -> Result { + Image::from_data(w, h, Kind::Gray, v, &Limits::default()).map_err(|e| e.to_string()) } #[cfg(test)] @@ -405,12 +430,51 @@ mod tests { let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 }); for s in [1.0, 6.0] { let b = gaussian(&img, s, true); + assert!((b.mean()[0] - img.mean()[0]).abs() < 1e-3, "sigma {s}"); } let flat = gaussian(&Image::filled(8, 8, Kind::Color, [0.2, 0.4, 0.6, 1.0]), 4.0, false); + assert!((flat.get(3, 3, false)[1] - 0.4).abs() < 1e-5); } + #[test] + fn box_blur_of_large_hdr_values_stays_finite() { + let value = 0.75 * f32::MAX; + let blurred = gaussian(&Image::filled(16, 4, Kind::Gray, [value; 4]), 5.0, true); + + for x in 0..16 { + let v = blurred.get(x, 1, false)[0]; + + assert!(v.is_finite() && (v / value - 1.0).abs() < 1e-5, "pixel {x} is {v}"); + } + } + + #[test] + fn blur_keeps_the_size_and_result_of_an_image_over_the_default_limits() { + let w = craft_texture::MAX_SIDE + 1; + let mut limits = Limits::default(); + limits.max_side = w; + let values: Vec = (0..w).map(|x| if (x / 8) % 2 == 0 { 1.0 } else { 0.0 }).collect(); + let Ok(img) = Image::from_data(w, 1, Kind::Gray, values, &limits) else { + panic!("a {w}x1 image fits the raised limits"); + }; + + for sigma in [1.0, 5.0] { + let blurred = gaussian(&img, sigma, false); + + assert_eq!((blurred.width(), blurred.height()), (w, 1), "sigma {sigma}"); + assert_ne!(blurred.data(), img.data(), "sigma {sigma} left the pixels unchanged"); + } + } + + #[test] + fn gray_from_rejects_an_empty_size_and_a_wrong_value_count() { + assert!(gray_from(0, 4, Vec::new()).is_err()); + assert!(gray_from(2, 2, vec![0.0; 3]).is_err()); + assert_eq!(gray_from(2, 2, vec![0.5; 4]).map(|image| image.mean()[0]), Ok(0.5)); + } + #[test] fn edt_exact() { let d = distance_sq(9, 1, |i| i == 4, false); diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs index a6139a4..7827c60 100644 --- a/crates/nodes/src/pattern/raster.rs +++ b/crates/nodes/src/pattern/raster.rs @@ -1,27 +1,33 @@ -use materialcraft_image::{Image, Kind}; +use craft_texture::{Image, Kind, Limits}; use std::sync::Arc; use super::{pattern_stamp::PatternStamp, region::Region, shape}; use crate::CookContext; const MAX_SAMPLES: u64 = 256_000_000; +const MAX_STAMP_COPIES: u64 = 1_048_576; +const MIN_STAMP_SIZE: f32 = 1e-8; pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: u32) -> Result { - let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let (width, height) = craft_texture::clamp_size(context.w, context.h); let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; - let mut image = + let mut background = context.input(0).map(|image| image.resize(width, height, context.tile)).unwrap_or_else(|| Image::filled(width, height, kind, context.v4("background"))); - image = if kind == Kind::Gray { image.to_gray() } else { image.to_color() }; + background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() }; if stamps.is_empty() { - return Ok(image); + return Ok(background); } let channels = kind.channels(); let opacity = context.f("opacity").max(0.0); let weights = depth_weights(context.f("roughness"), max_depth)?; - let pixels = Arc::make_mut(&mut image.data); + let integer_sampling = background.integer_sampling(); + let mut data = Arc::clone(background.shared_data()); + drop(background); + + let pixels = Arc::make_mut(&mut data); let mut budget = MAX_SAMPLES; - let mut copies_left = 1_048_576_u64; + let mut copies_left = MAX_STAMP_COPIES; let render_region = Region::new(context.v4("render_region"))?; let period = if context.tile { Region::new(context.v4("tiling_region"))?.period() } else { [1.0; 2] }; @@ -30,7 +36,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: return Err("pattern parameters must be finite".into()); } - if stamp.size.iter().any(|size| size.abs() < 1e-8) { + if stamp.size.iter().any(|size| size.abs() < MIN_STAMP_SIZE) { continue; } @@ -84,7 +90,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: Some(input) => { let uv = local.map(|coordinate| coordinate * 0.5 + 0.5); if stamp.filtering == 0 { - input.get((uv[0] * input.w as f32) as i64, (uv[1] * input.h as f32) as i64, false) + input.get((uv[0] * input.width() as f32) as i64, (uv[1] * input.height() as f32) as i64, false) } else { input.sample(uv[0], uv[1], false) } @@ -120,11 +126,11 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: } } - Ok(image) + Image::from_data(width, height, kind, data, &Limits::default()).map(|image| image.with_integer_sampling(integer_sampling)).map_err(|e| e.to_string()) } fn depth_weights(roughness: f32, max_depth: u32) -> Result, String> { - // Traversal is bounded by the 4096-node acyclic pattern graph. Keep this allocation bounded too + // Match the depth allocation cap to the 4096-node acyclic traversal limit if max_depth >= 4096 || !roughness.is_finite() || roughness < 0.0 { return Err("pattern roughness must be finite and nonnegative, with depth below 4096".into()); } diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index b0999dd..e274174 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -67,12 +67,17 @@ fn iterate_sets_number_and_switch_selects_one_child() { function.output = Some(function.add("get_float1", &[], Some(Value::Text("$number".into())))); graph.nodes[2].parameters.insert("opacity".into(), Value::Function(Box::new(function))); let image = cook(graph.clone()).unwrap().remove(0); + assert!((image.mean()[0] - 3.0).abs() < 1e-6); + let dot = graph.add(PatternNodeKind::Dot).unwrap(); graph.nodes[1].children[0] = Some(dot); graph.nodes[3].children[0] = Some(quadrant); - assert_eq!(cook(graph.clone()).unwrap()[0].data, image.data); + + assert_eq!(cook(graph.clone()).unwrap()[0].data(), image.data()); + graph.nodes[1].parameters.insert("switch".into(), Value::Bool(true)); + assert_eq!(cook(graph).unwrap()[0].mean()[0], 0.0); } @@ -96,7 +101,7 @@ fn iterate_preserves_assignments_from_previous_iterations() { graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(increment))); let image = cook(graph).unwrap().remove(0); - assert!(image.data.iter().all(|value| *value == 6.0), "expected 1 + 2 + 3, got {:?}", image.mean()); + assert!(image.data().iter().all(|value| *value == 6.0), "expected 1 + 2 + 3, got {:?}", image.mean()); } #[test] @@ -182,7 +187,7 @@ fn roughness_attenuates_quadrants_by_depth_and_keeps_background() { for blend in 0..=2 { let image = roughness_sample(roughness, depth, blend, color, false).unwrap().remove(0); let pixel = image.get(0, 0, false); - for (channel, foreground) in [0.8_f32, 0.4, 0.2, 1.0].into_iter().take(image.kind.channels()).enumerate() { + for (channel, foreground) in [0.8_f32, 0.4, 0.2, 1.0].into_iter().take(image.channels()).enumerate() { let value = foreground * 0.5 * weight; let expected = match blend { 1 if !color => value.max(0.1), @@ -245,7 +250,7 @@ fn a_full_nine_level_quadtree_renders_one_pattern_per_pixel() { let images = (definition.cook)(&context).unwrap(); - assert!(images[0].data.iter().all(|value| (*value - 1.0).abs() < 1e-6)); + assert!(images[0].data().iter().all(|value| (*value - 1.0).abs() < 1e-6)); } fn square(graph: &mut PatternGraph, node: usize) { diff --git a/crates/nodes/src/raster/composite.rs b/crates/nodes/src/raster/composite.rs index 36f6140..0e1f0ee 100644 --- a/crates/nodes/src/raster/composite.rs +++ b/crates/nodes/src/raster/composite.rs @@ -1,11 +1,11 @@ -use materialcraft_image::{Image, Kind, luminance}; +use craft_texture::{Image, Kind, luminance}; use crate::CookContext; pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; let background = match context.input(0) { - Some(image) if image.kind == kind => image.resize(context.w, context.h, context.tile), + Some(image) if image.kind() == kind => image.resize(context.w, context.h, context.tile), // An incompatible connection replaces the constant background with empty pixels Some(_) => Image::filled(1, 1, kind, [0.0; 4]), diff --git a/crates/nodes/src/tests.rs b/crates/nodes/src/tests.rs index b9104c7..7cca901 100644 --- a/crates/nodes/src/tests.rs +++ b/crates/nodes/src/tests.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; +use craft_texture::{Image, Kind}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use super::*; @@ -69,14 +69,17 @@ fn every_node_cooks() { let result = cook(definition, &inputs, 32); if definition.id == "pixel_processor" { assert_eq!(result.unwrap_err(), "function has no result node"); + continue; } let outputs = result.unwrap_or_else(|error| panic!("{}: {error}", definition.id)); + assert_eq!(outputs.len(), definition.outputs.len().max(1), "{}", definition.id); + for image in &outputs { - assert_eq!((image.w, image.h), (32, 32), "{}", definition.id); - assert!(image.data.iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id); + assert_eq!((image.width(), image.height()), (32, 32), "{}", definition.id); + assert!(image.data().iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id); } } } @@ -134,8 +137,8 @@ fn every_node_survives_hostile_params() { } for img in &out { - assert_eq!((img.w, img.h), (16, 16), "{}.{}={h}", def.id, p.id); - assert!(img.data.iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id); + assert_eq!((img.width(), img.height()), (16, 16), "{}.{}={h}", def.id, p.id); + assert!(img.data().iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id); } } } @@ -168,7 +171,7 @@ fn blend_and_levels_math() { let out = (def.cook)(&ctx).unwrap(); - assert!((out[0].data[0] - 0.125).abs() < 1e-6); + assert!((out[0].data()[0] - 0.125).abs() < 1e-6); assert!((atomic::levels_fn(0.5, 0.0, 0.5, 1.0, 0.0, 1.0) - 0.5).abs() < 1e-5); assert_eq!(atomic::levels_fn(0.2, 0.4, 0.5, 0.8, 0.0, 1.0), 0.0); } @@ -180,7 +183,93 @@ fn dynamic_gradient_preserves_the_gradient_image_type() { let source = Image::filled(4, 4, Kind::Gray, [0.5; 4]); let gradient = Image::filled(4, 4, kind, [0.25, 0.5, 0.75, 1.0]); let result = cook(definition, &[Some(source), Some(gradient.clone())], 16).unwrap(); - assert_eq!(result[0].kind, kind); + + assert_eq!(result[0].kind(), kind); assert_eq!(result[0].get(0, 0, false), gradient.get(0, 0, false)); } } + +/// Cooks `def` at `w × h` without tiling, with `resource` as the package's bitmaps. +fn cook_sized(def: &NodeDefinition, inputs: &[Option], w: u32, h: u32, resource: &(dyn Fn(&str) -> Option + Sync)) -> CookResult { + let params = resolve_params(def, &BTreeMap::new()); + let vars = BTreeMap::new(); + let ctx = CookContext { format: materialcraft_core::OutputFormat::F32, w, h, seed: 7, tile: false, inputs, params: ¶ms, resource, vars: &vars }; + (def.cook)(&ctx) +} + +/// A request wider than the size limit spreads the normalized coordinates over the clamped width. +#[test] +fn an_oversized_transformation_covers_the_whole_input() { + let ramp = Image::gray(8192, 1, |x, _| x as f32 / 8191.0); + let out = cook_sized(find("transformation").unwrap(), &[Some(ramp)], 16384, 1, &|_| None).unwrap(); + let last = out[0].get(8191, 0, false)[0]; + + assert!(last > 0.99, "the last pixel reads the ramp at {last}"); +} + +/// Bilinear resampling between finite values of opposite sign near the float limit stays finite. +#[test] +fn transformation_resamples_extreme_neighbors_to_finite_values() { + let extremes = Image::gray(2, 1, |x, _| if x == 0 { f32::MAX } else { -f32::MAX }); + let out = cook_sized(find("transformation").unwrap(), &[Some(extremes)], 4, 1, &|_| None).unwrap(); + + for x in 0..4 { + let value = out[0].get(x, 0, false)[0]; + + assert!(value.is_finite(), "pixel {x} is {value}"); + } +} + +#[test] +fn nearest_transformation_mips_preserve_finite_hdr_constants() { + let definition = find("transformation").unwrap(); + let parameters = resolve_params(definition, &BTreeMap::from([("filtering".into(), Value::Enum(1))])); + let variables = BTreeMap::new(); + let value = 0.75 * f32::MAX; + + for kind in [Kind::Gray, Kind::Color] { + let inputs = [Some(Image::filled(16, 16, kind, [value; 4]))]; + let context = CookContext { + format: materialcraft_core::OutputFormat::F32, + w: 4, + h: 4, + seed: 7, + tile: false, + inputs: &inputs, + params: ¶meters, + resource: &|_| None, + vars: &variables, + }; + + let output = (definition.cook)(&context).unwrap().remove(0); + + assert_eq!((output.width(), output.height(), output.kind()), (4, 4, kind)); + assert!(output.data().iter().all(|pixel| *pixel == value), "{:?}", output.data()); + } +} + +/// A repeated input offset far past its edge keeps the offset's phase: an offset near 2^31 lands on +/// the same place as an offset of zero, halfway between the last and the first column. +#[test] +fn directional_warp_repeats_a_far_offset_with_its_phase() { + let stripes = Image::gray(3, 3, |x, _| [0.0, 1.0, 4.0][x as usize]); + + // Intensity 10 scales the map by 10 / 256, moving each pixel by about 2^31 + let far = Image::filled(3, 3, Kind::Gray, [2_147_483_648.0 * 25.6; 4]); + let out = cook(find("directional_warp").unwrap(), &[Some(stripes), Some(far)], 3).unwrap(); + + for x in 0..3 { + assert_eq!(out[0].get_gray(x, 1, false), 2.0, "pixel {x}"); + } +} + +/// Shrinking a bitmap of large HDR values averages them without overflowing. +#[test] +fn bitmap_shrinks_large_hdr_values_without_overflow() { + let hdr = |_: &str| Some(Image::filled(2, 2, Kind::Color, [0.75 * f32::MAX, 0.75 * f32::MAX, 0.75 * f32::MAX, 1.0])); + let out = cook_sized(find("bitmap").unwrap(), &[], 1, 1, &hdr).unwrap(); + let pixel = out[0].get(0, 0, false); + + assert!(pixel.iter().all(|value| value.is_finite()), "{pixel:?}"); + assert!((pixel[0] / (0.75 * f32::MAX) - 1.0).abs() < 1e-6, "{pixel:?}"); +} diff --git a/crates/nodes/tests/atomic_filter_parity.rs b/crates/nodes/tests/atomic_filter_parity.rs index ce507cd..20e2304 100644 --- a/crates/nodes/tests/atomic_filter_parity.rs +++ b/crates/nodes/tests/atomic_filter_parity.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{OutputFormat, Value}; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; use std::collections::BTreeMap; @@ -71,7 +71,7 @@ fn sharpen_preserves_finite_hdr_constant() { let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true); - assert!(output.data.iter().all(|value| value.to_bits() == constant.to_bits())); + assert!(output.data().iter().all(|value| value.to_bits() == constant.to_bits())); } #[test] @@ -92,7 +92,7 @@ fn blur_preserves_finite_hdr_constant() { let output = cook("blur", &[Some(input)], &[("intensity", Value::Float(64.0))], [16, 16], true); - assert!(output.data.iter().all(|value| value.is_finite() && (*value - 1.0e38).abs() < 1.0e32)); + assert!(output.data().iter().all(|value| value.is_finite() && (*value - 1.0e38).abs() < 1.0e32)); } #[test] @@ -116,7 +116,7 @@ fn sharpen_has_center_gain_and_clamps_negative_lobes() { let output = cook("sharpen", &[Some(input)], &[("intensity", Value::Float(1.0))], [16, 16], true); assert_eq!(output.get_gray(8, 8, false), 5.0); - assert!(output.data.iter().all(|value| *value >= 0.0)); + assert!(output.data().iter().all(|value| *value >= 0.0)); } #[test] diff --git a/crates/nodes/tests/brick_primitives.rs b/crates/nodes/tests/brick_primitives.rs index de22081..faa5baf 100644 --- a/crates/nodes/tests/brick_primitives.rs +++ b/crates/nodes/tests/brick_primitives.rs @@ -1,5 +1,5 @@ +use craft_texture::{Image, Kind}; use materialcraft_core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; use std::collections::BTreeMap; @@ -59,7 +59,7 @@ fn repeated_quadrants_have_distinct_reproducible_random_values() { let samples: Vec<_> = [(16, 16), (48, 16), (16, 48), (48, 48)].map(|(x, y)| image.get_gray(x, y, false)).into_iter().collect(); assert!(samples.windows(2).all(|pair| pair[0] != pair[1]), "{samples:?}"); - assert_eq!(image.data, cook("fx_map", values, &[]).data); + assert_eq!(image.data(), cook("fx_map", values, &[]).data()); } #[test] @@ -89,7 +89,7 @@ fn subpixel_quadrants_do_not_accumulate_at_shared_edges() { leaf.parameters.insert("opacity".into(), Value::Float(0.25)); let image = cook("fx_map", BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))]), &[]); - assert!(image.data.iter().all(|value| (*value - 0.25).abs() < 1e-6), "mean {}", image.mean()[0]); + assert!(image.data().iter().all(|value| (*value - 0.25).abs() < 1e-6), "mean {}", image.mean()[0]); } #[test] @@ -105,5 +105,5 @@ fn grayscale_max_patterns_do_not_accumulate_opacity() { graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(2)); let repeated = cook("fx_map", values(graph), &[]); - assert!(single.data == repeated.data, "repeating a maximum blend must not brighten the image"); + assert!(single.data() == repeated.data(), "repeating a maximum blend must not brighten the image"); } diff --git a/crates/nodes/tests/distance.rs b/crates/nodes/tests/distance.rs index c9f2baa..642d6f2 100644 --- a/crates/nodes/tests/distance.rs +++ b/crates/nodes/tests/distance.rs @@ -1,13 +1,13 @@ use std::collections::BTreeMap; +use craft_texture::{Image, Kind}; use materialcraft_core::Value; -use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find, resolve_params}; fn cook(mask: Image, source: Option, tile: bool, combine: bool, distance: f32) -> Image { let def = find("distance").unwrap(); let params = resolve_params(def, &BTreeMap::from([("distance".into(), Value::Float(distance)), ("combine".into(), Value::Bool(combine))])); - let (w, h) = (mask.w, mask.h); + let (w, h) = (mask.width(), mask.height()); let inputs = [Some(mask), source]; let vars = BTreeMap::new(); let resource = |_: &str| None; @@ -23,7 +23,7 @@ fn tiled_distance_spreads_source_across_stationary_gradient() { // A zero slope at the only mask pixel must not stop the walk on background assert_eq!(output.get_gray(16, 16, false), 1.0); - assert!(output.data.iter().all(|&v| v == 1.0)); + assert!(output.data().iter().all(|&v| v == 1.0)); } #[test] @@ -55,11 +55,14 @@ fn distance_handles_empty_full_masks_and_no_source() { let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]); let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]); let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]); - assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data.iter().all(|&v| v == 0.0)); + + assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data().iter().all(|&v| v == 0.0)); assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]); - assert!(cook(empty, None, tile, true, 256.0).data.iter().all(|&v| v == 0.0)); + assert!(cook(empty, None, tile, true, 256.0).data().iter().all(|&v| v == 0.0)); + let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); let ramp = cook(mask, None, tile, false, 512.0 / 7.0); + assert_eq!(ramp.get_gray(0, 0, false), 1.0); assert_eq!(ramp.get_gray(1, 0, false), 0.5); assert_eq!(ramp.get_gray(3, 0, false), 0.0); diff --git a/crates/nodes/tests/fx_map_opacity.rs b/crates/nodes/tests/fx_map_opacity.rs index d3d6544..75992c7 100644 --- a/crates/nodes/tests/fx_map_opacity.rs +++ b/crates/nodes/tests/fx_map_opacity.rs @@ -2,7 +2,7 @@ use materialcraft_core::{PatternGraph, PatternNodeKind, Value}; use materialcraft_nodes::{CookContext, find, resolve_params}; use std::collections::BTreeMap; -fn render(depth: usize, roughness: f32, stack: bool, color: Option<[f32; 4]>) -> materialcraft_image::Image { +fn render(depth: usize, roughness: f32, stack: bool, color: Option<[f32; 4]>) -> craft_texture::Image { let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); for index in 0..depth { let child = graph.add(PatternNodeKind::Quadrant).unwrap(); @@ -59,7 +59,7 @@ fn quadrant_opacity_matches_measured_depth_and_stack_values() { let image = render(depth, roughness, false, None); assert!( - image.data.iter().all(|value| (*value - expected).abs() < 2e-7), + image.data().iter().all(|value| (*value - expected).abs() < 2e-7), "roughness {roughness}, depth {depth}: {:?}, expected {expected}", image.mean() ); @@ -68,7 +68,7 @@ fn quadrant_opacity_matches_measured_depth_and_stack_values() { for roughness in [0.42, 1.0] { let image = render(4, roughness, true, None); - assert!(image.data.iter().all(|value| (*value - 0.125).abs() < 2e-7), "stack roughness {roughness}: {:?}", image.mean()); + assert!(image.data().iter().all(|value| (*value - 0.125).abs() < 2e-7), "stack roughness {roughness}: {:?}", image.mean()); } } diff --git a/crates/nodes/tests/fx_map_regions.rs b/crates/nodes/tests/fx_map_regions.rs index 5b28606..6f2e8dc 100644 --- a/crates/nodes/tests/fx_map_regions.rs +++ b/crates/nodes/tests/fx_map_regions.rs @@ -35,7 +35,7 @@ fn render_region_samples_a_cropped_area() { let crop = render([0.25, 0.75, 0.25, 0.75], identity, false).unwrap().remove(0); assert_eq!(full.mean()[0], 0.25); - assert!(crop.data.iter().all(|value| *value == 1.0)); + assert!(crop.data().iter().all(|value| *value == 1.0)); } #[test] @@ -47,7 +47,7 @@ fn tiling_region_sets_repeat_distance_independently_of_render_region() { assert_eq!(repeated.get(48, 32, false)[0], 1.0); assert_eq!(wider.get(48, 32, false)[0], 0.0); - assert_eq!(wider.data, untiled.data); + assert_eq!(wider.data(), untiled.data()); assert_eq!(repeated.mean()[0], 0.25); assert_eq!(wider.mean()[0], 0.125); } diff --git a/crates/nodes/tests/parity_unconnected.rs b/crates/nodes/tests/parity_unconnected.rs index f34bcc8..bb24cb8 100644 --- a/crates/nodes/tests/parity_unconnected.rs +++ b/crates/nodes/tests/parity_unconnected.rs @@ -1,5 +1,5 @@ +use craft_texture::Kind; use materialcraft_core::{OutputFormat, Value}; -use materialcraft_image::Kind; use materialcraft_nodes::{CookContext, find, resolve_params}; use std::collections::BTreeMap; @@ -21,7 +21,8 @@ fn absent_textures_have_zero_pixels_and_expected_kinds() { let outputs = (definition.cook)(&context).unwrap(); let image = outputs.first().unwrap(); - assert_eq!(image.kind, kind, "{id}"); + assert_eq!(image.kind(), kind, "{id}"); + for y in 0..h { for x in 0..w { assert_eq!(image.get(x.into(), y.into(), false), pixel, "{id} at {x},{y}"); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index a2fe2a0..5e6791c 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -11,5 +11,5 @@ workspace = true [dependencies] materialcraft-core = { workspace = true } materialcraft-geom = { workspace = true } -materialcraft-image = { workspace = true } +craft-texture = { workspace = true } rayon = { workspace = true } diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 41d0d72..25c88ff 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -8,9 +8,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use crate::{Displacement, Relief}; +use craft_texture::{Image, linear_to_srgb}; use materialcraft_geom::glam::{Vec2, Vec3}; use materialcraft_geom::{Bvh, Mesh, OrbitCamera}; -use materialcraft_image::{Image, linear_to_srgb}; use rayon::prelude::*; use crate::ibl::{self, EnvImage}; @@ -94,8 +94,9 @@ impl Scene { mesh = mesh.subdivided(); } - // Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette - let height = height.resize(height.w.min(512), height.h.min(512), true); + // Filter detail finer than the mesh to prevent silhouette spikes + const MAX_HEIGHT_MAP_SIDE: u32 = 512; + let height = height.resize(height.width().min(MAX_HEIGHT_MAP_SIDE), height.height().min(MAX_HEIGHT_MAP_SIDE), true); let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 }; let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 }; let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 }; @@ -495,52 +496,52 @@ pub fn render(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32 /// [`render`] that gives up once `cancel` is set (rows not yet started are skipped) and then /// returns `None`: a frame the viewer no longer needs (the camera moved, the view was resized) /// stops holding the CPU. -pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option> { +pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, settings: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option> { let (w, h) = (w.clamp(1, 4096), h.clamp(1, 4096)); - let cam = camera(scene, s); + let camera = camera(scene, settings); let aspect = w as f32 / h as f32; - let ss = s.supersample.clamp(1, 4); - let k = 2f32.powf(s.exposure); - let bg_env = light.specular.get(3).or(light.specular.last()); + let samples_per_axis = settings.supersample.clamp(1, 4); + let exposure_scale = 2f32.powf(settings.exposure); + let background_environment = light.specular.get(3).or(light.specular.last()); // Key light from the camera's upper left, a little in front of the subject - let fwd = cam.ray(Vec2::ZERO, aspect).dir; - let right = fwd.cross(Vec3::Y).normalize_or(Vec3::X); - let key = (right * -0.6 + right.cross(fwd) * 0.75 - fwd * 0.5).normalize_or_zero(); - let mut out = vec![0u8; (w * h * 4) as usize]; - out.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| { + let forward = camera.ray(Vec2::ZERO, aspect).dir; + let right = forward.cross(Vec3::Y).normalize_or(Vec3::X); + let key = (right * -0.6 + right.cross(forward) * 0.75 - forward * 0.5).normalize_or_zero(); + let mut output = vec![0u8; (w * h * 4) as usize]; + output.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| { if cancel.load(Ordering::Relaxed) { return; } for x in 0..w as usize { - let mut acc = Vec3::ZERO; - for sy in 0..ss { - for sx in 0..ss { - let px = (x as f32 + (sx as f32 + 0.5) / ss as f32) / w as f32 * 2.0 - 1.0; - let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0; - let ray = cam.ray(Vec2::new(px, py), aspect); - let bg = backdrop(Vec2::new(px, py)); - let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) }; - let miss = match (s.show_env, bg_env) { - (true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k, - _ => bg, + let mut accumulated = Vec3::ZERO; + for sy in 0..samples_per_axis { + for sx in 0..samples_per_axis { + let px = (x as f32 + (sx as f32 + 0.5) / samples_per_axis as f32) / w as f32 * 2.0 - 1.0; + let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / samples_per_axis as f32) / h as f32 * 2.0; + let ray = camera.ray(Vec2::new(px, py), aspect); + let background = backdrop(Vec2::new(px, py)); + let p = Px { key, jitter: jitter(x as u32 * samples_per_axis + sx, y as u32 * samples_per_axis + sy) }; + let miss = match (settings.show_env, background_environment) { + (true, Some(e)) => e.sample(rotate_y(ray.dir, -settings.env_rotation)) * exposure_scale, + _ => background, }; - acc += if s.alpha_view { + accumulated += if settings.alpha_view { // Display values: the alpha as is, the background tone mapped - match shade(scene, maps, light, s, ray.origin, ray.dir, &p) { + match shade(scene, maps, light, settings, ray.origin, ray.dir, &p) { Some(h) => h.color, None => miss.map(|v| linear_to_srgb(aces(v))), } } else { - trace(scene, maps, light, s, ray.origin, ray.dir, &p, k, miss) + trace(scene, maps, light, settings, ray.origin, ray.dir, &p, exposure_scale, miss) }; } } - let c = acc / (ss * ss) as f32; + let c = accumulated / (samples_per_axis * samples_per_axis) as f32; let q = |v: f32| { - let d = if s.alpha_view { v } else { linear_to_srgb(aces(v)) }; + let d = if settings.alpha_view { v } else { linear_to_srgb(aces(v)) }; (d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 }; if let Some(px) = row.get_mut(x * 4..x * 4 + 4) { @@ -548,13 +549,13 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett } } }); - if cancel.load(Ordering::Relaxed) { None } else { Some(out) } + if cancel.load(Ordering::Relaxed) { None } else { Some(output) } } #[cfg(test)] mod tests { use super::*; - use materialcraft_image::Kind; + use craft_texture::Kind; #[test] fn renders_a_material_on_every_scene() { diff --git a/crates/ui-egui/src/export/export_tests.rs b/crates/ui-egui/src/export/export_tests.rs index 28d6efd..9dd5f5b 100644 --- a/crates/ui-egui/src/export/export_tests.rs +++ b/crates/ui-egui/src/export/export_tests.rs @@ -77,8 +77,11 @@ fn batch_writes_every_material_graph_at_the_output_size() { assert!(export(&mut app, &settings)); assert_eq!(files(&directory), ["New_graph_base_color.png", "New_graph_height.png", "Second_mask.png"]); + let image = materialcraft_engine::formats::decode(&std::fs::read(directory.join("Second_mask.png")).unwrap(), true).unwrap(); - assert_eq!((image.w, image.h), (64, 32)); + + assert_eq!((image.width(), image.height()), (64, 32)); + let _ = std::fs::remove_dir_all(directory); } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index ae90ef8..9d607d8 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -50,9 +50,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let theme = Tokens::get(ui.ctx()); - let ctx = ui.ctx().clone(); - let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Node graph"); + let context = ui.ctx().clone(); + let (rect, response) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Node graph"); app.graph.view = rect; if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) { app.ui.frame_all = false; @@ -69,7 +69,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { camera.zoom_from_input(ui, rect); app.ui.graph_camera = camera.state(); super::grid::paint(&painter, &camera, rect); - let pointer = ctx.input(|input| input.pointer.hover_pos()); + let pointer = context.input(|input| input.pointer.hover_pos()); let show_thumbnails = app.ui.prefs.thumbnails; let Ok(graph) = app.session.graph() else { return }; @@ -82,7 +82,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { }; // Layout every node and its ports - let mut layouts: Vec = Vec::with_capacity(graph.nodes.len()); for node in &graph.nodes { let (ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); @@ -211,24 +210,29 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { dot_grabs.push(grab); } - let resp = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Button, &node_label(node)); + let response = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Button, &node_label(node)); if node.def == "dot" { node_card::paint_dot(&painter, screen_rect, if selected { theme.accent } else { Color32::from_gray(0xb4) }); } else { node_card::paint(&painter, screen_rect, camera.zoom, &node_label(node), header_color(&node.def)); let header = node_card::header(screen_rect, camera.zoom); let body = node_card::body(screen_rect, camera.zoom); - if let Some(r0) = result - && let Some(img) = r0.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image) + if let Some(node_result) = result + && let Some(image) = node_result.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image) && show_thumbnails && !app.graph.thumbnails_cleared { let side = body.width().min(body.height()) - 6.0 * camera.zoom; - let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); - node_card::paint_well(&painter, tr_.expand(camera.zoom), camera.zoom); - let tex = app.thumbs.node(&ctx, r0.key, 0, img); - painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if node.disabled { Color32::from_gray(90) } else { Color32::WHITE }); + let thumbnail_rect = Rect::from_center_size(body.center(), vec2(side, side)); + node_card::paint_well(&painter, thumbnail_rect.expand(camera.zoom), camera.zoom); + let texture = app.thumbs.node(&context, node_result.key, 0, image); + painter.image( + texture, + thumbnail_rect, + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + if node.disabled { Color32::from_gray(90) } else { Color32::WHITE }, + ); } else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) { node_card::paint_well(&painter, body.shrink(4.0 * camera.zoom), camera.zoom); node_card::paint_symbol(&painter, body, camera.zoom, &super::value_text::value_text(value), theme.text_strong); @@ -240,25 +244,25 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Footer: size and format let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max); - if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { + if let Some(image) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { let bits = result.map_or(graph.format.bits(), |result| result.base.format.bits()); - let format = format!("{}{bits}", if img.is_gray() { "L" } else { "C" }); - let txt = if let Some(limit) = app.session.preview_size { + let format = format!("{}{bits}", if image.is_gray() { "L" } else { "C" }); + let label_text = if let Some(limit) = app.session.preview_size { let [width, height] = graph.size_px(); - resp.clone().on_hover_text(format!( + response.clone().on_hover_text(format!( "{} x {} ({bits}bpc)\n{}: {width} x {height}\n{}: {limit} px\n{}", - img.w, - img.h, + image.width(), + image.height(), tr("Parent size"), tr("Preview limit"), tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.") )); - format!("{}x{} {}", img.w, img.h, tr("Preview")) + format!("{}x{} {}", image.width(), image.height(), tr("Preview")) } else { - format!("{}x{} - {format}", img.w, img.h) + format!("{}x{} - {format}", image.width(), image.height()) }; - painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim); + painter.text(footer.center(), Align2::CENTER_CENTER, label_text, small.clone(), theme.text_dim); } if node.def == "output" { painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE); @@ -267,7 +271,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0)) } else if selected { Stroke::new(2.0, theme.accent) - } else if resp.hovered() { + } else if response.hovered() { Stroke::new(1.0, Color32::from_gray(0x90)) } else { Stroke::new(1.0, Color32::from_gray(0x10)) @@ -278,11 +282,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { painter.line_segment([screen_rect.left_top(), screen_rect.right_bottom()], Stroke::new(1.5, theme.danger)); } if let Some(e) = error { - resp.clone().on_hover_text(e); + response.clone().on_hover_text(e); } } - node_responses.push((node.id, resp)); + node_responses.push((node.id, response)); } let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera); @@ -318,11 +322,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // A wire under a comment is not hit let wire_hover = wire_hover.filter(|_| !pointer.is_some_and(|p| comment_hits.iter().any(|(_, r)| r.contains(p)))); if wire_hover.is_some() { - ctx.set_cursor_icon(egui::CursorIcon::PointingHand); + context.set_cursor_icon(egui::CursorIcon::PointingHand); } app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); - super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover); + super::input::handle(app, ui, &response, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover); app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); // GraphDrag previews diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index 986edb7..707270b 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -15,20 +15,20 @@ pub const BINS: usize = 256; const MIN_SPAN: f32 = 0.004; /// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B -pub fn histogram(img: &Image) -> Vec<[u32; BINS]> { - let channels = if img.kind == Kind::Gray { 1 } else { 3 }; - let stride = img.kind.channels(); - let mut h = vec![[0u32; BINS]; channels]; - for px in img.data.chunks(stride) { - for (c, bins) in h.iter_mut().enumerate() { - let v = px.get(c).copied().unwrap_or(0.0); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if let Some(b) = bins.get_mut(((v * (BINS - 1) as f32).round() as usize).min(BINS - 1)) { - *b = b.saturating_add(1); +pub fn histogram(image: &Image) -> Vec<[u32; BINS]> { + let channels = if image.kind() == Kind::Gray { 1 } else { 3 }; + let stride = image.channels(); + let mut histograms = vec![[0u32; BINS]; channels]; + for pixel in image.data().chunks(stride) { + for (channel, bins) in histograms.iter_mut().enumerate() { + let value = pixel.get(channel).copied().unwrap_or(0.0); + let value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + if let Some(bin) = bins.get_mut(((value * (BINS - 1) as f32).round() as usize).min(BINS - 1)) { + *bin = bin.saturating_add(1); } } } - h + histograms } /// The bar height scale: the tallest bin away from pure black and white (masks pile up there and would flatten everything else), at least one diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 7971ca0..81e7c90 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -38,27 +38,34 @@ pub fn title(app: &MaterialCraftApp) -> String { format!("{} - {}", name.unwrap_or_default(), tr("2D View")) } -fn rgba8(img: &Image, channel: &str) -> Vec { - let base = img.to_rgba8_display(); - let pick = match channel { +fn rgba8(image: &Image, channel: &str) -> Vec { + let mut pixels = image.to_rgba8_display(); + let selected = match channel { "r" => Some(0), "g" => Some(1), "b" => Some(2), "a" => Some(3), _ => None, }; - match pick { - Some(k) if img.kind == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(), - _ => base, + + if let Some(channel) = selected + && image.kind() == Kind::Color + { + for pixel in pixels.as_chunks_mut::<4>().0 { + let value = pixel[channel]; + pixel.copy_from_slice(&[value, value, value, u8::MAX]); + } } + + pixels } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let ctx = ui.ctx().clone(); + let theme = Tokens::get(ui.ctx()); + let context = ui.ctx().clone(); // Toolbar - egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + egui::Frame::NONE.fill(theme.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { ui.horizontal(|ui| { crate::preview_resolution::show(app, ui); for (c, label) in [("rgba", "RGBA"), ("r", "R"), ("g", "G"), ("b", "B"), ("a", "A")] { @@ -87,89 +94,90 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); }); - let Some((id, img)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else { - let (r, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover()); - crate::widgets::name(&resp, egui::Role::Image, "2D view"); - ui.painter().rect_filled(r, 0.0, tk.viewport); - ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), tk.viewport_text); + let Some((id, image)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else { + let (r, response) = ui.allocate_exact_size(ui.available_size(), Sense::hover()); + crate::widgets::name(&response, egui::Role::Image, "2D view"); + ui.painter().rect_filled(r, 0.0, theme.viewport); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), theme.viewport_text); return; }; - let texture_limit = ctx.input(|i| i.max_texture_side).max(1); + let texture_limit = context.input(|i| i.max_texture_side).max(1); let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) ^ (texture_limit as u64).rotate_left(32) - ^ (img.w as u64).rotate_left(16) - ^ img.h as u64 + ^ (image.width() as u64).rotate_left(16) + ^ image.height() as u64 ^ (app.session.view2d.port as u64).wrapping_mul(0x9e37) ^ (app.session.view2d.channel.len() as u64 * 31) ^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64; if app.view2d.tex.as_ref().is_none_or(|(k, _)| *k != key) { - let px = rgba8(&img, &app.session.view2d.channel); + let pixels = rgba8(&image, &app.session.view2d.channel); // Keep source pixels for readout/screenshots, but respect the renderer's upload limit - let ci = if img.w.max(img.h) as usize > texture_limit { - let scale = texture_limit as f64 / f64::from(img.w.max(img.h)); - let display = img.resize((f64::from(img.w) * scale).floor().max(1.0) as u32, (f64::from(img.h) * scale).floor().max(1.0) as u32, false); - ColorImage::from_rgba_unmultiplied([display.w as usize, display.h as usize], &rgba8(&display, &app.session.view2d.channel)) + let color_image = if image.width().max(image.height()) as usize > texture_limit { + let scale = texture_limit as f64 / f64::from(image.width().max(image.height())); + let display = + image.resize((f64::from(image.width()) * scale).floor().max(1.0) as u32, (f64::from(image.height()) * scale).floor().max(1.0) as u32, false); + ColorImage::from_rgba_unmultiplied([display.width() as usize, display.height() as usize], &rgba8(&display, &app.session.view2d.channel)) } else { - ColorImage::from_rgba_unmultiplied([img.w as usize, img.h as usize], &px) + ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], &pixels) }; - app.view2d.tex = Some((key, ctx.load_texture("view2d", ci, TextureOptions::NEAREST))); - app.view2d.shown = Some((img.w, img.h, px)); + app.view2d.tex = Some((key, context.load_texture("view2d", color_image, TextureOptions::NEAREST))); + app.view2d.shown = Some((image.width(), image.height(), pixels)); } - let avail = ui.available_size(); - let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 20.0).max(40.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Image, "2D view"); + let available = ui.available_size(); + let (rect, response) = ui.allocate_exact_size(vec2(available.x, (available.y - 20.0).max(40.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Image, "2D view"); let p = ui.painter_at(rect); - p.rect_filled(rect, 0.0, tk.viewport); + p.rect_filled(rect, 0.0, theme.viewport); // Camera: fit, wheel zoom around the pointer, drag to pan app.ui.image_camera = app.ui.image_camera.sanitized(); - let cam = &mut app.ui.image_camera; + let camera = &mut app.ui.image_camera; let tiles = if app.session.view2d.tiled { 3.0 } else { 1.0 }; - let fit_zoom = ((rect.width() - 16.0) / (img.w as f32 * tiles)).min((rect.height() - 16.0) / (img.h as f32 * tiles)).max(0.01); - if cam.fit { - cam.zoom = fit_zoom; - cam.offset = [0.0, 0.0]; + let fit_zoom = ((rect.width() - 16.0) / (image.width() as f32 * tiles)).min((rect.height() - 16.0) / (image.height() as f32 * tiles)).max(0.01); + if camera.fit { + camera.zoom = fit_zoom; + camera.offset = [0.0, 0.0]; } - if resp.hovered() { + if response.hovered() { let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll.abs() > 0.0 { - cam.fit = false; - let old = cam.zoom; - cam.zoom = (cam.zoom * (scroll * 0.003).exp()).clamp(0.02, 64.0); - if let Some(ptr) = resp.hover_pos() { - let c = rect.center() + vec2(cam.offset[0], cam.offset[1]); + camera.fit = false; + let old = camera.zoom; + camera.zoom = (camera.zoom * (scroll * 0.003).exp()).clamp(0.02, 64.0); + if let Some(ptr) = response.hover_pos() { + let c = rect.center() + vec2(camera.offset[0], camera.offset[1]); let d = ptr - c; - let k = cam.zoom / old; - cam.offset = [cam.offset[0] - d.x * (k - 1.0), cam.offset[1] - d.y * (k - 1.0)]; + let k = camera.zoom / old; + camera.offset = [camera.offset[0] - d.x * (k - 1.0), camera.offset[1] - d.y * (k - 1.0)]; } } } - if resp.dragged() { - cam.fit = false; - let d = resp.drag_delta(); - cam.offset = [cam.offset[0] + d.x, cam.offset[1] + d.y]; + if response.dragged() { + camera.fit = false; + let d = response.drag_delta(); + camera.offset = [camera.offset[0] + d.x, camera.offset[1] + d.y]; } - let size = vec2(img.w as f32, img.h as f32) * cam.zoom; - let center = rect.center() + vec2(cam.offset[0], cam.offset[1]); + let size = vec2(image.width() as f32, image.height() as f32) * camera.zoom; + let center = rect.center() + vec2(camera.offset[0], camera.offset[1]); let full = Rect::from_center_size(center, size * tiles); // A checker behind transparent images - if img.kind == Kind::Color && app.session.view2d.channel == "rgba" { + if image.kind() == Kind::Color && app.session.view2d.channel == "rgba" { let cell = 8.0; - let vis = full.intersect(rect); - let mut y = vis.top(); + let visible = full.intersect(rect); + let mut y = visible.top(); let mut row = 0; - while y < vis.bottom() { - let mut x = vis.left() + if row % 2 == 0 { 0.0 } else { cell }; - while x < vis.right() { - p.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell, cell)).intersect(vis), 0.0, Color32::from_gray(0x55)); + while y < visible.bottom() { + let mut x = visible.left() + if row % 2 == 0 { 0.0 } else { cell }; + while x < visible.right() { + p.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell, cell)).intersect(visible), 0.0, Color32::from_gray(0x55)); x += cell * 2.0; } y += cell; @@ -188,26 +196,35 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } if app.session.view2d.histogram { - let single = img.is_gray() || app.session.view2d.channel != "rgba"; + let single = image.is_gray() || app.session.view2d.channel != "rgba"; draw_histogram(&mut app.view2d, &p, rect, key, single); } // Info line: size, format, zoom and the pixel under the pointer let info = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 20.0)); let bits = app.session.cooked.nodes.get(&id).map_or("16", |result| result.base.format.bits()); - let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); - if let Some(ptr) = resp.hover_pos() { - let local = (ptr - (center - size * 0.5)) / cam.zoom; + let mut text = + format!("{} x {} ({}, {}bpc) {:.0}%", image.width(), image.height(), if image.is_gray() { "L" } else { "RGBA" }, bits, camera.zoom * 100.0); + if let Some(ptr) = response.hover_pos() { + let local = (ptr - (center - size * 0.5)) / camera.zoom; let (x, y) = (local.x.floor() as i64, local.y.floor() as i64); - let v = img.get(x, y, true); - if img.is_gray() { - text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.w as i64), y.rem_euclid(img.h as i64), v[0]); + let v = image.get(x, y, true); + if image.is_gray() { + text += &format!(" ({}, {}) {:.3}", x.rem_euclid(image.width() as i64), y.rem_euclid(image.height() as i64), v[0]); } else { - text += &format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.w as i64), y.rem_euclid(img.h as i64), v[0], v[1], v[2], v[3]); + text += &format!( + " ({}, {}) {:.3} {:.3} {:.3} {:.3}", + x.rem_euclid(image.width() as i64), + y.rem_euclid(image.height() as i64), + v[0], + v[1], + v[2], + v[3] + ); } } - ui.painter().rect_filled(info, 0.0, tk.panel); - ui.painter().text(info.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(11.0), tk.text_dim); + ui.painter().rect_filled(info, 0.0, theme.panel); + ui.painter().text(info.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(11.0), theme.text_dim); } /// The histogram card in the view's bottom-right corner, computed once per shown image. diff --git a/crates/ui-egui/tests/it/preview_resolution.rs b/crates/ui-egui/tests/it/preview_resolution.rs index 59c3532..2513aca 100644 --- a/crates/ui-egui/tests/it/preview_resolution.rs +++ b/crates/ui-egui/tests/it/preview_resolution.rs @@ -48,27 +48,33 @@ fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec { fn node_resolution_explains_the_preview_cap() { let (mut h, id) = harness(512, false); let img = h.state().session.cooked.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (512, 512)); + + assert_eq!((img.width(), img.height()), (512, 512)); assert_eq!(h.state().session.graph().unwrap().size, [10, 10]); assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h)); + let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; h.event(Event::PointerMoved(rect.center())); h.run_steps(90); let text = painted(&h).join("\n"); + assert!(text.contains("Parent size: 1024 x 1024"), "{text}"); assert!(text.contains("Preview limit: 512 px"), "{text}"); assert!(text.contains("Edit > Preferences"), "{text}"); assert!(text.contains("16bpc"), "format information lost: {text}"); + let full = h.state().session.cook_full(0); let img = full.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (1024, 1024)); + + assert_eq!((img.width(), img.height()), (1024, 1024)); } #[test] fn full_size_mode_retains_the_resolution_and_format() { let (h, id) = harness(0, false); let img = h.state().session.cooked.image(id, 0).unwrap(); - assert_eq!((img.w, img.h), (1024, 1024)); + + assert_eq!((img.width(), img.height()), (1024, 1024)); assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h)); assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview")); } diff --git a/crates/ui-egui/tests/it/resolution.rs b/crates/ui-egui/tests/it/resolution.rs index 64231d5..974f819 100644 --- a/crates/ui-egui/tests/it/resolution.rs +++ b/crates/ui-egui/tests/it/resolution.rs @@ -19,14 +19,17 @@ fn choose_4k(h: &mut Harness<'static, MaterialCraftApp>) { h.run(); h.get_by_label("4096 px").click(); h.run(); + assert_eq!(h.state().session.preview_size, Some(4096)); assert_eq!(h.state().ui.prefs.preview_size, 4096); + h.state_mut().session.cook(); h.step(); let app = h.state(); let (_, image) = app.session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (4096, 4096)); - assert!(app.session.material_maps().iter().all(|(_, image)| (image.w, image.h) == (4096, 4096))); + + assert_eq!((image.width(), image.height()), (4096, 4096)); + assert!(app.session.material_maps().iter().all(|(_, image)| (image.width(), image.height()) == (4096, 4096))); assert!(!app.session.material_maps().is_empty()); assert_eq!(app.view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); } @@ -58,7 +61,8 @@ fn four_k_preview_refreshes_texture_after_size_change() { app(), ); h.input_mut().max_texture_side = Some(4096); - // The cooked key alone does not name the input size, so changing size must still refresh. + + // The cooked key alone does not name the input size, so changing size must still refresh let node = h.state().session.view2d.node.unwrap(); h.state_mut().session.preview_size = Some(4096); h.state_mut().session.cook(); @@ -66,15 +70,18 @@ fn four_k_preview_refreshes_texture_after_size_change() { h.state_mut().ui.prefs.preview_size = 4096; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (4096, 4096)); + + assert_eq!((image.width(), image.height()), (4096, 4096)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); + h.state_mut().session.preview_size = Some(256); h.state_mut().session.cook(); h.state_mut().session.cooked.nodes.get_mut(&node).unwrap().key = 0; h.state_mut().ui.prefs.preview_size = 256; h.step(); let (_, image) = h.state().session.view2d_image().unwrap(); - assert_eq!((image.w, image.h), (256, 256)); + + assert_eq!((image.width(), image.height()), (256, 256)); assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256))); } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 93dfd96..aa24a2b 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1292,13 +1292,14 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { app.run("view.2d", json!({"node": source})).unwrap(); app.run("graph.select", json!({"ids": [source]})).unwrap(); app.session.cook(); - let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); + let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); let view3d = serde_json::to_value(&app.session.view3d).unwrap(); let mut harness = harness(app, 1600.0, 960.0); settle(&mut harness, 5); let query = By::new().role(egui::accesskit::Role::TreeItem).label("Base Color"); let position = harness.get(query.clone()).rect().center(); click_canvas(&mut harness, position); + assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(source)]); assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(source))); assert!(!harness.state().graph.ports.iter().any(|port| port.node.0 == output && port.output)); @@ -1313,12 +1314,16 @@ fn named_outputs_select_without_loading_and_open_on_double_click() { harness.step(); } settle(&mut harness, 3); + assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(output))); assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]); assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); assert_eq!(serde_json::to_value(&harness.state().session.view3d).unwrap(), view3d); - let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::>(); + + let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::>(); + assert_eq!(current, material); + save(&mut harness, &directory, "named-output-preview"); } diff --git a/crates/ui-egui/tests/snapshot/parameter_functions.rs b/crates/ui-egui/tests/snapshot/parameter_functions.rs index b5267dd..37bfc14 100644 --- a/crates/ui-egui/tests/snapshot/parameter_functions.rs +++ b/crates/ui-egui/tests/snapshot/parameter_functions.rs @@ -4,6 +4,16 @@ use materialcraft_engine::core::{BaseParameter, NodeId}; use materialcraft_ui_egui::{MaterialCraftApp, UiState}; use serde_json::json; +fn wait_for_cook(harness: &mut egui_kittest::Harness<'static, MaterialCraftApp>) { + // Cook errors can move Properties controls before a queued pointer click + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while (harness.state().cooker.busy() || harness.state().session.dirty) && std::time::Instant::now() < deadline { + settle(harness, 1); + } + + assert!(!harness.state().cooker.busy() && !harness.state().session.dirty, "the parameter preview cook must complete"); +} + #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn parameter_functions_create_edit_reset_and_return_to_the_owner() { @@ -14,6 +24,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { let owner = NodeId(app.run("graph.node.add", json!({"def": "directional_blur"})).unwrap()["id"].as_u64().unwrap()); let mut harness = harness(app, 1600.0, 1100.0); settle(&mut harness, 8); + wait_for_cook(&mut harness); let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); for parameter in BaseParameter::ALL { let label = format!("Parameter actions: {}", parameter.label()); @@ -34,6 +45,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { save(&mut harness, &directory, "parameter-function-menu"); harness.get(button("Empty function")).click(); settle(&mut harness, 5); + wait_for_cook(&mut harness); assert!(harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize].nodes.is_empty()); assert_eq!(harness.state().function_editor.as_ref().unwrap().node, Some(owner)); @@ -68,12 +80,14 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { settle(&mut harness, 8); harness.get(button("Reset to default")).click(); settle(&mut harness, 8); + wait_for_cook(&mut harness); harness.get(button("Parameter actions: Output size")).click(); settle(&mut harness, 8); save(&mut harness, &directory, "parameter-after-reset-menu"); assert!(harness.query(button("Constant value")).is_some(), "the reset parameter menu must offer a constant"); harness.get(button("Constant value")).click(); settle(&mut harness, 4); + wait_for_cook(&mut harness); let function = &harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize]; assert_eq!(function.nodes.len(), 1); @@ -93,6 +107,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() { settle(&mut harness, 3); harness.get(button("Constant value")).click(); settle(&mut harness, 4); + wait_for_cook(&mut harness); assert!(harness.query(By::new().label("Expected output: Float")).is_some()); assert!(harness.state().session.graph().unwrap().node(owner).unwrap().functions.contains_key("angle")); save(&mut harness, &directory, "parameter-specific-function"); diff --git a/docs/architecture.md b/docs/architecture.md index c9fec52..9d222d6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,8 +9,8 @@ them). Everything below the UI is plain Rust with no UI toolkit and builds for ```text L0 core document model: Package → Graph → Node / Connection / Frame / Comment / Pin / ExposedParameter; Value (float, vectors, int, bool, color, enum, text, curve, gradient, function graph) -L0 image Image: grayscale or RGBA f32 planes behind an Arc (copy-on-write, free to share); - wrap/clamp sampling, bilinear, box/bilinear resampling, sRGB, 8-bit display +L0 image the craft-texture crate from storytold/craft-libs: grayscale or RGBA f32 planes behind an + Arc (free to share); repeat/clamp sampling, bilinear, box/bilinear resampling, sRGB, 8-bit display L0 geom meshes, primitives (rounded cube, sphere, cylinder, plane, torus, material ball), BVH, camera L1 nodes 29 main-graph entries (NodeDefinition), 85 function operations, four pattern node kinds; shared image operations and iterative function/pattern execution diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 99f4764..4d74850 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -12,7 +12,7 @@ use serde_json::Value; /// Library crates by directory under `crates/` (package `materialcraft-`) and their layer. pub const TABLE: &[(&str, u8)] = - &[("core", 0), ("image", 0), ("geom", 0), ("nodes", 1), ("eval", 2), ("formats", 2), ("engine", 3), ("render", 3), ("automation", 4), ("ui-egui", 5)]; + &[("core", 0), ("geom", 0), ("nodes", 1), ("eval", 2), ("formats", 2), ("engine", 3), ("render", 3), ("automation", 4), ("ui-egui", 5)]; /// Binaries and build tooling on top of every layer: exempt from the rules. pub const EXEMPT: &[&str] = &["materialcraft", "materialcraft-cli", "materialcraft-web", "xtask"]; @@ -149,12 +149,13 @@ mod tests { fn downward_graph_passes() { let g = [ c("materialcraft-core", &[("serde", Normal, false)]), - c("materialcraft-nodes", &[("materialcraft-core", Normal, true), ("materialcraft-image", Normal, true)]), + c("materialcraft-nodes", &[("materialcraft-core", Normal, true), ("materialcraft-geom", Normal, true)]), c("materialcraft-engine", &[("materialcraft-eval", Normal, true), ("materialcraft-geom", Dev, true)]), c("materialcraft-render", &[("materialcraft-nodes", Normal, true), ("wgpu", Normal, false)]), c("materialcraft-ui-egui", &[("materialcraft-automation", Normal, true), ("egui", Normal, false), ("wgpu", Normal, false)]), c("materialcraft", &[("eframe", Normal, false), ("materialcraft-ui-egui", Normal, true), ("winresource", Build, false)]), ]; + assert!(check(&g).is_empty(), "{:?}", check(&g)); } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index b4ca9c6..5b20a2c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -115,7 +115,6 @@ fn cmd_layers() -> Result<(), String> { /// Packages that must build for wasm32-unknown-unknown, in dependency order. const WASM_PACKAGES: &[&str] = &[ "materialcraft-core", - "materialcraft-image", "materialcraft-geom", "materialcraft-nodes", "materialcraft-eval",