From 257ab55a686e43e49bb1aa20f8d96e29f3475946 Mon Sep 17 00:00:00 2001 From: AndreIsraelAO Date: Mon, 2 Nov 2026 22:59:57 -0300 Subject: [PATCH 01/91] Add Export outputs to the explorer graph context menu Fixes #22 --- crates/ui-egui/src/explorer.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index d0f4940e..8c50b844 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -55,7 +55,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { open = Some(i); } resp.context_menu(|ui| { - for (label, a) in [("Open", "open"), ("Duplicate", "duplicate"), ("Delete", "delete")] { + for (label, a) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { if ui.button(tr(label)).clicked() { action = Some((a, i)); ui.close(); @@ -70,6 +70,11 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { Some(("open", i)) => { app.run("graph.open", json!({"graph": i})); } + Some(("export", i)) => { + // The export window works on the open graph. + app.run("graph.open", json!({"graph": i})); + app.ui.windows.export = true; + } Some(("duplicate", i)) => { app.run("graph.duplicate", json!({"graph": i})); } From 3a104b4e724d82b1b57ca6ed17b80d87322057c8 Mon Sep 17 00:00:00 2001 From: AndreIsraelAO Date: Tue, 3 Nov 2026 00:26:12 -0300 Subject: [PATCH 02/91] Add a resolution option to Export outputs Adds size to file.export and a Resolution selector to the export window. Only open the export window when the graph opened. Refs #22 --- crates/automation/src/headless.rs | 4 ++-- crates/engine/src/file_cmds.rs | 28 +++++++++++++++++++--------- crates/engine/tests/session.rs | 5 +++++ crates/ui-egui/src/explorer.rs | 5 +++-- crates/ui-egui/src/state.rs | 3 +++ crates/ui-egui/src/web_files.rs | 2 +- crates/ui-egui/src/windows.rs | 14 ++++++++++++-- 7 files changed, 45 insertions(+), 16 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 3443f3f9..dc510b82 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -170,8 +170,8 @@ impl Headless { /// Export every output of a graph into folder `dir`. pub fn export(&mut self, p: &Value) -> Result { let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("`dir` is required"))?; - let (gi, ext, pattern, depth) = file_cmds::export_params(&self.session, p)?; - let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth)?; + let (gi, ext, pattern, depth, size) = file_cmds::export_params(&self.session, p)?; + let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth, size)?; self.create_dir_all(dir)?; let mut written = Vec::new(); for f in files { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 392e3b49..e1af7462 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -31,7 +31,7 @@ pub(crate) fn specs() -> Vec { "Export outputs...", ["File"], Some("Ctrl+Shift+E"), - "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), graph?} cooks the graph at full size and writes every output", + "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px, power of two, 16..8192; default the graph's), graph?} cooks the graph at full size and writes every output", has_graph, export ), @@ -150,9 +150,18 @@ pub struct Exported { } /// Cook graph `gi` at full size and encode every output (`pattern` names files). -pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option) -> Result> { - let g = s.pkg.graph(gi)?; - let cooked = s.cook_full(gi); +pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option, size: Option) -> Result> { + let mut pkg = s.pkg.clone(); + if let Some(px) = size { + let log2 = 31 - px.clamp(16, 8192).leading_zeros(); + pkg.graph_mut(gi)?.size = [log2, log2]; + } + let g = pkg.graph(gi)?; + let dec = s.resource_decoder(); + let cooked = { + let mut cache = s.cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &mut cache) + }; let mut out = Vec::new(); for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { let Some(img) = img else { continue }; @@ -168,8 +177,8 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O Ok(out) } -/// Export params: (graph index, extension, pattern, depth). -pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option)> { +/// Export params: (graph index, extension, pattern, depth, size). +pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option, Option)> { let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize); s.pkg.graph(gi)?; let ext = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); @@ -184,14 +193,15 @@ pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Optio Some(32) => Some(Depth::F32), Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))), }; - Ok((gi, ext, pattern, depth)) + let size = u64p(p, "size").map(|px| px.min(u64::from(u32::MAX)) as u32); + Ok((gi, ext, pattern, depth, size)) } #[cfg(not(target_arch = "wasm32"))] fn export(s: &mut Session, p: &J) -> Result { let dir = strp(p, "dir").ok_or_else(|| bad("file.export", "`dir` is required"))?; - let (gi, ext, pattern, depth) = export_params(s, p)?; - let files = export_outputs(s, gi, &ext, &pattern, depth)?; + let (gi, ext, pattern, depth, size) = export_params(s, p)?; + let files = export_outputs(s, gi, &ext, &pattern, depth, size)?; std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?; let mut written = Vec::new(); for f in files { diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5c108526..75f21c5f 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -83,6 +83,11 @@ fn package_save_and_open_round_trip() { 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(), 6); + let small = dir.join("small"); + run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); + let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); + let img = materialcraft_formats::decode(&std::fs::read(file).unwrap()).unwrap(); + assert_eq!((img.w, img.h), (64, 64)); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 8c50b844..547cbb7e 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -72,8 +72,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } Some(("export", i)) => { // The export window works on the open graph. - app.run("graph.open", json!({"graph": i})); - app.ui.windows.export = true; + if app.run("graph.open", json!({"graph": i})).is_some() { + app.ui.windows.export = true; + } } Some(("duplicate", i)) => { app.run("graph.duplicate", json!({"graph": i})); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b6d2a32..c328373a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -105,6 +105,8 @@ pub struct UiState { pub export_dir: String, pub export_format: String, pub export_depth: u32, + /// Export size in pixels; 0 = the graph's own size. + pub export_size: u32, pub export_pattern: String, /// Frame the whole graph on the next frame. #[serde(skip)] @@ -128,6 +130,7 @@ impl Default for UiState { export_dir: String::new(), export_format: "png".into(), export_depth: 0, + export_size: 0, export_pattern: "$(graph)_$(identifier)".into(), frame_all: true, } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index adaa1b9d..b5169055 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -198,7 +198,7 @@ mod web { /// Export outputs: one file downloads as is, several as `_outputs.zip`. pub fn export(app: &mut MaterialCraftApp, params: &serde_json::Value) { let result = materialcraft_engine::file_cmds::export_params(&app.session, params) - .and_then(|(gi, ext, pattern, depth)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth)) + .and_then(|(gi, ext, pattern, depth, size)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth, size)) .map_err(|e| e.to_string()) .and_then(|files| { let files: Vec<(String, Vec)> = files.into_iter().map(|f| (f.file, f.bytes)).collect(); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 931d19ca..1e42c8a8 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -197,7 +197,7 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) { fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; let mut go = false; - modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 260.0), |ui| { + modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 290.0), |ui| { let tk = Tokens::get(ui.ctx()); let g = app.session.graph().map(|g| g.name.clone()).unwrap_or_default(); ui.label(RichText::new(format!("{}: {g}", tr("Graph"))).strong()); @@ -229,6 +229,16 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { ui.selectable_value(&mut app.ui.export_depth, d, tr(l)); } }); + let size_label = match app.ui.export_size { + 0 => tr("Graph's size").to_string(), + px => format!("{px} x {px}"), + }; + crate::widgets::combo(ui, tr("Resolution"), size_label, |ui| { + ui.selectable_value(&mut app.ui.export_size, 0, tr("Graph's size")); + for px in [256u32, 512, 1024, 2048, 4096, 8192] { + ui.selectable_value(&mut app.ui.export_size, px, format!("{px} x {px}")); + } + }); ui.horizontal(|ui| { ui.label(tr("File names")); let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_pattern).desired_width(260.0)); @@ -250,7 +260,7 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.toast(tr("Choose a folder to export to"), true); } else { let depth = if app.ui.export_depth == 0 { Value::Null } else { json!(app.ui.export_depth) }; - let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth}); + let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth, "size": if app.ui.export_size == 0 { Value::Null } else { json!(app.ui.export_size) }}); #[cfg(target_arch = "wasm32")] { crate::web_files::export(app, &p); From e816ad75bbd81a23e2b9958297fc0feeb838184c Mon Sep 17 00:00:00 2001 From: AndreIsraelAO Date: Tue, 3 Nov 2026 07:29:07 -0300 Subject: [PATCH 03/91] Keep export proportions and expose size in the CLI and MCP size is now the larger side in pixels and the other side keeps its proportion; 0 means the graph's size. Adds --size to the CLI export, size to the MCP outputs_export, and the docs line. The resolution combo shows the graph's real size. Refs #22 --- apps/materialcraft-cli/src/main.rs | 6 +++--- crates/automation/src/server.rs | 3 +++ crates/engine/src/file_cmds.rs | 15 ++++++++++----- crates/engine/src/session.rs | 2 +- crates/engine/tests/session.rs | 19 +++++++++++++++++++ crates/ui-egui/src/windows.rs | 9 +++++---- docs/control-protocol.md | 2 +- 7 files changed, 42 insertions(+), 14 deletions(-) diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index fef8f39e..5afe3fb2 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -30,7 +30,7 @@ USAGE: materialcraft-cli cook [--graph ] [--set =]... [--full] Cook a graph and print per-node timings and errors. materialcraft-cli export [--graph ] [--set =]... [--format ] - [--depth 8|16|32] [--pattern

] + [--depth 8|16|32] [--size ] [--pattern

] Cook at full size and write every output (png, jpg, tga, tif, bmp, webp, exr, hdr). materialcraft-cli render [--size x] [--view 3d|2d] [--scene ] [--node ] [--yaw ] [--pitch ] [--graph ] [--set =]... [--full] @@ -57,7 +57,7 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("batch", &[], &[]), ("new", &["--size", "--name"], &[]), ("cook", &["--graph", "--set"], &["--full"]), - ("export", &["--graph", "--set", "--format", "--depth", "--pattern"], &[]), + ("export", &["--graph", "--set", "--format", "--depth", "--size", "--pattern"], &[]), ("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--set", "--tiling", "--displacement"], &["--full", "--hq"]), ("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]), ("serve", &["--port", "--read-root", "--write-root"], &[]), @@ -227,7 +227,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { let mut h = open(a.pos(0, "")?)?; select_graph(&mut h, a)?; let dir = a.pos(1, "

")?; - let p = json!({"dir": dir, "graph": a.num::("--graph")?, "format": a.get("--format"), "depth": a.num::("--depth")?, "pattern": a.get("--pattern")}); + let p = json!({"dir": dir, "graph": a.num::("--graph")?, "format": a.get("--format"), "depth": a.num::("--depth")?, "size": a.num::("--size")?, "pattern": a.get("--pattern")}); print(&h.export(&p).map_err(|e| e.to_string())?); } "render" => { diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index e23f3d18..5ecf5f3e 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -154,6 +154,9 @@ pub struct ExportParams { /// 8, 16 or 32 bits (default: the graph's output format). #[serde(default, skip_serializing_if = "Option::is_none")] pub depth: Option, + /// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, /// Graph index (default: the open graph). #[serde(default, skip_serializing_if = "Option::is_none")] pub graph: Option, diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index e1af7462..7d4bb5db 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -31,7 +31,7 @@ pub(crate) fn specs() -> Vec { "Export outputs...", ["File"], Some("Ctrl+Shift+E"), - "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px, power of two, 16..8192; default the graph's), graph?} cooks the graph at full size and writes every output", + "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, rounded down to a power of two, 16..8192; default the graph's size, keeping its proportions), graph?} cooks the graph at full size and writes every output", has_graph, export ), @@ -153,8 +153,11 @@ pub struct Exported { pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option, size: Option) -> Result> { let mut pkg = s.pkg.clone(); if let Some(px) = size { - let log2 = 31 - px.clamp(16, 8192).leading_zeros(); - pkg.graph_mut(gi)?.size = [log2, log2]; + let g = pkg.graph_mut(gi)?; + // The larger side becomes `px`; the other keeps its proportion. + let target = 31 - px.clamp(16, 8192).leading_zeros(); + let larger = g.size[0].max(g.size[1]); + g.size = g.size.map(|l| (l + target).saturating_sub(larger).max(4)); } let g = pkg.graph(gi)?; let dec = s.resource_decoder(); @@ -178,7 +181,9 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O } /// Export params: (graph index, extension, pattern, depth, size). -pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option, Option)> { +pub type ExportArgs = (usize, String, String, Option, Option); + +pub fn export_params(s: &Session, p: &J) -> Result { let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize); s.pkg.graph(gi)?; let ext = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); @@ -193,7 +198,7 @@ pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Optio Some(32) => Some(Depth::F32), Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))), }; - let size = u64p(p, "size").map(|px| px.min(u64::from(u32::MAX)) as u32); + let size = u64p(p, "size").filter(|&px| px > 0).map(|px| px.min(u64::from(u32::MAX)) as u32); Ok((gi, ext, pattern, depth, size)) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 040284df..2b0cc41b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -313,7 +313,7 @@ impl Session { &self.cooked } - /// Cook graph `gi` at full size (exports), without touching the preview results. + /// Cook graph `gi` at full size, without touching the preview results. pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); let opts = Options::new(&dec); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 75f21c5f..62849488 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -91,6 +91,25 @@ fn package_save_and_open_round_trip() { let _ = std::fs::remove_dir_all(&dir); } +/// `file.export` `size` is the larger side in pixels; 0 means the graph's size and the proportions are kept. +#[test] +fn export_size_keeps_proportions_and_clamps() { + let mut s = sample_session(); + s.pkg.graphs[0].size = [7, 6]; + let dims = |s: &Session, size: Value| { + let (gi, ext, pattern, depth, size) = materialcraft_engine::file_cmds::export_params(s, &json!({"size": size})).unwrap(); + let files = materialcraft_engine::file_cmds::export_outputs(s, gi, &ext, &pattern, depth, size).unwrap(); + files.iter().map(|f| materialcraft_formats::decode(&f.bytes).unwrap()).map(|i| (i.w, i.h)).collect::>() + }; + for size in [json!(0), json!(null)] { + assert!(dims(&s, size).iter().all(|d| *d == (128, 64))); + } + assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 16))); + let parsed = |size: Value| materialcraft_engine::file_cmds::export_params(&s, &json!({"size": size})).unwrap().4; + assert_eq!(parsed(json!(0)), None); + assert_eq!(parsed(json!(u64::MAX)), Some(u32::MAX)); +} + /// Every command, run with empty and hostile params, returns Ok or Err but never panics. #[test] fn panic_hunt() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 1e42c8a8..f82a03a8 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -229,14 +229,15 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { ui.selectable_value(&mut app.ui.export_depth, d, tr(l)); } }); + let graph_size = app.session.graph().map_or(String::new(), |g| format!("{} ({} x {})", tr("Graph's size"), 1u32 << g.size[0], 1u32 << g.size[1])); let size_label = match app.ui.export_size { - 0 => tr("Graph's size").to_string(), - px => format!("{px} x {px}"), + 0 => graph_size.clone(), + px => format!("{px} px"), }; crate::widgets::combo(ui, tr("Resolution"), size_label, |ui| { - ui.selectable_value(&mut app.ui.export_size, 0, tr("Graph's size")); + ui.selectable_value(&mut app.ui.export_size, 0, graph_size); for px in [256u32, 512, 1024, 2048, 4096, 8192] { - ui.selectable_value(&mut app.ui.export_size, px, format!("{px} x {px}")); + ui.selectable_value(&mut app.ui.export_size, px, format!("{px} px")); } }); ui.horizontal(|ui| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c0fba6c..7c1645e9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -25,7 +25,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: | `session.inspect` | all | package, graphs, the open graph's nodes (def, params, bindings, base, ports, cook error/size/mean/ms), wires, frames, comments, pins, exposed inputs, views, history | | `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O | | `bitmap.import {path, name?}` | headless | embed an image as a resource | -| `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output | +| `outputs.export {dir, format?, pattern?, depth?, size?, graph?}` | headless | cook at full size and write every output | | `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii | | `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts | | `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click | From af83c228c32858156b6f7fffc27dbe052d1e764f Mon Sep 17 00:00:00 2001 From: Belligerently Date: Tue, 3 Nov 2026 09:59:48 -0500 Subject: [PATCH 04/91] Allow centered dialogs to move by their title bars --- crates/ui-egui/src/windows.rs | 3 +- crates/ui-egui/tests/dialogs.rs | 76 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/dialogs.rs diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f308f048..9d8395ef 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -105,7 +105,8 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui .collapsible(false) .resizable(false) .default_size(size) - .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) .show(ctx, body); } diff --git a/crates/ui-egui/tests/dialogs.rs b/crates/ui-egui/tests/dialogs.rs new file mode 100644 index 00000000..2957e820 --- /dev/null +++ b/crates/ui-egui/tests/dialogs.rs @@ -0,0 +1,76 @@ +//! Home and export dialogs start centered, but their title bars must allow movement. + +use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2}; +use egui_kittest::Harness; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; + +type State = (MaterialCraftApp, Rect); + +fn harness(id: &'static str, render: bool) -> Harness<'static, State> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.windows.home = id == "home"; + app.ui.windows.export = id == "export"; + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + move |ui, (app, rect): &mut State| { + app.step(&ui.ctx().clone()); + app.draw(ui); + *rect = ui.ctx().memory(|m| m.area_rect(egui::Id::unique(id))).unwrap_or(Rect::NOTHING); + }, + (app, Rect::NOTHING), + ); + h.run_steps(10); + h +} + +fn drag_title(h: &mut Harness<'static, State>) { + let from = h.state().1.min + vec2(120.0, 12.0); + h.event(Event::PointerMoved(from)); + h.step(); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + for step in 1..=8 { + h.event(Event::PointerMoved(from + vec2(10.0, 7.5) * step as f32)); + h.step(); + } + h.event(Event::PointerButton { pos: from + vec2(80.0, 60.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(10); +} + +#[test] +fn home_and_export_can_be_dragged_and_keep_their_position() { + for id in ["home", "export"] { + let mut h = harness(id, false); + let before = h.state().1; + assert!(before.is_finite()); + assert!(before.center().distance(pos2(800.0, 480.0)) < 3.0, "{id}: initial rectangle {before:?}"); + drag_title(&mut h); + let moved = h.state().1; + assert!(moved.min.distance(before.min + vec2(80.0, 60.0)) < 8.0, "{id}: did not follow the drag: {before:?} -> {moved:?}"); + // Later frames and reopening the same dialog must not snap it back to the center. + h.state_mut().0.ui.windows.home = false; + h.state_mut().0.ui.windows.export = false; + h.run_steps(3); + h.state_mut().0.ui.windows.home = id == "home"; + h.state_mut().0.ui.windows.export = id == "export"; + h.run_steps(10); + assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: reopening lost the dragged position"); + h.set_size(vec2(1500.0, 900.0)); + h.run_steps(10); + assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: resizing recentered the dialog"); + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn dialog_drag_snapshots() { + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + for id in ["home", "export"] { + let mut h = harness(id, true); + h.render().unwrap().save(dir.join(format!("{id}-centered.png"))).unwrap(); + drag_title(&mut h); + h.render().unwrap().save(dir.join(format!("{id}-moved.png"))).unwrap(); + } +} From 7feafbf533f707cb29a18e301d3b11566547f57e Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:55:02 +0100 Subject: [PATCH 05/91] 2D view: show the node you click A single click only changed the selection, and the 2D view prefers a node shown with a double-click, an output port or "View in 2D view" over the selection, so after any of those, clicks never changed the view until the graph was switched. A click that leaves a node selected now shows it; a deselecting Ctrl+click or a drag does not, and the node already shown keeps its chosen output port. Fixes #10 --- crates/ui-egui/src/graph_view.rs | 175 ++++++++++++++++++++++++++----- crates/ui-egui/src/view2d.rs | 8 +- 2 files changed, 148 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index b56f295e..70c0076d 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -4,9 +4,10 @@ //! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire //! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route //! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to -//! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or -//! double-click the canvas for the node search, right-click for menus, drop library items to add -//! them. Every edit is an engine command; the gestures only draw previews until they commit. +//! zoom, click a node to show it in the 2D view (double-click a graph instance to open its graph), +//! Space, Tab or double-click the canvas for the node search, right-click for menus, drop library +//! items to add them. Every edit is an engine command; the gestures only draw previews until they +//! commit. use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; @@ -822,6 +823,10 @@ fn handle_input( app.run("view.2d", json!({"node": id.0, "port": 0})); } } + } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { + // A click that leaves the node selected shows it, replacing a node shown earlier (a + // Ctrl+click that deselects it does not; the shown node keeps its chosen port). + app.run("view.2d", json!({"node": id.0})); } r.context_menu(|ui| node_menu(app, ui, *id)); } @@ -1087,33 +1092,147 @@ fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { mod tests { use super::*; + /// The whole app in an offscreen egui context, driven one frame at a time. + struct Frames { + ctx: egui::Context, + app: MaterialCraftApp, + time: f64, + } + + impl Frames { + /// `session` after a few frames, so the canvas is laid out. + fn new(session: materialcraft_engine::Session) -> Frames { + let mut f = Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0 }; + for _ in 0..3 { + f.run(Vec::new(), egui::Modifiers::NONE); + } + f + } + + /// One frame with `events` while `modifiers` are held, in a desktop-sized window (egui's + /// default screen is so large that the 3D view's frame would exceed the texture limit). + fn run(&mut self, events: Vec, modifiers: egui::Modifiers) { + self.time += 0.05; + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))); + let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() }; + let app = &mut self.app; + self.ctx + .run_ui(input, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }) + .textures_delta + .clear(); + } + + /// Press and release the primary button at `pos`, a second after any earlier click so + /// the two never pair into a double-click. + fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) { + self.time += 1.0; + self.run(vec![egui::Event::PointerMoved(pos)], modifiers); + for pressed in [true, false] { + self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers); + } + } + + /// The center of node `id` on screen last frame. + fn center(&self, id: NodeId) -> Pos2 { + self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen")) + } + + /// The node the 2D view shows once the graph has cooked. + fn shown(&mut self) -> Option { + self.app.session.cook(); + self.app.session.view2d_image().map(|(id, _)| id) + } + } + + /// A graph with a Perlin noise, a checker and an RGBA split side by side, framed on screen. + fn three_nodes() -> (Frames, [NodeId; 3]) { + let mut s = materialcraft_engine::sample_session(); + materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); + let ids = ["perlin_noise", "checker", "rgba_split"].iter().enumerate().map(|(i, def)| { + let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); + NodeId(added["id"].as_u64().unwrap()) + }); + let ids: [NodeId; 3] = ids.collect::>().try_into().unwrap(); + s.selection.clear(); + (Frames::new(s), ids) + } + + #[test] + fn clicking_a_node_shows_it_in_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + // Shown explicitly first (a double-click, an output port or "View in 2D view"). + f.app.run("view.2d", json!({"node": noise.0})); + assert_eq!(f.shown(), Some(noise)); + let at = f.center(checker); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.app.session.view2d.node, Some(checker)); + assert_eq!(f.shown(), Some(checker)); + // And back. + let at = f.center(noise); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.view2d.node, Some(noise)); + assert_eq!(f.shown(), Some(noise)); + // Ctrl+click adds a node to the selection and shows it too. + let at = f.center(checker); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![noise, checker]); + assert_eq!(f.shown(), Some(checker)); + } + + #[test] + fn ctrl_click_that_deselects_a_node_does_not_show_it() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.session.selection = vec![noise, checker]; + f.app.run("view.2d", json!({"node": checker.0})); + let at = f.center(noise); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(checker)); + } + + #[test] + fn dragging_a_node_keeps_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.run("view.2d", json!({"node": noise.0})); + let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let from = f.center(checker); + let none = egui::Modifiers::NONE; + f.run(vec![egui::Event::PointerMoved(from)], none); + f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); + for step in 1..=8 { + f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); + } + let to = from + vec2(40.0, 0.0); + f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); + let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let moved = 40.0 / f.app.ui.graph_camera.zoom; + assert!((after[0] - before[0] - moved).abs() < 1e-3 && after[1] == before[1], "the checker moved {before:?} -> {after:?}, not {moved} right"); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(noise)); + } + + #[test] + fn clicking_the_shown_node_keeps_its_port() { + let (mut f, [_, _, split]) = three_nodes(); + f.app.run("view.2d", json!({"node": split.0, "port": 2})); + let at = f.center(split); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![split]); + assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); + } + #[test] fn tab_opens_search_in_the_full_workspace() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - let ctx = egui::Context::default(); - for _ in 0..3 { - ctx.run_ui(egui::RawInput::default(), |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - } - let pointer = app.graph.view.center(); - let input = egui::RawInput { - events: vec![ - egui::Event::PointerMoved(pointer), - egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - ], - ..Default::default() - }; - ctx.run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - assert!(app.graph.search.is_some()); + let mut f = Frames::new(materialcraft_engine::sample_session()); + let pointer = f.app.graph.view.center(); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); + assert!(f.app.graph.search.is_some()); } #[test] diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 2bb3d5cc..cc52172c 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -88,13 +88,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { 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("Double-click a node to show it here"), - egui::FontId::proportional(12.0), - tk.viewport_text, - ); + 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); return; }; let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) From 4b97a81f7d0455d70d0a793ed4e8318260c8f07a Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:08:13 -0600 Subject: [PATCH 06/91] Formats: bound package load memory, check image size before decoding, guard parsers --- crates/formats/src/lib.rs | 143 +++++++++++++++++++++++++++++++++---- crates/formats/src/mesh.rs | 7 +- 2 files changed, 135 insertions(+), 15 deletions(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 304fa0eb..9013dc3e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -11,6 +11,7 @@ pub mod material; pub mod mesh; +use std::collections::HashMap; use std::io::{Cursor, Read, Write}; use std::sync::Arc; @@ -32,6 +33,10 @@ pub type Result = std::result::Result; /// Largest `package.json` and resource accepted when reading (allocation caps). const MAX_JSON: u64 = 64 << 20; const MAX_RESOURCE: u64 = 256 << 20; +/// Most resource records a package may list. +const MAX_RESOURCES: usize = 4096; +/// Most decompressed bytes a package may hold across `package.json` and all its resources. +const MAX_PACKAGE_BYTES: u64 = 2 << 30; /// Export file types: (extension, label). pub const EXPORT_FORMATS: &[(&str, &str)] = @@ -63,6 +68,11 @@ pub fn save_package(pkg: &Package) -> Result> { /// Read a package from `.mcraft` bytes. pub fn load_package(bytes: &[u8]) -> Result { + load_package_within(bytes, MAX_PACKAGE_BYTES) +} + +/// [`load_package`] with an explicit cap on the total decompressed bytes. +fn load_package_within(bytes: &[u8], max_total: u64) -> Result { let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::BadPackage(e.to_string()))?; let mut json = Vec::new(); z.by_name("package.json") @@ -71,17 +81,37 @@ pub fn load_package(bytes: &[u8]) -> Result { .read_to_end(&mut json) .map_err(|e| FormatError::Io(e.to_string()))?; let mut pkg: Package = serde_json::from_slice(&json).map_err(|e| FormatError::BadPackage(e.to_string()))?; + if pkg.resources.len() > MAX_RESOURCES { + return Err(FormatError::BadPackage(format!("{} resources (limit {MAX_RESOURCES})", pkg.resources.len()))); + } + let mut total = json.len() as u64; + let mut read: HashMap>> = HashMap::new(); for r in &mut pkg.resources { let name = format!("resources/{}", safe_file_name(&r.file)); + if let Some(shared) = read.get(&name) { + r.bytes = Arc::clone(shared); + continue; + } let mut data = Vec::new(); if let Ok(mut f) = z.by_name(&name) { f.by_ref().take(MAX_RESOURCE).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?; } - r.bytes = Arc::new(data); + total = total.saturating_add(data.len() as u64); + if total > max_total { + return Err(FormatError::BadPackage(format!("package resources exceed {max_total} bytes"))); + } + let data = Arc::new(data); + read.insert(name, Arc::clone(&data)); + r.bytes = data; } Ok(pkg) } +/// Last-resort guard around third-party parsers: a panic inside them becomes an error. +pub(crate) fn guard(f: impl FnOnce() -> Result, err: impl FnOnce() -> FormatError) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(err())) +} + /// A file name with no path parts (resources live flat in `resources/`). pub fn safe_file_name(name: &str) -> String { let base = name.rsplit(['/', '\\']).next().unwrap_or(name); @@ -93,10 +123,25 @@ pub fn safe_file_name(name: &str) -> String { /// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale /// files stay grayscale). pub fn decode(bytes: &[u8]) -> Result { - // TGA has no signature: try it when the format cannot be guessed. - let img = image::load_from_memory(bytes) - .or_else(|e| image::load_from_memory_with_format(bytes, image::ImageFormat::Tga).map_err(|_| e)) - .map_err(|e| FormatError::Image(e.to_string()))?; + let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Image(e.to_string()))?; + if reader.format().is_none() { + // TGA has no signature: try it when the format cannot be guessed. + reader.set_format(image::ImageFormat::Tga); + } + 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); + reader.limits(limits); + let img = guard( + || { + reader.decode().map_err(|e| match e { + image::ImageError::Limits(_) => FormatError::Image(format!("image is larger than {MAX_SIDE} pixels")), + e => FormatError::Image(e.to_string()), + }) + }, + || FormatError::Image("the decoder failed on this file".into()), + )?; let (w, h) = (img.width(), img.height()); if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels"))); @@ -108,14 +153,14 @@ pub fn decode(bytes: &[u8]) -> Result { let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); } - let rgba = img.into_rgba32f(); - let data: Vec = rgba - .pixels() - .flat_map(|p| { - let [r, g, b, a] = p.0; - if float { [r, g, b, a] } else { [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a] } - }) - .collect(); + let mut data = img.into_rgba32f().into_raw(); + if !float { + for px in data.chunks_exact_mut(4) { + for c in px.iter_mut().take(3) { + *c = srgb_to_linear(*c); + } + } + } Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) }) } @@ -272,4 +317,76 @@ mod tests { assert_eq!(safe_file_name("../../etc/passwd"), "passwd"); assert_eq!(safe_file_name(".."), "resource"); } + + fn zip_with(json: &serde_json::Value, entries: &[(&str, usize)]) -> Vec { + let mut buf = Cursor::new(Vec::new()); + { + let mut z = zip::ZipWriter::new(&mut buf); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + z.start_file("package.json", opts).unwrap(); + z.write_all(json.to_string().as_bytes()).unwrap(); + for (name, len) in entries { + z.start_file(format!("resources/{name}"), opts).unwrap(); + z.write_all(&vec![0u8; *len]).unwrap(); + } + z.finish().unwrap(); + } + buf.into_inner() + } + + fn package_json(files: &[&str]) -> serde_json::Value { + let base = serde_json::to_value(Package::new("T")).unwrap(); + let mut v = base; + v["resources"] = files.iter().map(|f| serde_json::json!({ "name": "r", "file": f })).collect(); + v + } + + #[test] + fn many_records_share_one_entry() { + let files = vec!["big.bin"; 1000]; + let bytes = zip_with(&package_json(&files), &[("big.bin", 1 << 20)]); + let pkg = load_package(&bytes).unwrap(); + assert_eq!(pkg.resources.len(), 1000); + assert_eq!(pkg.resources[0].bytes.len(), 1 << 20); + assert!(Arc::ptr_eq(&pkg.resources[0].bytes, &pkg.resources[999].bytes)); + } + + #[test] + fn too_many_resources_is_an_error() { + let files = vec!["a.bin"; MAX_RESOURCES + 1]; + let bytes = zip_with(&package_json(&files), &[("a.bin", 4)]); + assert!(load_package(&bytes).is_err()); + } + + #[test] + fn total_budget_is_enforced() { + let bytes = zip_with(&package_json(&["a.bin", "b.bin"]), &[("a.bin", 1 << 20), ("b.bin", 1 << 20)]); + assert!(load_package_within(&bytes, 3 << 19).is_err()); + assert!(load_package_within(&bytes, 3 << 20).is_ok()); + } + + #[test] + fn oversized_images_are_refused_before_decoding() { + let mut png = Cursor::new(Vec::new()); + image::GrayImage::new(8193, 1).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let err = decode(png.get_ref()).unwrap_err().to_string(); + assert!(err.contains("8192"), "{err}"); + } + + #[test] + fn tga_still_decodes() { + let mut tga = Cursor::new(Vec::new()); + image::RgbaImage::new(2, 2).write_to(&mut tga, image::ImageFormat::Tga).unwrap(); + let img = decode(tga.get_ref()).unwrap(); + assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); + } + + #[test] + fn decode_matches_previous_values() { + let mut png = Cursor::new(Vec::new()); + image::RgbImage::from_pixel(2, 2, image::Rgb([128, 128, 128])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let img = decode(png.get_ref()).unwrap(); + let want = srgb_to_linear(128.0 / 255.0); + assert!((img.get(1, 1, false)[0] - want).abs() < 1e-4); + } } diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 2597dd0d..cfaca36c 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -47,7 +47,10 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { fn obj(bytes: &[u8]) -> Result { let mut reader = std::io::BufReader::new(bytes); let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() }; - let (models, _) = tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}")))?; + let (models, _) = crate::guard( + || tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}"))), + || bad("the OBJ parser failed on this file"), + )?; let mut positions = Vec::new(); let mut normals = Vec::new(); let mut uvs = Vec::new(); @@ -75,7 +78,7 @@ fn obj(bytes: &[u8]) -> Result { } fn gltf(bytes: &[u8]) -> Result { - let (doc, buffers, _) = gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}")))?; + let (doc, buffers, _) = crate::guard(|| gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}"))), || bad("the glTF parser failed on this file"))?; let mut positions = Vec::new(); let mut normals = Vec::new(); let mut uvs = Vec::new(); From 2bd4fd35b8bca2b814fc8c5b276d873f3e4c95ca Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:17:16 -0600 Subject: [PATCH 07/91] Control channel: harden the token file and the app's control server The app wrote its control token to the temp folder with default permissions from a hash-based generator, compared it with ==, spawned unlimited threads and let an unauthenticated client hold a connection for 10 minutes. The shared token file was opened with create+truncate, which follows a planted symlink. - Token files are created new (remove, then O_EXCL) with mode 0600; clients only read a regular, owner-only, non-symlink file. - The app's control server uses the shared security module: OS-random token, constant-time compare, bounded lines, at most 16 connections, one auth attempt within 10 s, close on malformed JSON before auth. - serve --port and the app bind before writing the token file. Ported from TextureCraft 5a065c1 and 836e3f2. --- Cargo.lock | 2 + Cargo.toml | 1 + apps/materialcraft-cli/src/main.rs | 18 +- apps/materialcraft/Cargo.toml | 1 + apps/materialcraft/src/control_server.rs | 254 ++++++++++++++++------- crates/automation/Cargo.toml | 3 + crates/automation/src/rpc.rs | 18 +- crates/automation/src/security.rs | 182 +++++++++++++++- docs/control-protocol.md | 10 +- 9 files changed, 400 insertions(+), 89 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ce3b0fc1..c0a22386 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2313,6 +2313,7 @@ dependencies = [ "egui", "image", "log", + "materialcraft-automation", "materialcraft-engine", "materialcraft-ui-egui", "serde_json", @@ -2332,6 +2333,7 @@ dependencies = [ "materialcraft-render", "rayon", "rmcp", + "rustix 1.1.6", "schemars", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 663ec4d4..284c1729 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,7 @@ 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"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils"] } tobj = { version = "4", default-features = false } diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index fef8f39e..6d2b24ec 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -274,14 +274,16 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?))); match a.num::("--port")? { Some(port) => { - let (token, file) = server_token(port).map_err(|e| e.to_string())?; - rpc::serve_tcp(port, h, token, |addr| { - eprintln!("materialcraft-cli: serving JSON lines on {addr}"); - if let Some(f) = &file { - eprintln!("materialcraft-cli: token in {}", f.display()); - } - }) - .map_err(|e| e.to_string())?; + // Bind first: a port in use must not replace its server's token file, and port 0's + // token file is named after the port actually picked. + let listener = rpc::bind_tcp(port).map_err(|e| e.to_string())?; + let addr = listener.local_addr().map_err(|e| e.to_string())?; + let (token, file) = server_token(addr.port()).map_err(|e| e.to_string())?; + eprintln!("materialcraft-cli: serving JSON lines on {addr}"); + if let Some(f) = &file { + eprintln!("materialcraft-cli: token in {}", f.display()); + } + rpc::serve_listener(listener, h, token).map_err(|e| e.to_string())?; } None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| e.to_string())?, } diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 64a1ca49..7b5a2caa 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -12,6 +12,7 @@ workspace = true [dependencies] materialcraft-engine = { workspace = true } +materialcraft-automation = { workspace = true } materialcraft-ui-egui = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] } egui = { workspace = true } diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index a094e2dc..0f841c43 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -1,42 +1,26 @@ //! Loopback JSON-lines control server (`--control `): one request per line, //! `{"id", "method", "params"}`, one reply per line. The first request must be //! `{"method":"auth","params":{"token":"…"}}` with the token from `MATERIALCRAFT_CONTROL_TOKEN` -//! or, when that is unset, the token written to `/materialcraft-control-.token`. +//! or, when that is unset, the token written (owner-only) to +//! `/materialcraft-control-.token`. Token handling, request framing and connection +//! limits are shared with `materialcraft-cli serve` (`materialcraft_automation::security`). -use std::io::{BufRead, BufReader, Read, Write}; +use std::io::{BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::time::Duration; +use materialcraft_automation::security::{ + AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_CONNECTIONS, read_bounded_line, server_token, token_matches, +}; use materialcraft_ui_egui::ControlRequest; use serde_json::{Value, json}; -/// Requests larger than this are rejected (screenshots go the other way). -const MAX_REQUEST: u64 = 8 << 20; - -fn token(port: u16) -> String { - if let Ok(t) = std::env::var("MATERIALCRAFT_CONTROL_TOKEN") - && t.len() >= 16 - { - return t; - } - use std::hash::{BuildHasher, Hasher}; - let mut out = String::new(); - for i in 0..4u64 { - let mut h = std::collections::hash_map::RandomState::new().build_hasher(); - h.write_u64(i ^ u64::from(std::process::id())); - h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); - out.push_str(&format!("{:016x}", h.finish())); - } - let path = std::env::temp_dir().join(format!("materialcraft-control-{port}.token")); - if let Err(e) = std::fs::write(&path, &out) { - eprintln!("materialcraft: could not write the control token to {}: {e}", path.display()); - } else { - eprintln!("materialcraft: control token written to {}", path.display()); - } - out -} +/// How long an authenticated connection may stay idle. +const IDLE_TIMEOUT: Duration = Duration::from_secs(600); +/// Listen on `127.0.0.1:port` and return the requests for the UI thread to answer +/// ([`ControlRequest::reply`]). Bind or token failures are printed and leave the channel empty. pub fn start(port: u16, ctx: egui::Context) -> Receiver { let (tx, rx) = channel::(); let listener = match TcpListener::bind(("127.0.0.1", port)) { @@ -46,35 +30,65 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver { return rx; } }; - let token = token(port); - eprintln!("materialcraft: control server listening on 127.0.0.1:{port}"); - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.clone()); - std::thread::spawn(move || serve(stream, &token, tx, ctx)); + // After binding, so an app that cannot listen never replaces another server's token. + let token = match server_token(port) { + Ok((token, Some(path))) => { + eprintln!("materialcraft: control token written to {}", path.display()); + token } - }); + Ok((token, None)) => token, + Err(e) => { + eprintln!("materialcraft: control server disabled: {e}"); + return rx; + } + }; + eprintln!("materialcraft: control server listening on 127.0.0.1:{port}"); + std::thread::spawn(move || accept(listener, &token, &tx, &ctx)); rx } -fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context) { - let _ = stream.set_read_timeout(Some(Duration::from_secs(600))); - let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(read.take(u64::MAX)); - let mut out = stream; - let mut authed = false; - loop { - let mut line = String::new(); - let n = match reader.by_ref().take(MAX_REQUEST).read_line(&mut line) { - Ok(n) => n, - Err(_) => break, +/// Serve connections from `listener` (at most [`MAX_CONNECTIONS`] at once). +fn accept(listener: TcpListener, token: &str, tx: &Sender, ctx: &egui::Context) { + let limiter = ConnectionLimiter::default(); + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let Some(permit) = limiter.try_acquire(MAX_CONNECTIONS) else { + let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"})); + continue; }; - if n == 0 { - break; - } - if !line.ends_with('\n') && n as u64 >= MAX_REQUEST { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"})); - break; + let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.to_string()); + std::thread::spawn(move || { + let _permit = permit; + serve(stream, &token, &tx, &ctx); + }); + } +} + +/// Send `reply` with the request's `id`; false when the client is gone. +fn reply(out: &mut TcpStream, id: Value, mut reply: Value) -> bool { + if let Some(o) = reply.as_object_mut() { + o.insert("id".into(), id); + } + writeln!(out, "{reply}").is_ok() && out.flush().is_ok() +} + +/// One connection: `auth` first (within [`AUTH_TIMEOUT`], one attempt), then requests +/// forwarded to the UI thread one at a time until the client disconnects or idles out. +fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui::Context) { + let Ok(mut deadline) = AuthDeadline::start(&stream, AUTH_TIMEOUT).map(Some) else { return }; + let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT)); + let Ok(read) = stream.try_clone() else { return }; + let mut reader = BufReader::new(read); + let mut out = stream; + let mut line = String::new(); + loop { + match read_bounded_line(&mut reader, &mut line) { + Ok(LineRead::Line) => {} + Ok(LineRead::TooLong) => { + reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"})); + return; + } + Ok(LineRead::Eof) | Err(_) => return, } if line.trim().is_empty() { continue; @@ -82,33 +96,133 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: let msg: Value = match serde_json::from_str(&line) { Ok(v) => v, Err(e) => { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")})); + let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": format!("bad JSON: {e}")})); + // Before `auth` a malformed line is the one refused attempt, as on `serve --port`. + if !sent || deadline.is_some() { + return; + } continue; } }; let id = msg.get("id").cloned().unwrap_or(Value::Null); let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); let params = msg.get("params").cloned().unwrap_or(json!({})); - let mut reply = if !authed { - let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token); - authed = ok; - if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) } - } else { - let (req, rrx) = ControlRequest::new(method, params); - if tx.send(req).is_err() { - break; + if deadline.is_some() { + let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default(); + if method != "auth" || !token_matches(token, supplied) { + // One attempt per connection, as on `materialcraft-cli serve`. + reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); + return; } - ctx.request_repaint(); - rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})) - }; - if let Some(o) = reply.as_object_mut() { - o.insert("id".into(), id); + drop(deadline.take()); + if !reply(&mut out, id, json!({"ok": true})) { + return; + } + continue; } - if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed { - if !authed { - continue; - } - break; + let (req, rrx) = ControlRequest::new(method, params); + if tx.send(req).is_err() { + return; + } + ctx.request_repaint(); + let answer = rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})); + if !reply(&mut out, id, answer) { + return; } } } + +#[cfg(test)] +mod tests { + use std::io::BufRead; + + use super::*; + + const TOKEN: &str = "0123456789abcdef0123456789abcdef"; + + /// A server on a free port whose app side answers every request with its method name. + fn server() -> std::net::SocketAddr { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || accept(listener, TOKEN, &tx, &egui::Context::default())); + std::thread::spawn(move || { + for r in rx { + let _ = r.reply.send(json!({"ok": true, "result": r.method})); + } + }); + addr + } + + fn connect(addr: std::net::SocketAddr) -> (TcpStream, BufReader) { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + let r = BufReader::new(s.try_clone().unwrap()); + (s, r) + } + + fn call(w: &mut TcpStream, r: &mut BufReader, line: &str) -> Option { + writeln!(w, "{line}").ok()?; + let mut reply = String::new(); + (r.read_line(&mut reply).ok()? > 0).then(|| serde_json::from_str(&reply).unwrap()) + } + + #[test] + fn requests_need_the_token() { + let addr = server(); + // Anything before `auth` is refused and the connection closed. + let (mut w, mut r) = connect(addr); + let denied = call(&mut w, &mut r, r#"{"id":1,"method":"command.run","params":{"id":"file.open"}}"#).unwrap(); + assert_eq!(denied["ok"], false); + assert_eq!(denied["id"], 1); + assert!(call(&mut w, &mut r, r#"{"id":2,"method":"ping"}"#).is_none(), "closed after a refused request"); + // A wrong token is refused and gets no second try. + let (mut w, mut r) = connect(addr); + let wrong = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{}x"}}}}"#, &TOKEN[1..]); + assert_eq!(call(&mut w, &mut r, &wrong).unwrap()["ok"], false); + let right = format!(r#"{{"id":2,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); + assert!(call(&mut w, &mut r, &right).is_none()); + // So is a malformed first line: no further lines before `auth`. + let (mut w, mut r) = connect(addr); + assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false); + assert!(call(&mut w, &mut r, &right).is_none(), "closed after malformed JSON before auth"); + // The right token unlocks the connection. + let (mut w, mut r) = connect(addr); + let ok = call(&mut w, &mut r, &right).unwrap(); + assert_eq!((ok["ok"].clone(), ok["id"].clone()), (json!(true), json!(2))); + let pong = call(&mut w, &mut r, r#"{"id":3,"method":"ping"}"#).unwrap(); + assert_eq!((pong["result"].clone(), pong["id"].clone()), (json!("ping"), json!(3))); + assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false); + assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); + } + + #[test] + fn connections_are_limited_and_idle_ones_time_out() { + let addr = server(); + let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect(); + // Let the server take every idle connection before the one over the limit. + std::thread::sleep(Duration::from_millis(300)); + // Read without writing: the server closes at once, and unread input would reset the + // connection before its reply arrives. + let (_, mut r) = connect(addr); + let mut full = String::new(); + r.read_line(&mut full).unwrap(); + assert_eq!(serde_json::from_str::(&full).unwrap()["error"], "too many connections"); + // Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots. + for (_, mut r) in idle { + let mut rest = String::new(); + assert_eq!(r.read_line(&mut rest).unwrap(), 0); + } + // A slot frees once its thread has ended, which can trail the client's EOF a little. + let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); + let authed = (0..50).any(|_| { + let (mut w, mut r) = connect(addr); + let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true); + if !ok { + std::thread::sleep(Duration::from_millis(100)); + } + ok + }); + assert!(authed, "slots are freed after the auth deadline"); + } +} diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 994b5a61..d56a4fbd 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -24,5 +24,8 @@ base64 = { workspace = true } cap-std = { workspace = true } getrandom = { workspace = true } +[target.'cfg(unix)'.dependencies] +rustix = { workspace = true } + [dev-dependencies] rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 0c156b78..0d4253dd 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -18,7 +18,9 @@ use serde_json::{Value, json}; use crate::budgets::json_text; use crate::headless::RenderOptions; -use crate::security::{ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches}; +use crate::security::{ + AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches, +}; use crate::{AutomationError, Headless, bad}; pub const METHODS: &[&str] = &[ @@ -160,6 +162,7 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st let mut w = stream; let mut line = String::new(); let mut authed = false; + let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?); loop { match read_bounded_line(&mut r, &mut line)? { LineRead::Eof => return Ok(()), @@ -178,15 +181,26 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st if !authed { return write_reply(&mut w, &json!({"id": id, "ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); } + drop(deadline.take()); write_reply(&mut w, &json!({"id": id, "ok": true}))?; } } +/// Listen on `127.0.0.1:port` (0 picks a port). +pub fn bind_tcp(port: u16) -> Result { + TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}"))) +} + /// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared /// session. `ready` gets the bound address. pub fn serve_tcp(port: u16, h: Arc>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> { - let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))?; + let listener = bind_tcp(port)?; ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?); + serve_listener(listener, h, token) +} + +/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session. +pub fn serve_listener(listener: TcpListener, h: Arc>, token: String) -> Result<(), AutomationError> { let limiter = ConnectionLimiter::default(); let token = Arc::new(token); for stream in listener.incoming() { diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 165fda18..41bec540 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -1,10 +1,13 @@ //! Tokens and bounded framing for the loopback JSON-lines transports (the app's control channel //! and `materialcraft-cli serve` share the token conventions). -use std::io::BufRead; -use std::path::PathBuf; +use std::io::{BufRead, Read, Write}; +use std::net::{Shutdown, TcpStream}; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{RecvTimeoutError, Sender, channel}; +use std::time::Duration; use crate::{AutomationError, bad}; @@ -14,6 +17,10 @@ pub const TOKEN_ENV: &str = "MATERIALCRAFT_CONTROL_TOKEN"; pub const MAX_REQUEST_BYTES: usize = 8 << 20; /// Simultaneous TCP connections served by `serve --port`. pub const MAX_CONNECTIONS: usize = 16; +/// Largest token file read (a token is at most 1024 characters, plus whitespace). +const MAX_TOKEN_FILE_BYTES: u64 = 4096; +/// Time a TCP client has to authenticate before its connection is closed. +pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10); /// Steps in one `command_batch`. pub const MAX_BATCH_STEPS: usize = 256; @@ -44,7 +51,7 @@ pub fn client_token(port: u16, supplied: Option) -> Result t, None => { let path = token_file(port); - std::fs::read_to_string(&path) + read_token_file(&path) .map_err(|e| bad(format!("no control token: set {TOKEN_ENV} or start the app with `--control {port}` so it writes {} ({e})", path.display())))? } }; @@ -54,7 +61,8 @@ pub fn client_token(port: u16, supplied: Option) -> Result Result<(String, Option), AutomationError> { if let Ok(t) = std::env::var(TOKEN_ENV) { validate_token(t.trim())?; @@ -62,13 +70,60 @@ pub fn server_token(port: u16) -> Result<(String, Option), AutomationEr } let token = generate_token()?; let path = token_file(port); + write_token_file(&path, &token).map_err(|e| { + AutomationError::Io(format!("cannot write the control token to {} ({e}); set {TOKEN_ENV} to a token of your own instead", path.display())) + })?; + Ok((token, Some(path))) +} + +/// Write `token` to a new file at `path`, readable by the owner only on Unix. Whatever was at +/// `path` is removed first and the file is created exclusively (`O_EXCL`, which never follows +/// a symlink), so a file or link planted in a shared temp folder can neither keep its +/// permissions nor redirect the write; one that cannot be removed (another user's, in a sticky +/// `/tmp`) fails the call. +fn write_token_file(path: &Path, token: &str) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), + _ => {} + } let mut o = std::fs::OpenOptions::new(); - o.write(true).create(true).truncate(true); + o.write(true).create_new(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); - let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes())); - res.map_err(|e| AutomationError::Io(format!("cannot write the control token to {}: {e}", path.display())))?; - Ok((token, Some(path))) + let mut f = o.open(path)?; + f.write_all(token.as_bytes())?; + f.sync_all() +} + +/// Read a token file written by [`write_token_file`]. On Unix the file must be a regular file +/// (not a symlink, FIFO or device) owned by this user with no group or other permissions, so a +/// file another user planted is never trusted and a link can't make a client send one of its +/// own secrets as the token. +fn read_token_file(path: &Path) -> std::io::Result { + #[cfg(unix)] + let file = { + use rustix::fs::{Mode, OFlags}; + use std::os::unix::fs::MetadataExt; + let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC; + let file = std::fs::File::from(rustix::fs::open(path, flags, Mode::empty())?); + let meta = file.metadata()?; + let refuse = |why: &str| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("refusing the token file: {why}"))); + if !meta.is_file() { + return refuse("not a regular file"); + } + if meta.uid() != rustix::process::geteuid().as_raw() { + return refuse("owned by another user"); + } + if meta.mode() & 0o077 != 0 { + return refuse("readable or writable by other users"); + } + file + }; + #[cfg(not(unix))] + let file = std::fs::File::open(path)?; + let mut out = String::new(); + file.take(MAX_TOKEN_FILE_BYTES).read_to_string(&mut out)?; + Ok(out) } /// Compare equal-length tokens without an early exit. @@ -134,6 +189,27 @@ impl Drop for Permit { } } +/// Closes a connection that has not authenticated in time, so idle or trickling clients can't +/// hold the few connection slots. Drop it once the client is authenticated (or gone). +pub struct AuthDeadline { + _cancel: Sender<()>, +} + +impl AuthDeadline { + /// Shut `stream` down after `timeout` unless the returned deadline is dropped first. + pub fn start(stream: &TcpStream, timeout: Duration) -> std::io::Result { + let stream = stream.try_clone()?; + let (tx, rx) = channel::<()>(); + std::thread::spawn(move || { + // Dropping the deadline disconnects the channel and ends this thread at once. + if let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(timeout) { + let _ = stream.shutdown(Shutdown::Both); + } + }); + Ok(AuthDeadline { _cancel: tx }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -149,6 +225,76 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("mc-token-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn token_files_round_trip_and_replace_old_ones() { + let dir = scratch("round-trip"); + let path = dir.join("t.token"); + write_token_file(&path, "first-token-0123456789").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "first-token-0123456789"); + write_token_file(&path, "second-token-0123456789").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "second-token-0123456789"); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn token_files_are_owner_only_even_over_an_open_file() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("perms"); + let path = dir.join("t.token"); + std::fs::write(&path, "old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); + write_token_file(&path, "fresh-token-0123456789").unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn token_files_never_write_through_a_symlink() { + let dir = scratch("symlink-write"); + let (path, victim) = (dir.join("t.token"), dir.join("victim")); + std::fs::write(&victim, "keep me").unwrap(); + std::os::unix::fs::symlink(&victim, &path).unwrap(); + write_token_file(&path, "fresh-token-0123456789").unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me"); + assert!(!std::fs::symlink_metadata(&path).unwrap().file_type().is_symlink()); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn unsafe_token_files_are_refused() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("refuse"); + // Readable by others: another user may have planted or read it. + let open = dir.join("open.token"); + std::fs::write(&open, "planted-token-0123456789").unwrap(); + std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_token_file(&open).is_err()); + // A symlink, even to an owner-only file: a client must not send that file as its token. + let secret = dir.join("secret"); + write_token_file(&secret, "private-0123456789abcdef").unwrap(); + let link = dir.join("link.token"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + assert!(read_token_file(&link).is_err()); + // A FIFO is refused without blocking on open or read. + let fifo = dir.join("fifo.token"); + if std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + assert!(read_token_file(&fifo).is_err()); + } + // A directory is not a token. + assert!(read_token_file(&dir).is_err()); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn oversized_lines_are_skipped() { let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10)); @@ -160,6 +306,26 @@ mod tests { assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Eof)); } + #[test] + fn auth_deadline_closes_idle_connections_only() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let idle = TcpStream::connect(addr).unwrap(); + let (server_idle, _) = listener.accept().unwrap(); + let _deadline = AuthDeadline::start(&server_idle, Duration::from_millis(200)).unwrap(); + let mut buf = [0u8; 1]; + idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + assert_eq!(std::io::Read::read(&mut &idle, &mut buf).unwrap(), 0, "closed by the deadline"); + + let kept = TcpStream::connect(addr).unwrap(); + let (server_kept, _) = listener.accept().unwrap(); + drop(AuthDeadline::start(&server_kept, Duration::from_millis(200)).unwrap()); + std::thread::sleep(Duration::from_millis(400)); + (&server_kept).write_all(b"x").unwrap(); + kept.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + assert_eq!(std::io::Read::read(&mut &kept, &mut buf).unwrap(), 1, "a met deadline leaves the connection open"); + } + #[test] fn limiter_releases() { let l = ConnectionLimiter::default(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c0fba6c..0713ee05 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -11,7 +11,15 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: 3. **The app's control channel** (`materialcraft --control `): one JSON request per line, `{"id", "method", "params"}` → `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`. The first request must be `{"method":"auth","params":{"token":"…"}}` with the token from - `MATERIALCRAFT_CONTROL_TOKEN` or the file `/materialcraft-control-.token`. + `MATERIALCRAFT_CONTROL_TOKEN` (16 to 1024 printable ASCII characters) or the file + `/materialcraft-control-.token`, a fresh random 256-bit token written after the port + is bound. On Unix the file is created new with mode 0600 (owner only); if an existing file there + cannot be replaced, the control server stays off and `MATERIALCRAFT_CONTROL_TOKEN` is the + alternative. Clients (`materialcraft-cli mcp --bridge`) refuse a token file that is a symlink, + not a regular file, not owned by them, or accessible to group or others. A connection gets one + authentication attempt, within 10 s; a wrong token, any other first request or malformed JSON + closes it. At most 16 connections are served at once. Whoever holds the token has full + engine-command authority, including host file access. Set `MATERIALCRAFT_NO_PREFS=1` for scripted runs so the user's layout is left alone. ## Methods From c4d74432186b7853be682f612eb57434e84bb221 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:19:15 -0600 Subject: [PATCH 08/91] Eval: key resources on content and graph instances on their whole sub-graph tree Resources carry a content hash (ResourceBytes); the decoder memo is keyed on it and pruned. Graphs that use themselves, directly or through other instanced graphs, give an explicit error. --- crates/core/src/lib.rs | 2 +- crates/core/src/package.rs | 81 ++++++++++++++++- crates/engine/src/file_cmds.rs | 5 +- crates/engine/src/session.rs | 17 ++-- crates/engine/tests/session.rs | 16 ++++ crates/eval/src/lib.rs | 155 ++++++++++++++++++++++++++++++--- crates/formats/src/lib.rs | 18 ++-- 7 files changed, 265 insertions(+), 29 deletions(-) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 890eeabe..860e1b8b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -17,7 +17,7 @@ pub use graph::{ Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, Node, NodeId, OutputFormat, Pin, Preset, SizeMode, }; -pub use package::{PACKAGE_EXT, Package, Resource}; +pub use package::{PACKAGE_EXT, Package, Resource, ResourceBytes}; pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear}; #[derive(Debug, thiserror::Error)] diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs index 44d0c361..e00541e2 100644 --- a/crates/core/src/package.rs +++ b/crates/core/src/package.rs @@ -1,5 +1,6 @@ //! Packages: the document. A package holds graphs and the resources (bitmaps) they use. +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; use serde::{Deserialize, Serialize}; @@ -18,7 +19,68 @@ pub struct Resource { pub file: String, /// The file's bytes (stored in the zip, not in `package.json`). #[serde(skip)] - pub bytes: Arc>, + pub bytes: ResourceBytes, +} + +impl Resource { + /// A resource named `name`, stored as `file` in the package. + pub fn new(name: impl Into, file: impl Into, bytes: ResourceBytes) -> Resource { + Resource { name: name.into(), file: file.into(), bytes } + } +} + +/// A resource's bytes with a hash of their whole content, computed once when the bytes are +/// set, so caches can key on content (two files of one size are not the same image). +#[derive(Clone, Debug)] +pub struct ResourceBytes { + bytes: Arc>, + hash: u64, +} + +impl ResourceBytes { + /// Take ownership of `bytes` and hash them. + pub fn new(bytes: Vec) -> ResourceBytes { + let mut h = DefaultHasher::new(); + bytes.hash(&mut h); + ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) } + } + + /// The bytes. + pub fn as_slice(&self) -> &[u8] { + &self.bytes + } + + /// Number of bytes. + pub fn len(&self) -> usize { + self.bytes.len() + } + + /// Whether there are no bytes. + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// Hash of the whole content. + pub fn content_hash(&self) -> u64 { + self.hash + } + + /// Whether both values share one allocation (cheap clones of one file). + pub fn ptr_eq(&self, other: &ResourceBytes) -> bool { + Arc::ptr_eq(&self.bytes, &other.bytes) + } +} + +impl Default for ResourceBytes { + fn default() -> Self { + ResourceBytes::new(Vec::new()) + } +} + +impl PartialEq for ResourceBytes { + fn eq(&self, other: &Self) -> bool { + self.hash == other.hash && self.bytes == other.bytes + } } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -66,3 +128,20 @@ impl Package { (1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn same_length_same_prefix_bytes_hash_differently() { + let a = vec![7u8; 200]; + let mut b = a.clone(); + b[150] = 8; + let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b)); + assert_eq!(a.len(), b.len()); + assert_ne!(a.content_hash(), b.content_hash()); + assert_ne!(a, b); + assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new())); + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 392e3b49..a8c555e9 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -4,7 +4,7 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{Package, Resource}; +use materialcraft_core::{Package, Resource, ResourceBytes}; use materialcraft_formats::{Depth, encode, output_name}; use crate::commands::{CommandSpec, always, bad, has_graph, strp, u64p}; @@ -76,6 +76,7 @@ fn new_package(s: &mut Session, p: &J) -> Result { /// Make `pkg` the session's document (after open/new): history and views reset. pub fn replace_package(s: &mut Session, pkg: Package, path: Option) { s.pkg = pkg; + s.clear_decoded(); s.path = path; s.graph = 0; s.selection.clear(); @@ -224,7 +225,7 @@ pub(crate) fn push_resource(pkg: &mut Package, file: &str, bytes: Vec, name: name = format!("{stem}_{i}"); i += 1; } - pkg.resources.push(Resource { name: name.clone(), file: format!("{name}_{file}"), bytes: std::sync::Arc::new(bytes) }); + pkg.resources.push(Resource::new(name.clone(), format!("{name}_{file}"), ResourceBytes::new(bytes))); name } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 040284df..8339877b 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, PoisonError}; -use materialcraft_core::{Graph, NodeId, Package}; +use materialcraft_core::{Graph, NodeId, Package, ResourceBytes}; use materialcraft_eval::{Cache, Cooked, Options}; use materialcraft_image::Image; use serde::{Deserialize, Serialize}; @@ -146,7 +146,7 @@ pub struct Session { redo: Vec, /// Edits with the same key coalesce into one undo step (slider drags). merge_key: Option, - decoded: Arc>>, + decoded: Arc>>, } impl Session { @@ -285,20 +285,27 @@ 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 res: Vec<(String, Arc>)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); + let res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); let memo = self.decoded.clone(); + // Free images of resources that were deleted or replaced. + memo.lock().unwrap_or_else(PoisonError::into_inner).retain(|k, _| res.iter().any(|(_, b)| b.content_hash() == *k)); move |name: &str| { let (_, bytes) = res.iter().find(|(n, _)| n == name)?; - let key = format!("{name}:{}", bytes.len()); + let key = bytes.content_hash(); if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { return Some(i.clone()); } - let img = materialcraft_formats::decode(bytes).ok()?; + let img = materialcraft_formats::decode(bytes.as_slice()).ok()?; memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); Some(img) } } + /// Forget every decoded resource image (the package was replaced). + pub(crate) fn clear_decoded(&self) { + self.decoded.lock().unwrap_or_else(PoisonError::into_inner).clear(); + } + /// Cook the open graph now (at the preview size), on this thread. pub fn cook(&mut self) -> &Cooked { let dec = self.resource_decoder(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5c108526..161a3ea4 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -187,3 +187,19 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() { assert_eq!(s.camera, CameraPrefs::default()); assert_eq!(CameraPrefs { pan_limit: f32::INFINITY, pan_speed: 2.0 }.sanitized().pan_speed, 2.0); } + +#[test] +fn reimported_bitmap_shows_new_pixels() { + 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]; + 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]; + assert!(after - before > 0.5, "{before} -> {after}"); +} diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index b5d18df7..9a125d41 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -178,11 +178,13 @@ pub struct Options<'a> { /// Set from another thread to stop between nodes. pub cancel: Option<&'a AtomicBool>, pub depth: u32, + /// Graphs being cooked around this one, outermost first (cycle detection). + pub graph_stack: Vec, } impl<'a> Options<'a> { pub fn new(resource: &'a (dyn Fn(&str) -> Option + Sync)) -> Options<'a> { - Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0 } + Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0, graph_stack: Vec::new() } } } @@ -261,7 +263,7 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook let opts = if opts.depth == 0 && !graph.input_images.is_empty() { let mut inputs: BTreeMap = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect(); inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone()))); - bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), ..*opts }; + bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), graph_stack: opts.graph_stack.clone(), ..*opts }; &bound } else { opts @@ -288,14 +290,53 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook break; } let Ok(node) = graph.node(id) else { continue }; - let r = cook_node(pkg, graph, node, &out, &vars, opts, cache); + let r = cook_node(pkg, gi, graph, node, &out, &vars, opts, cache); out.nodes.insert(id, r); } out.ms = (now_ms() - t0) as f32; out } -fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BTreeMap, opts: &Options, cache: &mut Cache) -> NodeResult { +/// A hash of graph `gi` and everything it reaches: its own JSON, the content of every +/// resource its nodes name, and (recursively) every graph it instances. A cycle hashes as a +/// marker; `cook_instance` reports it as an error. +fn graph_tree_hash(pkg: &Package, gi: usize, stack: &mut Vec) -> u64 { + let Some(graph) = pkg.graphs.get(gi) else { return 0 }; + if stack.len() > MAX_DEPTH as usize { + return 1; + } + let mut h = DefaultHasher::new(); + serde_json::to_string(graph).unwrap_or_default().hash(&mut h); + for n in &graph.nodes { + if let Some(Value::Text(name)) = n.params.get("resource") { + pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); + } + if n.def != "graph_instance" { + continue; + } + match instance_graph(pkg, n) { + Some((si, _)) if stack.contains(&si) => "cycle".hash(&mut h), + Some((si, _)) => { + stack.push(si); + graph_tree_hash(pkg, si, stack).hash(&mut h); + stack.pop(); + } + None => 0u64.hash(&mut h), + } + } + h.finish() +} + +fn cook_node( + pkg: &Package, + gi: usize, + graph: &Graph, + node: &Node, + done: &Cooked, + vars: &BTreeMap, + opts: &Options, + cache: &mut Cache, +) -> NodeResult { let (in_ports, out_ports) = ports(pkg, node); let def = find(&node.def); // Gather inputs by port order, with their keys. @@ -350,11 +391,10 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT // Input nodes read the caller's image for their identifier. let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); let res_hash = match params.get("resource") { - Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| hash_of(&(r.bytes.len(), r.bytes.get(..64.min(r.bytes.len())).map(|b| b.to_vec())))), + Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), _ => 0, }; - let sub_hash = - if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(_, g)| hash_of(&serde_json::to_string(g).unwrap_or_default())) } else { 0 }; + let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si, &mut vec![si])) } else { 0 }; let key = hash_of(&( &node.def, serde_json::to_string(¶ms).unwrap_or_default(), @@ -375,7 +415,7 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT let img = img.resize(w, h, tile); Ok(vec![if node.def == "input_grayscale" { img.to_gray() } else { img }]) } else if node.def == "graph_instance" { - cook_instance(pkg, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) + cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) } else if let Some(d) = def { let ctx = Ctx { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; (d.cook)(&ctx) @@ -393,8 +433,25 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT } } +/// Whether graph `from` instances graph `target`, directly or through other instanced graphs. +/// `seen` holds the graphs already visited. +fn instances_reach(pkg: &Package, from: usize, target: usize, seen: &mut Vec) -> bool { + let Some(graph) = pkg.graphs.get(from) else { return false }; + graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)).any(|(si, _)| { + if si == target { + return true; + } + if seen.contains(&si) { + return false; + } + seen.push(si); + instances_reach(pkg, si, target, seen) + }) +} + fn cook_instance( pkg: &Package, + gi: usize, node: &Node, in_ports: &[Port], out_ports: &[Port], @@ -407,14 +464,19 @@ fn cook_instance( if opts.depth >= MAX_DEPTH { return Err("graph instances nest too deep (does a graph use itself?)".into()); } - let (gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi, &mut vec![sub_gi]) { + return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); + } let mut o = Options::new(opts.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(gi); o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); - let cooked = cook(pkg, gi, &o, cache); + let cooked = cook(pkg, sub_gi, &o, cache); if cooked.cancelled { return Err("cancelled".into()); } @@ -534,7 +596,78 @@ mod tests { let c = cook(&p, 0, &Options::new(&no_res), &mut 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!(c.nodes[&selfi].error.is_some() || c.nodes[&selfi].outputs.len() == 1); + assert!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); + } + + /// A graph `name` holding one instance of `target` wired to an output. + fn instancing(name: &str, target: &str) -> (Graph, NodeId) { + let mut g = Graph::new(name); + g.size = [4, 4]; + let inst = g.add_node("graph_instance", [0.0, 0.0]); + g.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text(target.into())); + let o = g.add_node("output", [100.0, 0.0]); + g.connect(inst, "output", o, "input").unwrap(); + (g, inst) + } + + #[test] + fn editing_a_nested_graph_recooks_the_top() { + let mut c = Graph::new("c"); + c.size = [4, 4]; + let u = c.add_node("uniform", [0.0, 0.0]); + c.node_mut(u).unwrap().params.insert("mode".into(), Value::Enum(1)); + c.node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.2, 0.2, 0.2, 1.0])); + let o = c.add_node("output", [100.0, 0.0]); + c.connect(u, "output", o, "input").unwrap(); + let (b, _) = instancing("b", "c"); + let (a, top) = instancing("a", "b"); + let mut p = Package::new("p"); + p.graphs = vec![a, b, c]; + let mut cache = Cache::default(); + let opts = Options::new(&no_res); + let first = cook(&p, 0, &opts, &mut cache); + let out_a = p.graphs[0].nodes.iter().find(|n| n.def == "output").unwrap().id; + assert!((first.image(out_a, 0).unwrap().mean()[0] - 0.2).abs() < 0.01); + p.graphs[2].node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.8, 0.8, 0.8, 1.0])); + let second = cook(&p, 0, &opts, &mut cache); + assert!(!second.nodes[&top].cached); + assert!((second.image(out_a, 0).unwrap().mean()[0] - 0.8).abs() < 0.01); + } + + #[test] + fn mutual_instances_are_an_error() { + let (x, xi) = instancing("x", "y"); + let (y, _) = instancing("y", "x"); + let mut p = Package::new("p"); + p.graphs = vec![x, y]; + let mut cache = Cache::default(); + let c = cook(&p, 0, &Options::new(&no_res), &mut cache); + assert!(c.nodes[&xi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&xi].error); + } + + #[test] + fn same_size_resources_key_differently() { + use materialcraft_core::{Resource, ResourceBytes}; + use std::sync::atomic::AtomicU8; + let mut g = Graph::new("g"); + g.size = [4, 4]; + let bm = g.add_node("bitmap", [0.0, 0.0]); + g.node_mut(bm).unwrap().params.insert("resource".into(), Value::Text("tex".into())); + let mut p = Package::new("p"); + p.graphs.push(g); + p.resources.push(Resource::new("tex", "tex.bin", ResourceBytes::new(vec![1; 100]))); + // Stands in for decoding: the first byte picks the shade. + let shade = AtomicU8::new(1); + let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 4])); + let mut cache = Cache::default(); + let opts = Options::new(&res); + let first = cook(&p, 0, &opts, &mut cache); + let mean = first.image(bm, 0).unwrap().mean()[0]; + p.resources[0].bytes = ResourceBytes::new(vec![2; 100]); + shade.store(2, Ordering::Relaxed); + let second = cook(&p, 0, &opts, &mut cache); + assert!(!second.nodes[&bm].cached); + assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05); } #[test] diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 9013dc3e..3503b266 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -15,7 +15,7 @@ use std::collections::HashMap; use std::io::{Cursor, Read, Write}; use std::sync::Arc; -use materialcraft_core::{OutputFormat, Package}; +use materialcraft_core::{OutputFormat, Package, ResourceBytes}; use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear}; #[derive(Debug, thiserror::Error)] @@ -59,7 +59,7 @@ pub fn save_package(pkg: &Package) -> Result> { // Images are already compressed. let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); z.start_file(format!("resources/{}", safe_file_name(&r.file)), stored).map_err(io)?; - z.write_all(&r.bytes).map_err(|e| FormatError::Io(e.to_string()))?; + z.write_all(r.bytes.as_slice()).map_err(|e| FormatError::Io(e.to_string()))?; } z.finish().map_err(io)?; } @@ -85,11 +85,11 @@ fn load_package_within(bytes: &[u8], max_total: u64) -> Result { return Err(FormatError::BadPackage(format!("{} resources (limit {MAX_RESOURCES})", pkg.resources.len()))); } let mut total = json.len() as u64; - let mut read: HashMap>> = HashMap::new(); + let mut read: HashMap = HashMap::new(); for r in &mut pkg.resources { let name = format!("resources/{}", safe_file_name(&r.file)); if let Some(shared) = read.get(&name) { - r.bytes = Arc::clone(shared); + r.bytes = shared.clone(); continue; } let mut data = Vec::new(); @@ -100,8 +100,8 @@ fn load_package_within(bytes: &[u8], max_total: u64) -> Result { if total > max_total { return Err(FormatError::BadPackage(format!("package resources exceed {max_total} bytes"))); } - let data = Arc::new(data); - read.insert(name, Arc::clone(&data)); + let data = ResourceBytes::new(data); + read.insert(name, data.clone()); r.bytes = data; } Ok(pkg) @@ -284,12 +284,12 @@ mod tests { g.connect(a, "output", o, "input").unwrap(); p.graphs.push(g); let png = encode(&Image::filled(4, 4, Kind::Color, [1.0, 0.5, 0.0, 1.0]), "png", Depth::U8, true).unwrap(); - p.resources.push(Resource { name: "tex".into(), file: "../../evil/tex.png".into(), bytes: Arc::new(png) }); + p.resources.push(Resource::new("tex", "../../evil/tex.png", ResourceBytes::new(png))); let bytes = save_package(&p).unwrap(); let q = load_package(&bytes).unwrap(); assert_eq!(q.graphs, p.graphs); assert_eq!(q.resources[0].bytes, p.resources[0].bytes); - let img = decode(&q.resources[0].bytes).unwrap(); + let img = decode(q.resources[0].bytes.as_slice()).unwrap(); assert!((img.get(0, 0, false)[1] - 0.5).abs() < 0.01); assert!(load_package(b"not a zip").is_err()); } @@ -348,7 +348,7 @@ mod tests { let pkg = load_package(&bytes).unwrap(); assert_eq!(pkg.resources.len(), 1000); assert_eq!(pkg.resources[0].bytes.len(), 1 << 20); - assert!(Arc::ptr_eq(&pkg.resources[0].bytes, &pkg.resources[999].bytes)); + assert!(pkg.resources[0].bytes.ptr_eq(&pkg.resources[999].bytes)); } #[test] From eef9f5397fe6c15340baff88a843b1a9b2f29a6b Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:23:07 -0600 Subject: [PATCH 09/91] Nodes: clamp parameters to hard limits before cooking --- crates/eval/src/lib.rs | 20 +++++++++++- crates/nodes/src/catalog.rs | 54 ++++++++++++++++++++++++++++++++ crates/nodes/src/filters.rs | 18 ++++++++--- crates/nodes/src/filters_more.rs | 3 +- crates/nodes/src/generators.rs | 3 +- crates/nodes/src/lib.rs | 47 ++++++++++++++++++++++++++- 6 files changed, 137 insertions(+), 8 deletions(-) diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index b5d18df7..369ff9f8 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value}; use materialcraft_image::{Image, Kind}; -use materialcraft_nodes::{Ctx, NodeDef, PortKind, find, resolve_params}; +use materialcraft_nodes::{Ctx, NodeDef, PortKind, clamp_params, find, resolve_params}; /// Sub-graphs may nest this deep (a graph instancing itself would recurse forever). pub const MAX_DEPTH: u32 = 8; @@ -346,6 +346,12 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT Err(e) => return fail(format!("function of `{param}`: {e}"), 0), } } + // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook). + if let Some(d) = def + && node.def != "graph_instance" + { + clamp_params(d, &mut params); + } let tile = node.base.tiling[0] && node.base.tiling[1]; // Input nodes read the caller's image for their identifier. let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); @@ -495,6 +501,18 @@ mod tests { assert_eq!(outputs(&p.graphs[0], &c).len(), 1); } + #[test] + fn hostile_param_is_clamped_before_cooking() { + let (mut p, noise, _, _) = sample(); + let blur = p.graphs[0].add_node("anisotropic_blur", [150.0, 100.0]); + p.graphs[0].connect(noise, "output", blur, "input").unwrap(); + p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30)); + let mut cache = Cache::default(); + let c = cook(&p, 0, &Options::new(&no_res), &mut 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))); + } + #[test] fn preview_cap_and_unknown_nodes() { let (mut p, _, _, out) = sample(); diff --git a/crates/nodes/src/catalog.rs b/crates/nodes/src/catalog.rs index aed5b9b0..719c98e1 100644 --- a/crates/nodes/src/catalog.rs +++ b/crates/nodes/src/catalog.rs @@ -352,6 +352,60 @@ pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> { out } +/// How many slider spans the hard limit extends past each end of a parameter's range. +const HARD_SPAN: f32 = 16.0; + +/// Clamp `v` to `[lo, hi]`; a non-finite `v` becomes `fallback`. +fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 { + if v.is_finite() { v.clamp(lo, hi) } else { fallback } +} + +/// Clamp numeric parameters to hard limits: the declared slider range widened by +/// `HARD_SPAN` spans on each side (the editor lets values past the slider through, so the +/// slider range itself is not a limit). Non-finite values become the default. Keeps cooks +/// bounded whatever a file, binding, function or command supplies. +pub fn clamp_params(def: &NodeDef, params: &mut BTreeMap) { + for p in &def.params { + let Some(v) = params.get_mut(p.id) else { continue }; + if let Value::Enum(i) = v { + if !p.options.is_empty() { + *i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX)); + } + continue; + } + if let Value::Color(c) = v { + for x in c { + *x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0); + } + continue; + } + if p.min >= p.max { + continue; + } + let span = p.max - p.min; + let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span); + // The default's component `i`, or 0 when the default is a different variant. + let fallback = |i: usize| match &p.default { + Value::Float(d) => [*d].get(i).copied(), + Value::Float2(d) => d.get(i).copied(), + Value::Float3(d) => d.get(i).copied(), + Value::Float4(d) => d.get(i).copied(), + _ => None, + }; + let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0)); + let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32; + match v { + Value::Float(x) => clamp_at(x, 0), + Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Int(x) => clamp_int(x), + Value::Int2(a) => a.iter_mut().for_each(clamp_int), + _ => {} + } + } +} + /// Parameter values for a node: catalog defaults overlaid with `overrides`. pub fn resolve_params(def: &NodeDef, overrides: &BTreeMap) -> BTreeMap { let mut m: BTreeMap = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect(); diff --git a/crates/nodes/src/filters.rs b/crates/nodes/src/filters.rs index 84a6645e..702383b5 100644 --- a/crates/nodes/src/filters.rs +++ b/crates/nodes/src/filters.rs @@ -361,7 +361,8 @@ fn contrast_luminosity(ctx: &Ctx) -> CookResult { } fn exposure(ctx: &Ctx) -> CookResult { - let k = 2f32.powf(ctx.f("stops")); + // Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite. + let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0)); per_value(ctx, |v| v * k) } @@ -504,7 +505,15 @@ fn anisotropic_blur(ctx: &Ctx) -> CookResult { Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))]) } +/// Most extra horizontal passes `blur_xy` runs: a cost bound, whatever sigma it is given. +const MAX_BLUR_PASSES: i64 = 64; +/// Widest horizontal kernel half-width `blur_xy` builds: a cost bound on the kernel allocation. +const MAX_KERNEL_RADIUS: i64 = 512; + fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { + if !sx.is_finite() || !sy.is_finite() { + return img.clone(); + } // Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so // blur fully with the smaller sigma and add the extra along x by repeated small passes. let base = ops::gaussian(img, sy, tile); @@ -512,12 +521,12 @@ fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { if extra < 0.1 { return base; } - let n = (extra / 2.0).ceil().max(1.0) as i64; + let n = ((extra / 2.0).ceil().max(1.0) as i64).min(MAX_BLUR_PASSES); let step = extra / (n as f32).sqrt(); let mut out = base; for _ in 0..n { let src = out.clone(); - let r = (step * 2.0).ceil() as i64; + let r = ((step * 2.0).ceil() as i64).clamp(1, MAX_KERNEL_RADIUS); let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect(); let sum: f32 = k.iter().sum(); out = Image::generate(src.w, src.h, src.kind, |x, y| { @@ -687,7 +696,8 @@ fn edge_detect(ctx: &Ctx) -> CookResult { .map(|(a, b)| { let d = a.sqrt().max(b.sqrt()); let t = (1.0 - d / w).max(0.0); - t.powf(1.0 - round * 0.8) + // A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2. + t.powf((1.0 - round * 0.8).max(0.01)) }) .collect(); Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) diff --git a/crates/nodes/src/filters_more.rs b/crates/nodes/src/filters_more.rs index 403f2bb0..68c39415 100644 --- a/crates/nodes/src/filters_more.rs +++ b/crates/nodes/src/filters_more.rs @@ -222,7 +222,8 @@ fn smoothstep_node(ctx: &Ctx) -> CookResult { } fn s_curve(ctx: &Ctx) -> CookResult { - let (k, p) = (1.0 + ctx.f("amount") * 4.0, ctx.f("pivot").clamp(0.01, 0.99)); + // A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1). + let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99)); per_channel(ctx, |v, _| { let v = v.clamp(0.0, 1.0); if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) } diff --git a/crates/nodes/src/generators.rs b/crates/nodes/src/generators.rs index 700a6a08..f30db65a 100644 --- a/crates/nodes/src/generators.rs +++ b/crates/nodes/src/generators.rs @@ -357,7 +357,8 @@ fn plasma(ctx: &Ctx) -> CookResult { fn turbulence(ctx: &Ctx) -> CookResult { let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).sqrt())]) + // A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN. + Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())]) } fn creased(ctx: &Ctx) -> CookResult { diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index d51c3d95..a30494ac 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -28,12 +28,13 @@ pub mod svg; pub mod text; pub mod weathering; -pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, find, resolve_params}; +pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, clamp_params, find, resolve_params}; #[cfg(test)] mod tests { use std::collections::BTreeMap; + use materialcraft_core::Value; use materialcraft_image::{Image, Kind}; use super::*; @@ -72,6 +73,50 @@ mod tests { assert!(catalog().len() >= 200, "{} nodes", catalog().len()); } + /// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN): + /// the hard limits keep the cook bounded, finite and the right size. + #[test] + fn every_node_survives_hostile_params() { + use std::time::{Duration, Instant}; + + let mut slow: Vec<(String, Duration)> = Vec::new(); + let total = Instant::now(); + for def in catalog() { + if def.id == "graph_instance" { + continue; + } + for p in &def.params { + for h in [1e30_f32, -1e30, f32::NAN] { + let v = match p.default { + Value::Float(_) => Value::Float(h), + Value::Int(_) => Value::Int(h as i32), + Value::Float2(_) => Value::Float2([h, h]), + Value::Enum(_) => Value::Enum(h as u32), + _ => continue, + }; + let mut params = resolve_params(def, &BTreeMap::from([(p.id.to_string(), v)])); + clamp_params(def, &mut params); + let inputs = vec![None; def.inputs.len()]; + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let ctx = Ctx { w: 16, h: 16, seed: 7, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + let t = Instant::now(); + let out = (def.cook)(&ctx).unwrap_or_else(|e| panic!("{}.{}={h}: {e}", def.id, p.id)); + let dt = t.elapsed(); + assert!(dt < Duration::from_secs(2), "{}.{}={h} took {dt:?}", def.id, p.id); + if dt > Duration::from_millis(250) { + slow.push((format!("{}.{}={h}", def.id, p.id), dt)); + } + 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); + } + } + } + } + eprintln!("hostile params: total {:?}; cooks over 250 ms: {slow:?}", total.elapsed()); + } + #[test] fn noises_tile() { for id in [ From 55f1a1c3232ac504833ddedcfc9e63a4b713e4d2 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:30:34 -0600 Subject: [PATCH 10/91] Engine: add cook benchmarks for input changes and parameter edits Baseline (noisy, concurrent load), input change: 1024 ~320 ms, 2048 ~1500 ms, 21 of 21 nodes re-cooked. --- crates/engine/tests/perf.rs | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 crates/engine/tests/perf.rs diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs new file mode 100644 index 00000000..99fc053b --- /dev/null +++ b/crates/engine/tests/perf.rs @@ -0,0 +1,55 @@ +//! Cook benchmarks (run with `--ignored --nocapture` in release). +use std::time::Instant; + +use materialcraft_engine::{Session, execute, sample_session}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + execute(s, id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +/// The `rusty_metal` template plus an exposed input `level` read by one unconnected `uniform`. +fn heavy(size: u64) -> (Session, u64) { + let mut s = sample_session(); + run(&mut s, "file.new", json!({"template": "rusty_metal", "size": size})); + s.preview_size = None; + let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"mode": 1}}))["id"].as_u64().unwrap(); + run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}})); + let f = json!({"nodes": [{"id": 1, "op": "get_var", "value": {"t": "text", "v": "level"}}], "output": 1}); + run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f})); + (s, u) +} + +fn timed(s: &mut Session) -> (f64, usize, usize) { + let t = Instant::now(); + s.cook(); + let ms = t.elapsed().as_secs_f64() * 1000.0; + (ms, s.cooked.nodes.values().filter(|r| !r.cached).count(), s.cooked.nodes.len()) +} + +#[test] +#[ignore = "benchmark"] +fn bench_input_change() { + println!("size, cold_ms, warm_ms, input_change_ms, recooked_nodes, total_nodes"); + for size in [1024, 2048] { + let (mut s, _) = heavy(size); + let (cold, ..) = timed(&mut s); + let (warm, ..) = timed(&mut s); + run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75})); + let (change, recooked, total) = timed(&mut s); + println!("{size}, {cold:.1}, {warm:.1}, {change:.1}, {recooked}, {total}"); + } +} + +#[test] +#[ignore = "benchmark"] +fn bench_param_edit() { + println!("size, cold_ms, param_edit_ms, recooked_nodes, total_nodes"); + for size in [1024, 2048] { + let (mut s, u) = heavy(size); + let (cold, ..) = timed(&mut s); + run(&mut s, "graph.node.param", json!({"id": u, "param": "mode", "value": 0})); + let (edit, recooked, total) = timed(&mut s); + println!("{size}, {cold:.1}, {edit:.1}, {recooked}, {total}"); + } +} From b991f4fb112d2b87f79925c972787248b809254b Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:30:34 -0600 Subject: [PATCH 11/91] Eval: key nodes only on the graph inputs they read An exposed-input change re-cooked 21 of 21 nodes in rusty_metal; now 1 (the reader). Input-change cook (noisy, concurrent load): 1024 ~320 ms -> ~0.1 ms, 2048 ~1500 ms -> ~0.2 ms. --- crates/engine/tests/session.rs | 16 ++++++++++++++ crates/eval/src/lib.rs | 40 +++++++++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 161a3ea4..79bb422a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -138,6 +138,22 @@ fn dynamic_parameters_follow_graph_inputs() { assert!((mean(&s) - 0.5).abs() < 0.05); } +#[test] +fn exposed_input_change_recooks_only_readers() { + let mut s = sample_session(); + run(&mut s, "file.new", json!({"template": "rusty_metal", "size": 64})); + s.preview_size = None; + let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"mode": 1}}))["id"].as_u64().unwrap(); + run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}})); + let f = json!({"nodes": [{"id": 1, "op": "get_var", "value": {"t": "text", "v": "level"}}], "output": 1}); + run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f})); + s.cook(); + run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75})); + s.cook(); + let recooked: Vec = s.cooked.nodes.iter().filter(|(_, r)| !r.cached).map(|(id, _)| u64::from(id.0)).collect(); + assert_eq!(recooked, [u], "only the node reading `level` re-cooks"); +} + #[test] fn presets_store_and_restore_inputs() { let mut s = sample_session(); diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 9a125d41..9cc33761 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -327,6 +327,24 @@ fn graph_tree_hash(pkg: &Package, gi: usize, stack: &mut Vec) -> u64 { h.finish() } +/// The graph inputs a node's cook can read: those named by `get_*` ops of its function-valued +/// parameters. Bindings and node functions are already folded into `params` before the key is +/// computed, so these are the only remaining readers of `vars` (`Ctx::vars` in the function nodes). +/// Matching every `get_*` op, not only `get_var`, over-approximates on purpose. +fn vars_read<'v>(params: &BTreeMap, vars: &'v BTreeMap) -> Vec<(&'v str, &'v Value)> { + let mut read: Vec<(&str, &Value)> = params + .values() + .filter_map(|v| if let Value::Function(g) = v { Some(g) } else { None }) + .flat_map(|g| g.nodes.iter()) + .filter(|n| n.op.starts_with("get_")) + .filter_map(|n| if let Some(Value::Text(name)) = &n.value { vars.get_key_value(name.as_str()) } else { None }) + .map(|(k, v)| (k.as_str(), v)) + .collect(); + read.sort_by_key(|(k, _)| *k); + read.dedup_by_key(|(k, _)| *k); + read +} + fn cook_node( pkg: &Package, gi: usize, @@ -403,7 +421,7 @@ fn cook_node( res_hash, sub_hash, input_img.map(image_key), - serde_json::to_string(vars).unwrap_or_default(), + serde_json::to_string(&vars_read(¶ms, vars)).unwrap_or_default(), )); if let Some(v) = cache.get(key) { return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; @@ -692,4 +710,24 @@ mod tests { let c = cook(&p, 0, &opts, &mut cache); assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); } + + #[test] + fn input_change_recooks_only_readers() { + use materialcraft_core::function::{FnGraph, FnNode}; + let (mut p, noise, blur, out) = sample(); + let reader = p.graphs[0].add_node("pixel_processor", [0.0, 100.0]); + let get_a = FnNode { id: 1, op: "get_var".into(), inputs: vec![], value: Some(Value::Text("a".into())), pos: [0.0; 2] }; + p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FnGraph { nodes: vec![get_a], output: Some(1) }))); + let cache = &mut Cache::default(); + let mut opts = Options::new(&no_res); + opts.overrides.insert("a".into(), Value::Float(0.25)); + let first = cook(&p, 0, &opts, cache); + assert!(first.nodes.values().all(|r| r.error.is_none() && !r.cached)); + opts.overrides.insert("a".into(), Value::Float(0.75)); + let second = cook(&p, 0, &opts, cache); + for id in [noise, blur, out] { + assert!(second.nodes[&id].cached, "node {} does not read `a`", id.0); + } + assert!(!second.nodes[&reader].cached, "the reader must re-cook"); + } } From 2758d1d389da5c676aa1564a92cc9faacda55df6 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:37:56 -0600 Subject: [PATCH 12/91] Cook: cancel stale background cooks and lock the cache only around lookups The cooker sets the running cook's cancel flag when the graph changes again and starts the new cook at once; eval::cook takes &Mutex and locks per lookup/insert. --- crates/engine/src/material_cmds.rs | 5 +-- crates/engine/src/session.rs | 9 +---- crates/eval/src/lib.rs | 60 ++++++++++++++++-------------- crates/ui-egui/src/cook.rs | 29 ++++++++++++--- 4 files changed, 59 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index c5902b97..b8d55711 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -72,10 +72,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result)> = Vec::new(); let mut entries = Vec::new(); let mut size = [0, 0]; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 8339877b..cf9d6cc5 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -311,11 +311,7 @@ impl Session { let dec = self.resource_decoder(); let mut opts = Options::new(&dec); opts.max_size = self.preview_size; - let cooked = { - let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_eval::cook(&self.pkg, self.graph, &opts, &mut cache) - }; - self.cooked = cooked; + self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache); self.dirty = false; &self.cooked } @@ -324,8 +320,7 @@ impl Session { pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); let opts = Options::new(&dec); - let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_eval::cook(&self.pkg, gi, &opts, &mut cache) + materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache) } /// Cook if the graph changed since the last cook. diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 9cc33761..d25a49e4 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, HashMap}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value}; @@ -253,8 +253,14 @@ pub fn function_value(like: &Value, v: [f32; 4]) -> Option { }) } -/// Cook graph `gi` of `pkg`. -pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cooked { +/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written). +fn lock(cache: &Mutex) -> std::sync::MutexGuard<'_, Cache> { + cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Cook graph `gi` of `pkg`. The cache is locked only around lookups and inserts, never while a +/// node cooks, so other users of the cache are not blocked for the length of a cook. +pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex) -> Cooked { let t0 = now_ms(); let mut out = Cooked::default(); let Some(graph) = pkg.graphs.get(gi) else { return out }; @@ -353,7 +359,7 @@ fn cook_node( done: &Cooked, vars: &BTreeMap, opts: &Options, - cache: &mut Cache, + cache: &Mutex, ) -> NodeResult { let (in_ports, out_ports) = ports(pkg, node); let def = find(&node.def); @@ -423,7 +429,7 @@ fn cook_node( input_img.map(image_key), serde_json::to_string(&vars_read(¶ms, vars)).unwrap_or_default(), )); - if let Some(v) = cache.get(key) { + if let Some(v) = lock(cache).get(key) { return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; } let t0 = now_ms(); @@ -443,7 +449,7 @@ fn cook_node( match result { Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { let v = Arc::new(imgs); - cache.put(key, v.clone()); + lock(cache).put(key, v.clone()); NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } } Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), @@ -477,7 +483,7 @@ fn cook_instance( params: &BTreeMap, size: (u32, u32), opts: &Options, - cache: &mut Cache, + cache: &Mutex, ) -> Result, String> { if opts.depth >= MAX_DEPTH { return Err("graph instances nest too deep (does a graph use itself?)".into()); @@ -560,17 +566,17 @@ mod tests { #[test] fn cooks_and_caches() { let (mut p, noise, blur, out) = sample(); - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let opts = Options::new(&no_res); - let a = cook(&p, 0, &opts, &mut cache); + 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))); // Same graph: everything from the cache. - let b = cook(&p, 0, &opts, &mut cache); + let b = cook(&p, 0, &opts, &cache); assert!(b.nodes.values().all(|r| r.cached)); // Editing the blur re-cooks the blur and the output, not the noise. p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(5.0)); - let c = cook(&p, 0, &opts, &mut cache); + let c = cook(&p, 0, &opts, &cache); assert!(c.nodes[&noise].cached && !c.nodes[&blur].cached && !c.nodes[&out].cached); assert_eq!(outputs(&p.graphs[0], &c).len(), 1); } @@ -580,10 +586,10 @@ mod tests { let (mut p, _, _, out) = sample(); p.graphs[0].size = [10, 10]; let bad = p.graphs[0].add_node("no_such_node", [0.0, 0.0]); - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let mut opts = Options::new(&no_res); opts.max_size = Some(128); - let c = cook(&p, 0, &opts, &mut cache); + let c = cook(&p, 0, &opts, &cache); assert_eq!(c.image(out, 0).map(|i| i.w), Some(128)); assert!(c.nodes[&bad].error.is_some()); } @@ -610,8 +616,8 @@ mod tests { // A graph instancing itself is refused, not a stack overflow. let selfi = g.add_node("graph_instance", [0.0, 200.0]); g.node_mut(selfi).unwrap().params.insert("graph".into(), Value::Text("g".into())); - let mut cache = Cache::default(); - let c = cook(&p, 0, &Options::new(&no_res), &mut cache); + let cache = Mutex::new(Cache::default()); + 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!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error); @@ -641,13 +647,13 @@ mod tests { let (a, top) = instancing("a", "b"); let mut p = Package::new("p"); p.graphs = vec![a, b, c]; - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let opts = Options::new(&no_res); - let first = cook(&p, 0, &opts, &mut cache); + let first = cook(&p, 0, &opts, &cache); let out_a = p.graphs[0].nodes.iter().find(|n| n.def == "output").unwrap().id; assert!((first.image(out_a, 0).unwrap().mean()[0] - 0.2).abs() < 0.01); p.graphs[2].node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.8, 0.8, 0.8, 1.0])); - let second = cook(&p, 0, &opts, &mut cache); + let second = cook(&p, 0, &opts, &cache); assert!(!second.nodes[&top].cached); assert!((second.image(out_a, 0).unwrap().mean()[0] - 0.8).abs() < 0.01); } @@ -658,8 +664,8 @@ mod tests { let (y, _) = instancing("y", "x"); let mut p = Package::new("p"); p.graphs = vec![x, y]; - let mut cache = Cache::default(); - let c = cook(&p, 0, &Options::new(&no_res), &mut cache); + let cache = Mutex::new(Cache::default()); + let c = cook(&p, 0, &Options::new(&no_res), &cache); assert!(c.nodes[&xi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&xi].error); } @@ -677,13 +683,13 @@ mod tests { // Stands in for decoding: the first byte picks the shade. let shade = AtomicU8::new(1); let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 4])); - let mut cache = Cache::default(); + let cache = Mutex::new(Cache::default()); let opts = Options::new(&res); - let first = cook(&p, 0, &opts, &mut cache); + let first = cook(&p, 0, &opts, &cache); let mean = first.image(bm, 0).unwrap().mean()[0]; p.resources[0].bytes = ResourceBytes::new(vec![2; 100]); shade.store(2, Ordering::Relaxed); - let second = cook(&p, 0, &opts, &mut cache); + let second = cook(&p, 0, &opts, &cache); assert!(!second.nodes[&bm].cached); assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05); } @@ -700,14 +706,14 @@ mod tests { g.input_images.insert("curvature".into(), "curv".into()); p.graphs.push(g); let res = |n: &str| (n == "curv").then(|| Image::filled(4, 4, Kind::Color, [0.8, 0.8, 0.8, 1.0])); - let mut cache = Cache::default(); - let c = cook(&p, 0, &Options::new(&res), &mut cache); + let cache = Mutex::new(Cache::default()); + 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"); // 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, &mut cache); + let c = cook(&p, 0, &opts, &cache); assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4); } @@ -718,7 +724,7 @@ mod tests { let reader = p.graphs[0].add_node("pixel_processor", [0.0, 100.0]); let get_a = FnNode { id: 1, op: "get_var".into(), inputs: vec![], value: Some(Value::Text("a".into())), pos: [0.0; 2] }; p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FnGraph { nodes: vec![get_a], output: Some(1) }))); - let cache = &mut Cache::default(); + let cache = &Mutex::new(Cache::default()); let mut opts = Options::new(&no_res); opts.overrides.insert("a".into(), Value::Float(0.25)); let first = cook(&p, 0, &opts, cache); diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index 9b6e4100..57033c1b 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -10,6 +10,9 @@ use crate::MaterialCraftApp; #[derive(Default)] pub struct Cooker { rx: Option>, + /// Stops the running cook between nodes once its result is stale. + #[cfg(not(target_arch = "wasm32"))] + cancel: Option>, /// When the running cook started (app seconds). pub started: Option, } @@ -25,11 +28,25 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(rx) = &app.cooker.rx { match rx.try_recv() { Ok(c) => { - app.session.cooked = c; + if c.cancelled { + // A stopped cook is partial: keep the previous results and cook again. + app.session.dirty = true; + } else { + app.session.cooked = c; + } app.cooker.rx = None; app.cooker.started = None; ctx.request_repaint(); } + Err(TryRecvError::Empty) if app.session.dirty => { + // The running cook is stale: stop it, ignore its result and cook the new state. + #[cfg(not(target_arch = "wasm32"))] + if let Some(flag) = &app.cooker.cancel { + flag.store(true, std::sync::atomic::Ordering::Relaxed); + } + app.cooker.rx = None; + app.cooker.started = None; + } Err(TryRecvError::Empty) => { ctx.request_repaint_after(std::time::Duration::from_millis(16)); return; @@ -55,20 +72,20 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let cache = s.cache.clone(); let dec = s.resource_decoder(); let (tx, rx) = std::sync::mpsc::channel(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let thread_flag = flag.clone(); use materialcraft_engine::eval::Options; - use std::sync::PoisonError; let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || { let mut opts = Options::new(&dec); opts.max_size = max; - let cooked = { - let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_engine::eval::cook(&pkg, gi, &opts, &mut cache) - }; + opts.cancel = Some(&thread_flag); + let cooked = materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache); let _ = tx.send(cooked); }); match spawned { Ok(_) => { app.cooker.rx = Some(rx); + app.cooker.cancel = Some(flag); app.cooker.started = Some(now); } Err(e) => { From 76684bc3a870c38efd8a8b69ca8915f76dabc6df Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:38:35 -0600 Subject: [PATCH 13/91] Cook: format and lint fixes --- crates/engine/tests/session.rs | 2 +- crates/eval/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 79bb422a..8f55883e 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -150,7 +150,7 @@ fn exposed_input_change_recooks_only_readers() { s.cook(); run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75})); s.cook(); - let recooked: Vec = s.cooked.nodes.iter().filter(|(_, r)| !r.cached).map(|(id, _)| u64::from(id.0)).collect(); + let recooked: Vec = s.cooked.nodes.iter().filter(|(_, r)| !r.cached).map(|(id, _)| id.0).collect(); assert_eq!(recooked, [u], "only the node reading `level` re-cooks"); } diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index d25a49e4..ebdbafa0 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -11,8 +11,8 @@ use std::collections::{BTreeMap, HashMap}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value}; use materialcraft_image::{Image, Kind}; From c9e3a9ea837eb51ab19cbedf0d03a0072fa57ee2 Mon Sep 17 00:00:00 2001 From: smittie2000 Date: Tue, 3 Nov 2026 22:55:23 +0200 Subject: [PATCH 14/91] fix(windows): a start that never opens a window says why instead of exiting silently Without a usable GPU, driver or desktop, no graphics backend can create a window and MaterialCraft exited with code 1 and nothing on screen. The reason now goes to the log and to an error dialog, as FilmCraft does since 0.14.0 (which unstuck it on WinGet). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + apps/materialcraft/Cargo.toml | 2 ++ apps/materialcraft/src/main.rs | 3 +++ apps/materialcraft/src/start_failure.rs | 36 +++++++++++++++++++++++++ 4 files changed, 42 insertions(+) create mode 100644 apps/materialcraft/src/start_failure.rs diff --git a/Cargo.lock b/Cargo.lock index ce3b0fc1..2cf4cdaa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2315,6 +2315,7 @@ dependencies = [ "log", "materialcraft-engine", "materialcraft-ui-egui", + "rfd", "serde_json", "winresource", ] diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 64a1ca49..d5783b90 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -18,6 +18,8 @@ egui = { workspace = true } image = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# A start that never opens a window says why in an error dialog (src/start_failure.rs). +rfd = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index 5a27232c..781e79d0 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod control_server; +mod start_failure; use materialcraft_engine::Session; use materialcraft_ui_egui::MaterialCraftApp; @@ -118,6 +119,8 @@ fn main() { ); if let Err(e) = r { eprintln!("materialcraft: {e}"); + // Say why instead of exiting silently (`start_failure`). + start_failure::report(&e); std::process::exit(1); } } diff --git a/apps/materialcraft/src/start_failure.rs b/apps/materialcraft/src/start_failure.rs new file mode 100644 index 00000000..836ae6ba --- /dev/null +++ b/apps/materialcraft/src/start_failure.rs @@ -0,0 +1,36 @@ +//! A window that can't start, or stops, says why instead of the app quitting silently. +//! +//! Without a usable GPU, graphics driver or desktop (a broken or very old driver, a remote or +//! virtual machine, a program started by a service or a test harness), the window's surface +//! can't be configured and eframe returns an error. MaterialCraft used to log it and exit with no +//! window, which looks like "the app doesn't open". +//! winget-pkgs validation starts installed programs without a desktop, so a version that fails +//! like this never reaches WinGet. +//! +//! Now the reason also goes to an error dialog, as FilmCraft does since 0.14.0. The dialog keeps +//! the process alive until it is dismissed; the exit code afterwards is still the error's. + +/// What the dialog and the log say. +pub(crate) fn message(error: &eframe::Error) -> String { + format!("MaterialCraft could not start its window: {error}\n\nUpdating the graphics driver usually fixes this.") +} + +/// Logs the failure and shows it in a dialog, which stays until the user closes it. +pub(crate) fn report(error: &eframe::Error) { + let message = message(error); + log::error!("{message}"); + let _ = rfd::MessageDialog::new().set_title("MaterialCraft").set_description(&message).set_level(rfd::MessageLevel::Error).show(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_message_names_the_cause_and_what_to_do() { + let text = message(&eframe::Error::AppCreation("no adapter".into())); + assert!(text.starts_with("MaterialCraft could not start its window"), "{text}"); + assert!(text.contains("no adapter"), "{text}"); + assert!(text.contains("graphics driver"), "{text}"); + } +} From 0dee441161bdde2ae01d6df1031f33c31f249c68 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Tue, 3 Nov 2026 22:45:17 +0100 Subject: [PATCH 15/91] feat(i18n): add complete Arabic (ar) UI localization and font fallbacks - Add full Arabic translation table (363 entries) in crates/ui-egui/src/i18n/ar.rs - Implement live language switching, locale detection and RTL support in crates/ui-egui/src/i18n.rs - Add system font fallbacks for Arabic (Segoe UI, SF Arabic, Noto Sans Arabic) in crates/ui-egui/src/fonts.rs - Add language selector combo box to Preferences dialog in crates/ui-egui/src/windows.rs - Add language preference persistence in crates/ui-egui/src/state.rs - Update docs/localization-parity.md tracking Arabic support --- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/fonts.rs | 92 +++++++++ crates/ui-egui/src/i18n.rs | 169 +++++++++++++++- crates/ui-egui/src/i18n/ar.rs | 367 ++++++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 8 + crates/ui-egui/src/state.rs | 3 + crates/ui-egui/src/windows.rs | 11 +- docs/localization-parity.md | 2 + 8 files changed, 646 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/fonts.rs create mode 100644 crates/ui-egui/src/i18n/ar.rs diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 0eb3447a..93ee1188 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -23,6 +23,7 @@ image = { workspace = true } zip = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +sys-locale = "0.3" rfd = { workspace = true } # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs new file mode 100644 index 00000000..4be466bc --- /dev/null +++ b/crates/ui-egui/src/fonts.rs @@ -0,0 +1,92 @@ +//! Arabic fallback fonts for the UI. egui's default fonts have no Arabic glyphs, so translated +//! UIs need fallback fonts from the operating system. +//! +//! Windows: Segoe UI, Tahoma, Arial +//! macOS: SF Arabic, Geeza Pro, Arial Unicode +//! Linux: Noto Sans Arabic, DejaVu Sans + +use std::sync::Arc; + +use egui::{FontData, FontFamily}; + +/// Candidate system font files: (path, face index in a collection). +#[cfg(not(target_arch = "wasm32"))] +fn system_files() -> Vec<(std::path::PathBuf, u32)> { + use std::path::PathBuf; + let mut v: Vec<(PathBuf, u32)> = Vec::new(); + if cfg!(windows) { + let fonts = PathBuf::from(std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into())).join("Fonts"); + let files: &[&str] = &["segoeui.ttf", "tahoma.ttf", "arial.ttf"]; + v.extend(files.iter().map(|f| (fonts.join(f), 0))); + } else if cfg!(target_os = "macos") { + let files: &[&str] = &["/System/Library/Fonts/SFArabic.ttf", "/System/Library/Fonts/Supplemental/GeezaPro.ttc"]; + v.extend(files.iter().map(|f| (PathBuf::from(f), 0))); + v.push((PathBuf::from("/System/Library/Fonts/Supplemental/Arial Unicode.ttf"), 0)); + } else { + for f in [ + "/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf", + "/usr/share/fonts/noto/NotoSansArabic-Regular.ttf", + "/usr/share/fonts/google-noto/NotoSansArabic-Regular.ttf", + "/usr/local/share/fonts/noto/NotoSansArabic-Regular.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/dejavu/DejaVuSans.ttf", + "/usr/local/share/fonts/dejavu/DejaVuSans.ttf", + ] { + v.push((PathBuf::from(f), 0)); + } + } + v +} + +/// Fallback fonts manager for the egui context. +#[derive(Default)] +pub struct UiFonts { + installed: bool, + data: Option>, +} + +impl UiFonts { + /// Update fallback fonts according to active language and whether the preferences dialog is open. + pub fn update(&mut self, ctx: &egui::Context, language: &str, preferences_open: bool) { + let want_arabic = language == "ar" || preferences_open; + if !want_arabic || self.installed { + return; + } + let Some(data) = self.load_arabic() else { return }; + let mut defs = crate::theme::font_definitions(); + let name = "script-Arab".to_string(); + defs.font_data.insert(name.clone(), data); + defs.families.entry(FontFamily::Proportional).or_default().push(name.clone()); + defs.families.entry(FontFamily::Monospace).or_default().push(name); + ctx.set_fonts(defs); + self.installed = true; + } + + /// Whether an Arabic fallback font has been found and loaded. + pub fn covers_arabic(&self) -> bool { + self.data.is_some() + } + + fn load_arabic(&mut self) -> Option> { + if let Some(d) = &self.data { + return Some(d.clone()); + } + #[cfg(not(target_arch = "wasm32"))] + for (path, index) in system_files() { + let Ok(meta) = std::fs::metadata(&path) else { continue }; + if !meta.is_file() || meta.len() == 0 || meta.len() > (128 << 20) { + continue; + } + if let Ok(bytes) = std::fs::read(&path) { + let mut data = FontData::from_owned(bytes); + data.index = index; + let arc = Arc::new(data); + self.data = Some(arc.clone()); + log::info!("UI font fallback for Arabic: {}", path.display()); + return Some(arc); + } + } + log::warn!("no font found for Arabic text; system fonts may show boxes"); + None + } +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 68d287c6..a3b1358e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,12 +1,169 @@ -//! Interface text. English only for now; every user-facing string goes through [`tr`] (or is -//! marked with [`n_`] where it is stored), so translations can be added without touching callers. +//! UI text lookup. Keys are the English strings, so English needs no table and a missing +//! translation falls back to English. Every user-visible literal goes through [`tr`] (or [`trf`] +//! for text with `{name}` placeholders); each language is a static `(English, translation)` +//! table, indexed into a hash map the first time the language is used. `Prefs::language` picks it. -/// Mark a string for translation where it is stored; translate with [`tr`] where it is shown. +use std::collections::HashMap; +use std::fmt::Display; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicUsize, Ordering}; + +mod ar; + +pub struct Language { + /// BCP 47 code ("en", "ar"). + pub code: &'static str, + /// The language's own name, for the picker. + pub name: &'static str, + /// Its English name (the picker's fallback when no font can draw `name`). + pub english: &'static str, + /// `(English, translation)` pairs, in any order. + pub table: &'static [(&'static str, &'static str)], +} + +const COUNT: usize = 2; + +pub static LANGUAGES: [Language; COUNT] = [ + Language { code: "en", name: "English", english: "English", table: &[] }, + Language { code: "ar", name: "العربية", english: "Arabic", table: ar::TABLE }, +]; + +static MAPS: [OnceLock>; COUNT] = [const { OnceLock::new() }; COUNT]; +static CURRENT: AtomicUsize = AtomicUsize::new(0); + +/// Switch the UI language (unknown codes fall back to English). +pub fn set_language(code: &str) { + CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed); +} + +/// The current UI language. +pub fn current() -> &'static Language { + LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0]) +} + +/// Returns true if `code` is a right-to-left language (e.g. Arabic `"ar"`). +pub fn is_rtl_code(code: &str) -> bool { + craft_ui::direction::resolve(code, craft_ui::direction::Setting::Language) == craft_ui::direction::Direction::Rtl +} + +/// Returns true if the current UI language is right-to-left. +pub fn is_rtl() -> bool { + is_rtl_code(current().code) +} + +/// `text` in the current language (unchanged when it has no translation). +pub fn tr(text: &str) -> &str { + let i = CURRENT.load(Ordering::Relaxed); + let (Some(lang), Some(map)) = (LANGUAGES.get(i), MAPS.get(i)) else { return text }; + if lang.table.is_empty() { + return text; + } + map.get_or_init(|| lang.table.iter().copied().collect()).get(text).copied().unwrap_or(text) +} + +/// Marks a static string for translation where it is defined (gettext's `N_`); it is translated +/// with [`tr`] where it is shown. The key test collects both. pub const fn n_(text: &'static str) -> &'static str { text } -/// The text in the interface language. -pub fn tr(text: &str) -> &str { - text +/// `template` translated, with each `{name}` replaced by its value in `args`. +pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String { + let mut out = String::with_capacity(template.len() + 16); + let mut rest = tr(template); + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let after = &rest[open + 1..]; + match after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (close, v))) { + Some((close, v)) => { + use std::fmt::Write as _; + let _ = write!(out, "{v}"); + rest = &after[close + 1..]; + } + None => { + out.push('{'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +/// The supported language for a locale such as "ar-EG", "ar-SA" ("en" when none matches). +pub fn language_for_locale(locale: &str) -> &'static str { + let lang = locale.split(['-', '_', '.', '@']).next().unwrap_or("").to_ascii_lowercase(); + match lang.as_str() { + "ar" => "ar", + l => LANGUAGES.iter().find(|x| x.code == l).map_or("en", |x| x.code), + } +} + +/// The operating system's (or browser's) UI language, for the first run. +pub fn os_language() -> &'static str { + #[cfg(not(target_arch = "wasm32"))] + let locale = sys_locale::get_locale(); + #[cfg(target_arch = "wasm32")] + let locale = web_sys::window().and_then(|w| w.navigator().language()); + locale.map_or("en", |l| language_for_locale(&l)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn language_switching_and_arabic_translations_work() { + set_language("en"); + assert_eq!(current().code, "en"); + assert_eq!(tr("Properties"), "Properties"); + assert!(!is_rtl()); + + set_language("ar"); + assert_eq!(current().code, "ar"); + assert_eq!(tr("Properties"), "الخصائص"); + assert_eq!(tr("Preferences"), "التفضيلات"); + assert_eq!(tr("New graph"), "مخطط جديد"); + assert_eq!(tr("Export outputs"), "تصدير المخرجات"); + assert_eq!(tr("Welcome to MaterialCraft"), "مرحباً بك في MaterialCraft"); + assert!(is_rtl()); + + // Live formatting + let formatted = trf("Hello {name}", &[("name", &"World")]); + assert_eq!(formatted, "Hello World"); + + // Fallback for unknown text + assert_eq!(tr("Unknown untranslated string 1234"), "Unknown untranslated string 1234"); + + // Reset to English + set_language("en"); + } + + #[test] + fn locale_detection() { + assert_eq!(language_for_locale("ar"), "ar"); + assert_eq!(language_for_locale("ar-EG"), "ar"); + assert_eq!(language_for_locale("ar_SA.UTF-8"), "ar"); + assert_eq!(language_for_locale("en-US"), "en"); + assert_eq!(language_for_locale("fr-FR"), "en"); + } + + #[test] + fn arabic_table_has_no_duplicate_keys() { + let mut seen = std::collections::HashSet::new(); + for (k, _) in ar::TABLE { + assert!(seen.insert(*k), "duplicate key in ar::TABLE: {k:?}"); + } + } + + #[test] + fn placeholders_match_between_key_and_arabic_translation() { + for (k, v) in ar::TABLE { + let mut kp: Vec<&str> = k.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect(); + let mut vp: Vec<&str> = v.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect(); + kp.sort(); + vp.sort(); + assert_eq!(kp, vp, "mismatched placeholders in {k:?} vs {v:?}"); + } + } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs new file mode 100644 index 00000000..f8e392ed --- /dev/null +++ b/crates/ui-egui/src/i18n/ar.rs @@ -0,0 +1,367 @@ +//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. + +pub const TABLE: &[(&str, &str)] = &[ + ("$pos", "$pos"), + ("$size", "$size"), + ("(checker)", "(رقعة شطرنج)"), + ("1024 px", "1024 بكسل"), + ("16 bits", "16 بت"), + ("16 bits per channel", "16 بت لكل قناة"), + ("16 bits per channel float (HDR)", "16 بت لكل قناة فاصلة عائمة (HDR)"), + ("2048 px", "2048 بكسل"), + ("256 px", "256 بكسل"), + ("2D View", "عرض ثنائي الأبعاد"), + ("32 bits float", "32 بت فاصلة عائمة"), + ("32 bits per channel float (HDR)", "32 بت لكل قناة فاصلة عائمة (HDR)"), + ("3D pan limit (mesh radii)", "حد التحريك ثلاثي الأبعاد (أنصاف أقطار المجسم)"), + ("3D pan speed", "سرعة التحريك ثلاثي الأبعاد"), + ("3D View", "عرض ثلاثي الأبعاد"), + ("512 px", "512 بكسل"), + ("8 bits", "8 بت"), + ("8 bits per channel", "8 بت لكل قناة"), + ("About MaterialCraft", "حول MaterialCraft"), + ("About MaterialCraft...", "حول MaterialCraft..."), + ("Absolute", "مطلق"), + ("Accent color", "لون التمييز"), + ("Actual pixels", "البكسلات الفعلية"), + ("Add", "إضافة"), + ("Add Comment", "إضافة تعليق"), + ("Add comment", "إضافة تعليق"), + ("Add Dot node", "إضافة عقدة نقطية"), + ("Add Frame", "إضافة إطار"), + ("Add frame around selection", "إضافة إطار حول التحديد"), + ("Add frame around the selection", "إضافة إطار حول التحديد"), + ("Add Navigation pin", "إضافة دبوس تنقل"), + ("Add navigation pin", "إضافة دبوس تنقل"), + ("Add node", "إضافة عقدة"), + ("Add Output nodes with usages (base color, normal, ...) to see the material", "أضف عُقد مخرجات مع استخداماتها (اللون الأساسي، الناظم، ...) لمعاينة المادة"), + ("Align centers horizontally", "محاذاة المراكز أفقياً"), + ("Align centers vertically", "محاذاة المراكز رأسياً"), + ("Align left", "محاذاة لليسار"), + ("Align top", "محاذاة للأعلى"), + ("All nodes", "كل العقد"), + ("Amber", "كهرماني"), + ("An open-source Crafting App by the ArtCraft team and community.", "تطبيق تصميم مفتوح المصدر من قِبل فريق ومجتمع ArtCraft."), + ("And", "و (And)"), + ("Apply", "تطبيق"), + ("Arc tangent 2", "ظل زاوية قوسي 2"), + ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), + ("As JSON", "بصيغة JSON"), + ("Atomic nodes", "عقد أولية"), + ("Attributes", "السمات"), + ("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"), + ("Bad function", "دالة غير صالحة"), + ("Base parameters", "المعلمات الأساسية"), + ("Bind to input", "ربط بالمدخل"), + ("Bit depth", "عمق البت"), + ("Blends", "عمليات الدمج"), + ("Blue", "أزرق"), + ("Boolean", "منطقي"), + ("Brick wall", "جدار طوب"), + ("Brightness", "السطوع"), + ("Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.", "أنشئ مواد قابلة للتكرار من التشويش والأنماط والمرشحات، وعاينها مباشرة ثنائية وثلاثية الأبعاد، وصدّر الخرائط لأي محرك."), + ("Cache", "الذاكرة المؤقتة"), + ("Camera", "الكاميرا"), + ("Cancel", "إلغاء"), + ("Cast", "تحويل النوع"), + ("Ceil", "الحد الأعلى (Ceil)"), + ("Choose a folder to export to", "اختر مجلداً للتصدير إليه"), + ("Clamp", "تقييد النطاق (Clamp)"), + ("Clear cache", "مسح الذاكرة المؤقتة"), + ("Clear recent packages", "مسح الحزم الأخيرة"), + ("Close all", "إغلاق الكل"), + ("Community (Discord)", "المجتمع (Discord)"), + ("Comparison", "مقارنة"), + ("Compute graph", "حساب المخطط"), + ("Computing...", "جاري الحساب..."), + ("Console", "وحدة التحكم"), + ("Constant", "ثابت"), + ("Control", "تحكم"), + ("Copper", "نحاسي"), + ("Copy", "نسخ"), + ("Copy selection", "نسخ التحديد"), + ("Coral", "مرجاني"), + ("Cosine", "جيب التمام (Cosine)"), + ("Couldn't export", "تعذر التصدير"), + ("Couldn't import", "تعذر الاستيراد"), + ("Couldn't load", "تعذر التحميل"), + ("Couldn't open", "تعذر الفتح"), + ("Couldn't save", "تعذر الحفظ"), + ("Create", "إنشاء"), + ("Create graph from selection", "إنشاء مخطط من التحديد"), + ("Create graph in", "إنشاء مخطط في"), + ("Cube", "مكعب"), + ("Cut", "قص"), + ("Cyan", "سماوي"), + ("Cylinder", "أسطوانة"), + ("Dark", "داكن"), + ("Default", "افتراضي"), + ("Delete", "حذف"), + ("Delete and relink", "حذف وإعادة ربط"), + ("Delete input", "حذف المدخل"), + ("Delete preset", "حذف الإعداد المسبق"), + ("Delete selection", "حذف التحديد"), + ("Disable selection", "تعطيل التحديد"), + ("Display", "عرض"), + ("Distribute horizontally", "توزيع أفقي"), + ("Distribute vertically", "توزيع رأسي"), + ("Division", "قسمة"), + ("Documentation", "التوثيق"), + ("Documentation...", "التوثيق..."), + ("Dot Product", "الجداء السلمي (Dot Product)"), + ("Double-click a node to show it here", "انقر نقراً مزدوجاً على عقدة لعرضها هنا"), + ("Downloaded", "تم التنزيل"), + ("Duplicate", "تكرار"), + ("Duplicate selection", "تكرار التحديد"), + ("Duplicate selection without link", "تكرار التحديد بدون ربط"), + ("Edit", "تحرير"), + ("Edit function graph...", "تحرير مخطط الدوال..."), + ("Empty", "فارغ"), + ("Empty package", "حزمة فارغة"), + ("Engine", "المحرك"), + ("Environment", "البيئة"), + ("Environment background", "خلفية البيئة"), + ("Equal", "مساوٍ"), + ("Exit", "خروج"), + ("Explorer", "المستكشف"), + ("Exponential", "دالة أسية (Exp)"), + ("Export", "تصدير"), + ("Export material...", "تصدير المادة..."), + ("Export outputs", "تصدير المخرجات"), + ("Export outputs...", "تصدير المخرجات..."), + ("Export outputs... (Ctrl+Shift+E)", "تصدير المخرجات... (Ctrl+Shift+E)"), + ("Exported", "تم التصدير"), + ("Expose as graph input", "كشف كمدخل للمخطط"), + ("Exposure", "التعريض"), + ("File", "ملف"), + ("File names", "أسماء الملفات"), + ("files", "ملفات"), + ("Filters", "مرشحات"), + ("Fit", "ملاءمة"), + ("Float", "فاصلة عائمة (Float)"), + ("Float2", "فاصلة عائمة ثنائية (Float2)"), + ("Float3", "فاصلة عائمة ثلاثية (Float3)"), + ("Float4", "فاصلة عائمة رباعية (Float4)"), + ("Flood fill", "تعبئة متصلة (Flood fill)"), + ("Floor", "الحد الأدنى (Floor)"), + ("Folder", "المجلد"), + ("Format", "الصيغة"), + ("Fractional part", "الجزء الكسري"), + ("Frame all", "تأطير الكل"), + ("Frame all (F)", "تأطير الكل (F)"), + ("Frame all / the selection", "تأطير الكل / التحديد"), + ("Front", "أمامي"), + ("Full size", "الحجم الكامل"), + ("full size", "الحجم الكامل"), + ("Function", "دالة"), + ("function", "دالة"), + ("Function graph", "مخطط الدوال"), + ("function nodes", "عقد الدوال"), + ("Function of", "دالة لـ"), + ("Get variable", "جلب متغير"), + ("Go to pin", "الانتقال إلى الدبوس"), + ("Graph", "مخطط"), + ("Graph instance", "نسخة المخطط"), + ("Graph items", "عناصر المخطط"), + ("Graph name", "اسم المخطط"), + ("Graph's format", "صيغة المخطط"), + ("Graph...", "مخطط..."), + ("Graphs in this package", "المخططات في هذه الحزمة"), + ("Greater", "أكبر من"), + ("Greater or equal", "أكبر من أو يساوي"), + ("Green", "أخضر"), + ("Height (parallax) depth", "عمق الارتفاع (اختلاف المنظر)"), + ("Help", "مساعدة"), + ("Histogram", "المخطط البياني (Histogram)"), + ("History", "السجل"), + ("Home", "الرئيسية"), + ("Home screen...", "الشاشة الرئيسية..."), + ("Icons", "أيقونات"), + ("If...Else", "إذا...وإلا (If...Else)"), + ("Import bitmap...", "استيراد صورة نقطية..."), + ("Imported", "تم الاستيراد"), + ("Input parameters", "معلمات المدخلات"), + ("Input previews", "معاينات المدخلات"), + ("Instance parameters", "معلمات النسخة"), + ("Integer", "عدد صحيح"), + ("Interface scale", "حجم واجهة المستخدم"), + ("Join the community (Discord)...", "انضم إلى المجتمع (Discord)..."), + ("Key at", "مفتاح عند"), + ("Language", "اللغة"), + ("Last compute", "آخر حساب"), + ("Lava rock", "صخور بركانية"), + ("Length", "الطول"), + ("Library", "المكتبة"), + ("Light", "فاتح"), + ("Linear interpolation", "استيفاء خطي (Lerp)"), + ("List", "قائمة"), + ("Load mesh...", "تحميل مجسم..."), + ("Logarithm", "لوغاريتم"), + ("Logical", "منطقي"), + ("Lower", "أصغر من"), + ("Lower or equal", "أصغر من أو يساوي"), + ("Mat ball", "كرة المادة"), + ("Material filters", "مرشحات المواد"), + ("Maximum", "الحد الأقصى"), + ("Medium dark", "داكن متوسط"), + ("Medium light", "فاتح متوسط"), + ("Minimum", "الحد الأدنى"), + ("Modulo", "باقي القسمة (Modulo)"), + ("Mossy ground", "أرضية مغطاة بالطحالب"), + ("Multiplication", "ضرب"), + ("Name", "الاسم"), + ("Negation", "نفي / سالب"), + ("New", "جديد"), + ("New graph", "مخطط جديد"), + ("New graph...", "مخطط جديد..."), + ("New graph... (Ctrl+N)", "مخطط جديد... (Ctrl+N)"), + ("New random seed", "بذرة عشوائية جديدة"), + ("Night", "ليل"), + ("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"), + ("No graph is open", "لا يوجد مخطط مفتوح"), + ("No matching node", "لا توجد عقدة مطابقة"), + ("No presets yet", "لا توجد إعدادات مسبقة بعد"), + ("No recent packages", "لا توجد حزم حديثة"), + ("Node search (over the graph)", "البحث عن عقدة (فوق المخطط)"), + ("Node-based procedural materials, built in pure Rust.", "مواد إجرائية قائمة على العقد، مبنية بلغة Rust النقية."), + ("Noises", "تشويشات"), + ("None", "بلا"), + ("Normal", "الناظم (Normal)"), + ("Normalize", "تسوية (Normalize)"), + ("Not", "ليس (Not)"), + ("Not equal", "غير مساوٍ"), + ("Nothing matches", "لا توجد تطابقات"), + ("Open", "فتح"), + ("Open graph", "فتح المخطط"), + ("Open package...", "فتح حزمة..."), + ("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"), + ("Open...", "فتح..."), + ("Opened", "تم الفتح"), + ("Operator", "معامل حسابي"), + ("Ops", "عمليات"), + ("Or", "أو (Or)"), + ("Output format", "صيغة المخرج"), + ("Output size", "حجم المخرج"), + ("Outputs", "المخرجات"), + ("Overcast", "غائم"), + ("Painted metal plates", "صفائح معدنية مطلية"), + ("Pan the camera", "تحريك الكاميرا"), + ("Pan the graph", "تحريك المخطط"), + ("Parent size:", "حجم العنصر الأصل:"), + ("Paste", "لصق"), + ("Patterns", "أنماط"), + ("PBR material (outputs only)", "مادة PBR (مخرجات فقط)"), + ("Perlin noise", "تشويش بيرلين (Perlin noise)"), + ("Pick an image file (a mesh map baked in TextureCraft)", "اختر ملف صورة (خريطة مجسم مخبوزة في TextureCraft)"), + ("Pink", "وردي"), + ("Plane", "مستوى"), + ("Polished marble", "رخام مصقول"), + ("Power", "قوة / أس (Power)"), + ("Preferences", "التفضيلات"), + ("Preferences...", "التفضيلات..."), + ("Preset name", "اسم الإعداد المسبق"), + ("Presets", "الإعدادات المسبقة"), + ("Preview", "معاينة"), + ("Preview size", "حجم المعاينة"), + ("Preview size while editing", "حجم المعاينة أثناء التحرير"), + ("Properties", "الخصائص"), + ("Random", "عشوائي"), + ("Random seed", "بذرة عشوائية"), + ("Recent", "الأخيرة"), + ("Recent packages", "الحزم الأخيرة"), + ("Redo", "إعادة"), + ("Redo (Ctrl+Y)", "إعادة (Ctrl+Y)"), + ("Relative to input", "نسبي إلى المدخل"), + ("Relative to parent", "نسبي إلى الأصل"), + ("Reload resources", "إعادة تحميل الموارد"), + ("Remove function", "إزالة الدالة"), + ("Render time", "وقت التصيير"), + ("Renderer", "المصير"), + ("Report a bug...", "الإبلاغ عن خطأ..."), + ("Reset layout", "إعادة ضبط التخطيط"), + ("Reset parameters", "إعادة ضبط المعلمات"), + ("Reset scene", "إعادة ضبط المشهد"), + ("Reset to default", "إعادة ضبط للافتراضي"), + ("Resources", "الموارد"), + ("Revert", "استرجاع"), + ("Right-click a node parameter > Expose as graph input", "انقر بزر الفأرة الأيمن على معلمة العقدة > كشف كمدخل للمخطط"), + ("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.", "انقر بزر الفأرة الأيمن أو مفتاح المسافة لإضافة عمليات؛ اسحب من نقطة المخرج إلى المدخل؛ العقدة المميزة بنجمة هي النتيجة."), + ("Rotation", "التدوير"), + ("Rounded cube", "مكعب مدور الحواف"), + ("Rusty metal", "معدن صدئ"), + ("Sample Color", "عينة لونية"), + ("Sample Gray", "عينة تدرج رمادي"), + ("Samplers", "عينات"), + ("Samples", "عينات"), + ("Save", "حفظ"), + ("Save (Ctrl+S)", "حفظ (Ctrl+S)"), + ("Save as...", "حفظ باسم..."), + ("Save image...", "حفظ الصورة..."), + ("Save package", "حفظ الحزمة"), + ("Save preset", "حفظ الإعداد المسبق"), + ("Saved", "تم الحفظ"), + ("Scene", "المشهد"), + ("Search", "بحث"), + ("Search nodes...", "البحث في العقد..."), + ("Select all", "تحديد الكل"), + ("Select downstream nodes", "تحديد العقد اللاحقة"), + ("Select upstream nodes", "تحديد العقد السابقة"), + ("Send to TextureCraft", "إرسال إلى TextureCraft"), + ("Sent to TextureCraft: find it on the shelf under My smart materials", "أُرسل إلى TextureCraft: ستجده على الرف ضمن موادي الذكية"), + ("Set function...", "تعيين دالة..."), + ("Shortcuts", "الاختصارات"), + ("Shortcuts list...", "قائمة الاختصارات..."), + ("Show at startup", "إظهار عند بدء التشغيل"), + ("Show in the 2D view", "إظهار في العرض ثنائي الأبعاد"), + ("Show node thumbnails", "إظهار الصور المصغرة للعقد"), + ("Showing", "عرض"), + ("Side", "جانبي"), + ("Sine", "جيب الزاوية (Sine)"), + ("Size", "الحجم"), + ("Specific parameters", "المعلمات المخصصة"), + ("Sphere", "كرة"), + ("Square root", "جذر تربيعي"), + ("Stone tiles", "بلاط حجري"), + ("Studio", "استوديو"), + ("Subtraction", "طرح"), + ("Sunset", "غروب"), + ("SVG", "رسوم متجهة (SVG)"), + ("Swizzle", "إعادة ترتيب القنوات (Swizzle)"), + ("Tangent", "ظل الزاوية (Tangent)"), + ("Templates", "القوالب"), + ("Text", "نص"), + ("Texture generators", "مولدات الخامات"), + ("The instanced graph is missing", "المخطط المنسوخ مفقود"), + ("This graph exposes no inputs", "هذا المخطط لا يكشف أي مدخلات"), + ("This package", "هذه الحزمة"), + ("threads", "خيوط معالجة"), + ("Tile 3x3", "تكرار 3x3"), + ("Tiling", "التكرار"), + ("Tiling (H and V)", "التكرار (أفقياً ورأسياً)"), + ("To Float", "إلى فاصلة عائمة"), + ("To Integer", "إلى عدد صحيح"), + ("Tools", "أدوات"), + ("Top", "علوي"), + ("Torus", "شكل حلقي (Torus)"), + ("Transforms", "التحويلات"), + ("Turn the environment", "تدوير البيئة"), + ("Unbind", "فك الارتباط"), + ("Undo", "تراجع"), + ("Undo (Ctrl+Z)", "تراجع (Ctrl+Z)"), + ("Use as result", "استخدام كنتيجة"), + ("Variables", "متغيرات"), + ("Vector", "متجه"), + ("Vector Float2", "متجه ثنائي (Float2)"), + ("Vector Float3", "متجه ثلاثي (Float3)"), + ("Vector Float4", "متجه رباعي (Float4)"), + ("Version", "الإصدار"), + ("View in 2D view", "عرض في العرض ثنائي الأبعاد"), + ("Violet", "بنفسجي"), + ("Weathering", "التجوية والتقادم"), + ("Welcome to MaterialCraft", "مرحباً بك في MaterialCraft"), + ("Wicker weave", "نسيج قش"), + ("Windows", "نوافذ"), + ("Wood planks", "ألواح خشبية"), + ("Woven fabric", "قماش منسوج"), + ("Zoom the graph and the views", "تقريب المخطط وطرق العرض"), +]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5997865a..a8c98426 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -11,6 +11,7 @@ pub mod control; pub mod cook; pub mod docking; pub mod explorer; +pub mod fonts; pub mod function_editor; pub mod graph_view; pub mod i18n; @@ -69,6 +70,8 @@ pub struct MaterialCraftApp { #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, styled: Option<(theme::Brightness, theme::Accent)>, + /// Fallback fonts for Arabic. + pub fonts: fonts::UiFonts, /// The icon font is installed (it takes effect on the frame after `set_fonts`). fonts_ready: bool, } @@ -78,6 +81,7 @@ impl MaterialCraftApp { let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_default(); theme::install(&cc.egui_ctx); let mut app = MaterialCraftApp::headless(session, ui); + i18n::set_language(&app.ui.prefs.language); app.fonts_ready = true; app.ui.windows.home = app.ui.prefs.show_home; app @@ -108,8 +112,10 @@ impl MaterialCraftApp { last_time: 0.0, next_autosave, styled: None, + fonts: fonts::UiFonts::default(), fonts_ready: false, }; + i18n::set_language(&app.ui.prefs.language); app.apply_prefs(); app } @@ -205,6 +211,8 @@ impl MaterialCraftApp { ctx.request_repaint(); return; } + i18n::set_language(&self.ui.prefs.language); + self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences); let now = ctx.input(|i| i.time); let dt = (now - self.last_time) as f32; if dt > 0.0 { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b6d2a32..1c9fc427 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -11,6 +11,8 @@ use crate::theme::{Accent, Brightness}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Prefs { + /// UI language code (`i18n::LANGUAGES`). + pub language: String, pub brightness: Brightness, pub accent: Accent, pub ui_scale: f32, @@ -31,6 +33,7 @@ pub struct Prefs { impl Default for Prefs { fn default() -> Self { Prefs { + language: crate::i18n::os_language().into(), brightness: Brightness::default(), accent: Accent::default(), ui_scale: 1.0, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f308f048..b0a5df85 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -271,8 +271,17 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; - modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 300.0), |ui| { + modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 340.0), |ui| { let p = &mut app.ui.prefs; + let current_lang = crate::i18n::current(); + crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| { + for l in &crate::i18n::LANGUAGES { + if ui.selectable_label(p.language == l.code, l.name).clicked() { + p.language = l.code.to_owned(); + crate::i18n::set_language(&p.language); + } + } + }); crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| { for b in Brightness::ALL { ui.selectable_value(&mut p.brightness, b, tr(b.label())); diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 0fc1308a..fc92f435 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -8,6 +8,7 @@ so catalogs can be added without touching callers. Today only English ships. | Language | Code | Status | Notes | |---|---|---|---| | English | `en` | Complete | Source language | +| Arabic | `ar` | Complete | Full UI translation table (`crates/ui-egui/src/i18n/ar.rs`), system font fallbacks (Segoe UI / SF Arabic / Noto Sans Arabic), live language picker in Preferences | | French, German, Spanish, Portuguese (Brazil), Italian | `fr`, `de`, `es`, `pt-br`, `it` | Not started | Planned with the shared craft-i18n catalogs | | Japanese, Chinese (Simplified), Korean | `ja`, `zh-hans`, `ko` | Not started | Needs the craft-fonts CJK faces (`CRAFT_FONTS_DIR`), as in TextureCraft | @@ -15,4 +16,5 @@ so catalogs can be added without touching callers. Today only English ships. | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Add complete Arabic (`ar`) UI localization and font fallbacks | | 2026-11-02 | major | First version | From 73378cbfd8328ad58f5505f9395ead5756b04afd Mon Sep 17 00:00:00 2001 From: Belligerently Date: Tue, 3 Nov 2026 17:16:16 -0500 Subject: [PATCH 16/91] Keep typed numeric parameter values across frames --- crates/ui-egui/src/properties.rs | 4 +- crates/ui-egui/src/widgets.rs | 29 ++++- crates/ui-egui/tests/numeric_input.rs | 172 ++++++++++++++++++++++++++ 3 files changed, 198 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/tests/numeric_input.rs diff --git a/crates/ui-egui/src/properties.rs b/crates/ui-egui/src/properties.rs index aabd042a..4978b7b5 100644 --- a/crates/ui-egui/src/properties.rs +++ b/crates/ui-egui/src/properties.rs @@ -43,10 +43,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.set_width(ui.available_width()); let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned()); - match node { + ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { Some(n) => node_props(app, ui, &n), None => graph_props(app, ui), - } + }); }); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4b2d5dbd..1f86f196 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -20,26 +20,45 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { let tk = Tokens::get(ui.ctx()); let (lo, hi) = (*range.start(), *range.end()); let w = ui.available_width(); + let mut edited = false; ui.horizontal(|ui| { ui.label(RichText::new(label).color(tk.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut text = format!("{:.*}", decimals, value); - let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE)); + let id = ui.next_auto_id(); + // Keep incomplete input (such as "-") across frames while editing. + let draft = id.with("numeric-draft"); + let editing = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id)); + let mut text = editing.then(|| ui.data(|d| d.get_temp::(draft))).flatten().unwrap_or_else(|| format!("{:.*}", decimals, value)); + let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE)); name(&r, egui::Role::TextInput, label); - if r.lost_focus() + if (r.changed() || r.lost_focus()) + && !ui.input(|i| i.key_pressed(egui::Key::Escape)) && let Ok(v) = text.trim().parse::() && v.is_finite() { - *value = v.clamp(lo, hi); + let v = v.clamp(lo, hi); + edited = v != *value; + *value = v; } + let focused = r.has_focus(); + ui.data_mut(|d| { + if focused { + d.insert_temp(draft, text); + } else { + d.remove::(draft); + } + }); }); }); let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); + if edited { + resp.mark_changed(); + } let (v, l) = (*value as f64, label.to_string()); resp.widget_info(move || egui::WidgetInfo::slider(true, v, l.clone())); if (resp.dragged() || resp.clicked()) diff --git a/crates/ui-egui/tests/numeric_input.rs b/crates/ui-egui/tests/numeric_input.rs new file mode 100644 index 00000000..ec027f90 --- /dev/null +++ b/crates/ui-egui/tests/numeric_input.rs @@ -0,0 +1,172 @@ +//! Exact numeric edits must survive intervening frames and reach engine parameters. +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_engine::core::{NodeId, Value}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.run("file.new", json!({"template":"empty"})).unwrap(); + let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap()); + app.session.reset_history(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + (h, id) +} +fn focus_x(h: &mut Harness<'static, MaterialCraftApp>, index: usize) { + h.get_all(By::new().role(egui::accesskit::Role::TextInput).label("X")).nth(index).unwrap().click(); + h.step(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); +} +fn type_text(h: &mut Harness<'static, MaterialCraftApp>, text: &str) { + h.event(Event::Text(text.into())); + h.step(); + h.run_steps(4); +} +fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32; 2] { + match h.state().session.graph().unwrap().node(id).unwrap().params.get(param) { + Some(Value::Float2(v)) => *v, + None => match materialcraft_engine::nodes::find("transformation").unwrap().params.iter().find(|p| p.id == param).unwrap().default { + Value::Float2(v) => v, + _ => panic!("not a pair"), + }, + other => panic!("unexpected value {other:?}"), + } +} +#[test] +fn scale_x_commits_on_enter_and_focus_loss_with_undo() { + for enter in [true, false] { + let (mut h, id) = harness(false); + focus_x(&mut h, 1); + type_text(&mut h, "4"); + if enter { + h.key_press(Key::Enter); + h.step(); + } else { + h.get_by_label("Node label").click(); + h.step(); + } + h.run_steps(5); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0], "Scale X did not persist (Enter={enter})"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + } +} +#[test] +fn a_negative_decimal_can_be_typed_across_frames() { + let (mut h, id) = harness(false); + focus_x(&mut h, 0); + for part in ["-", ".", "5"] { + type_text(&mut h, part); + } + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [-0.5, 0.0]); + assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]); +} +#[test] +fn clicking_the_canvas_and_switching_nodes_keep_the_right_values() { + let (mut h, id) = harness(false); + focus_x(&mut h, 1); + type_text(&mut h, "4"); + let pos = h.state().graph.view.left_top() + vec2(20.0, 20.0); + h.event(Event::PointerMoved(pos)); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + assert!(h.state().session.selection.is_empty()); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + h.state_mut().run("graph.select", json!({"ids": [id.0]})).unwrap(); + h.run_steps(4); + focus_x(&mut h, 1); + type_text(&mut h, "5"); + let other = NodeId(h.state_mut().run("graph.node.add", json!({"def":"transformation","at":[300,0]})).unwrap()["id"].as_u64().unwrap()); + h.run_steps(4); + h.key_press(Key::Enter); + h.step(); + assert_eq!(pair(&h, id, "scale"), [5.0, 1.0]); + assert_eq!(pair(&h, other, "scale"), [1.0, 1.0], "an edit leaked into the newly selected node"); +} + +#[test] +fn invalid_input_is_ignored_and_values_are_clamped() { + let (mut h, id) = harness(false); + focus_x(&mut h, 0); + type_text(&mut h, "NaN"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [0.0, 0.0]); + focus_x(&mut h, 0); + type_text(&mut h, "123"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]); + focus_x(&mut h, 0); + type_text(&mut h, "-"); + h.key_press(Key::Escape); + h.step(); + h.run_steps(4); + assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]); +} + +#[test] +fn integer_input_and_slider_track_both_update_the_node() { + let (mut h, id) = harness(false); + let input = By::new().role(egui::accesskit::Role::TextInput).label("Random seed"); + h.get(input).click(); + h.step(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); + type_text(&mut h, "42"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(4); + assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 42); + let pos = h.get(By::new().role(egui::accesskit::Role::Slider).label("Random seed")).rect().center(); + h.event(Event::PointerMoved(pos)); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 500); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn exact_scale_screenshot() { + let (mut h, id) = harness(true); + focus_x(&mut h, 1); + type_text(&mut h, "4"); + h.key_press(Key::Enter); + h.step(); + h.run_steps(8); + assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("scale-x-4.png")).unwrap(); +} From ef8ab335c2d5eb953a8d13b3eb911c00f1e50207 Mon Sep 17 00:00:00 2001 From: A-Gift-Of-Flame <76142225+A-Gift-Of-Flame@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:55:13 +0100 Subject: [PATCH 17/91] feat(automation): material_export MCP tool for portable .mcmat Sandboxed agents could not hand a material to TextureCraft: the workspace sandbox refuses `file.*` commands and there was no MCP tool for `.mcmat`. Add `material_export {path, graph?, size?, values?}` (RPC method `material.export`). It cooks the graph through the same engine code as `file.exportMaterial` and writes the `.mcmat` only through AuthorizedWorkspace (cap-std, `--write-root`): no write root, a malformed path or an escape is an error, the parent folder must exist, and the file is capped at what `package_open` may read back. Bridge mode refuses it like the other path tools. The engine gets a shared `material_request` helper so the command and the tool parse graph/size/values identically. Tests: file written and readable, bad requests, denied without a write root (Denied and read-only workspace), path escapes (`..`, absolute, backslash, drive, symlink) and the MCP tool end to end. docs/control-protocol.md lists the method and tool. Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/headless.rs | 23 ++++++++- crates/automation/src/rpc.rs | 82 +++++++++++++++++++++++++++++- crates/automation/src/server.rs | 46 ++++++++++++++++- crates/automation/src/workspace.rs | 7 +++ crates/engine/src/material_cmds.rs | 12 ++++- docs/control-protocol.md | 10 ++-- 6 files changed, 170 insertions(+), 10 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 3443f3f9..137c0e5c 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -4,7 +4,8 @@ use std::path::Path; use materialcraft_engine::core::NodeId; -use materialcraft_engine::{Session, commands, file_cmds, inspect}; +use materialcraft_engine::formats::material::MATERIAL_EXT; +use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds}; use materialcraft_render::{Lighting, Maps, Scene, Settings}; use serde_json::{Value, json}; @@ -182,6 +183,26 @@ impl Headless { Ok(json!({"files": written})) } + /// Cook a graph and write it as a portable `.mcmat` material (`.mcmat` appended when + /// missing) to `path`: `{path, graph?, size?, values?}`, the workspace-scoped + /// `file.exportMaterial`. The file is capped at what `package_open` may read back. + pub fn export_material(&mut self, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?; + let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") }; + match &self.fs { + Filesystem::Denied => return Err(bad("file access is not granted: start the server with --write-root ")), + Filesystem::Workspace(w) => w.check_write(&path)?, + Filesystem::TrustedLocal => {} + } + let (gi, options) = material_cmds::material_request(&self.session, "material.export", p)?; + let bytes = material_cmds::material_bytes(&self.session, gi, &options)?; + if bytes.len() as u64 > MAX_READ_BYTES { + return Err(bad(format!("the material is {} bytes (limit {MAX_READ_BYTES}); export a smaller `size`", bytes.len()))); + } + self.write(&path, &bytes)?; + Ok(json!({"path": path, "bytes": bytes.len()})) + } + /// Render the 3D view or a node's 2D output as PNG. pub fn render_png(&mut self, o: &RenderOptions) -> Result { let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE }; diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 0c156b78..4338f341 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -4,8 +4,9 @@ //! //! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`, //! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`, -//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}` -//! (workspace-scoped versions of the engine commands), `render {view?, width?, height?, yaw?, +//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`, +//! `material.export {path, graph?, size?, values?}` (workspace-scoped versions of the engine +//! commands; the last writes a portable `.mcmat`), `render {view?, width?, height?, yaw?, //! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`) //! and `methods`. @@ -32,6 +33,7 @@ pub const METHODS: &[&str] = &[ "package.save", "bitmap.import", "outputs.export", + "material.export", "render", ]; @@ -84,6 +86,7 @@ impl Headless { "package.save" => self.save(str_of(p, "path")), "bitmap.import" => self.import_bitmap(required(p, "path")?, str_of(p, "name")), "outputs.export" => self.export(p), + "material.export" => self.export_material(p), "render" => { let o = RenderOptions { view: str_of(p, "view").map(str::to_string), @@ -253,6 +256,81 @@ mod tests { assert_eq!(r[6]["result"]["failed"]["index"], 1); } + /// A workspace session rooted at a fresh `inside` folder, with an `outside` sibling. + fn workspace_session(name: &str, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex) { + let base = std::env::temp_dir().join(format!("mc-rpc-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (inside, outside) = (base.join("inside"), base.join("outside")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let ws = crate::AuthorizedWorkspace::new(Some(&inside), write.then_some(inside.as_path())).unwrap(); + let h = Mutex::new(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws))); + (inside, outside, h) + } + + fn call(h: &Mutex, method: &str, params: Value) -> Result { + h.lock().unwrap().handle(method, ¶ms).map_err(|e| e.to_string()) + } + + #[test] + fn material_export_writes_a_portable_material_below_the_write_root() { + let (inside, _, h) = workspace_session("mat-ok", true); + std::fs::create_dir(inside.join("out")).unwrap(); + let r = call(&h, "material.export", json!({"path": "out/brick", "size": 32})).unwrap(); + assert_eq!(r["path"], "out/brick.mcmat"); + let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap(); + assert_eq!(r["bytes"], bytes.len()); + let (m, source) = materialcraft_engine::formats::material::read_material(&bytes).unwrap(); + assert_eq!(m.size, [32, 32]); + assert!(m.maps.iter().any(|e| e.usage == "baseColor")); + assert!(!source.is_empty()); + assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind"); + // An explicit extension is kept (case-insensitively) and the file can be opened again. + let r = call(&h, "material.export", json!({"path": "again.MCMAT", "size": 16})).unwrap(); + assert_eq!(r["path"], "again.MCMAT"); + assert!(call(&h, "package.open", json!({"path": "again.MCMAT"})).is_ok()); + } + + #[test] + fn material_export_reports_bad_requests() { + let (inside, _, h) = workspace_session("mat-bad", true); + for bad in [json!({}), json!({"path": "m", "graph": 99}), json!({"path": "m", "values": {"no_such_input": 1}})] { + assert!(call(&h, "material.export", bad.clone()).is_err(), "{bad}"); + } + assert!(call(&h, "material.export", json!({"path": "missing/dir/m"})).is_err(), "parent must exist"); + assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0, "failed exports leave nothing behind"); + } + + #[test] + fn material_export_needs_a_write_root() { + let denied = session(); + let e = call(&denied, "material.export", json!({"path": "m.mcmat"})).unwrap_err(); + assert!(e.contains("not granted"), "{e}"); + let (inside, _, read_only) = workspace_session("mat-readonly", false); + let e = call(&read_only, "material.export", json!({"path": "m.mcmat"})).unwrap_err(); + assert!(e.contains("no write root"), "{e}"); + assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0); + } + + #[test] + fn material_export_cannot_escape_the_write_root() { + let (inside, outside, h) = workspace_session("mat-escape", true); + let abs = outside.join("abs.mcmat").display().to_string(); + for p in ["../outside/m.mcmat", "a/../../outside/m.mcmat", "/tmp/m.mcmat", "a\\b.mcmat", "C:/m.mcmat", "./m.mcmat", abs.as_str()] { + let e = call(&h, "material.export", json!({"path": p, "size": 16})); + assert!(e.is_err(), "accepted {p:?}"); + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(&outside, inside.join("link")).unwrap(); + assert!(call(&h, "material.export", json!({"path": "link/m.mcmat", "size": 16})).is_err()); + } + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "nothing written outside the root"); + // The generic command path stays closed too: host paths are still refused. + let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err(); + assert!(e.contains("disabled for automation"), "{e}"); + } + #[test] fn tcp_requires_the_token() { use std::io::{BufRead, BufReader}; diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index e23f3d18..12abc3cb 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -159,6 +159,22 @@ pub struct ExportParams { pub graph: Option, } +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct MaterialExportParams { + /// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The + /// parent folder must exist. + pub path: String, + /// Graph index (default: the open graph). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub graph: Option, + /// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + /// Exposed input values to cook with and embed, by input id (see `session_inspect`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub values: Option, +} + #[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] pub struct RenderParams { /// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output). @@ -305,7 +321,7 @@ impl MaterialcraftMcp { b.call(method, p).await } "package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await, - "package.save" | "package.open" | "bitmap.import" | "outputs.export" | "command.batch" | "render" => { + "package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => { Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)"))) } _ => b.call(method, p).await, @@ -426,6 +442,13 @@ impl MaterialcraftMcp { to_result(self.call("outputs.export", params(&p)).await) } + #[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \ + source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \ + Returns {path, bytes}.")] + async fn material_export(&self, Parameters(p): Parameters) -> Result { + to_result(self.call("material.export", params(&p)).await) + } + #[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \ 2048 px a side. In bridge mode use view_screenshot.")] async fn view_render(&self, Parameters(p): Parameters) -> Result { @@ -467,7 +490,7 @@ impl MaterialcraftMcp { (usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \ (templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \ / node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \ - view_render (3d, or 2d for one node), then package_save and outputs_export. Undo: command_run edit.undo." + view_render (3d, or 2d for one node), then package_save, outputs_export or material_export (.mcmat for TextureCraft). Undo: command_run edit.undo." )] impl ServerHandler for MaterialcraftMcp {} @@ -489,6 +512,25 @@ mod tests { assert!(mcp.call("session.inspect", json!({})).await.is_ok()); } + #[tokio::test(flavor = "multi_thread")] + async fn material_export_tool_writes_through_the_workspace_only() { + let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None }); + + let denied = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied)); + assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true)); + + let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap(); + let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws))); + assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false)); + assert!(base.join("m.mcmat").is_file()); + let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None }); + assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true)); + assert!(!base.parent().unwrap().join("m.mcmat").exists()); + } + #[test] fn oversized_replies_become_errors() { let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES))); diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 61c18446..80812243 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -69,6 +69,13 @@ impl AuthorizedWorkspace { Ok(()) } + /// Fail now, before any expensive work, when [`write`](Self::write) to `path` cannot succeed + /// for lack of a write root or because the path is malformed. + pub fn check_write(&self, path: &str) -> Result<(), AutomationError> { + relative_path(path)?; + self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write")) + } + /// Create a directory (and its parents) below the write root. pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> { let rel = relative_path(path)?; diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index c5902b97..bc313b6f 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -144,13 +144,21 @@ fn graph_param(s: &Session, p: &J) -> Result { Ok(gi) } +/// The graph and cook options a material export request asks for: `graph?`, `size?` (px) and +/// `values?` (exposed input values). Shared by `file.exportMaterial` and the workspace-scoped +/// automation export, which supply their own destination. +pub fn material_request(s: &Session, cmd: &str, p: &J) -> Result<(usize, MaterialOptions)> { + let gi = graph_param(s, p)?; + let o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(cmd, s.pkg.graph(gi)?, p)?, ..Default::default() }; + Ok((gi, o)) +} + #[cfg(not(target_arch = "wasm32"))] fn export_material(s: &mut Session, p: &J) -> Result { const CMD: &str = "file.exportMaterial"; let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") }; - let gi = graph_param(s, p)?; - let mut o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(CMD, s.pkg.graph(gi)?, p)?, ..Default::default() }; + let (gi, mut o) = material_request(s, CMD, p)?; for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() { let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?; let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c0fba6c..2729cc99 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,6 +1,6 @@ # Control protocol and MCP -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials for TextureCraft) · **Target:** the professional node-based material workflow +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (`material_export` MCP tool) · **Target:** the professional node-based material workflow Agents drive MaterialCraft three ways, all dispatching the same engine commands: @@ -26,6 +26,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: | `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O | | `bitmap.import {path, name?}` | headless | embed an image as a resource | | `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output | +| `material.export {path, graph?, size?, values?}` | headless | cook and write a portable `.mcmat` (`.mcmat` appended when missing) below the write root: the workspace-scoped `file.exportMaterial` | | `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii | | `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts | | `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click | @@ -122,6 +123,9 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k `session_inspect`, `command_list`, `command_run`, `command_batch`, `library_list`, `graph_new`, `node_add`, `node_connect`, `node_param`, `package_open`, `package_save`, `bitmap_import`, -`outputs_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`, +`outputs_export`, `material_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`, `ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. `package_open` opens `.mcmat` files -too; exporting one is CLI-only for now (the workspace sandbox refuses `file.*` commands). +too, and `material_export` `{path, graph?, size?, values?}` writes one below `--write-root` (`path` is +relative, the parent folder must exist, `values` are exposed input values). The workspace sandbox +still refuses `file.*` commands, so a sandboxed agent exports through the tool, not `file.exportMaterial`; +mesh-map `inputs` stay a CLI feature. From 6f73fc7c7745db317ff5c36b432dc13fbdf2350f Mon Sep 17 00:00:00 2001 From: smittie2000 Date: Wed, 4 Nov 2026 06:50:35 +0200 Subject: [PATCH 18/91] start_failure: say the window could not start or stopped, and offer the driver as a likely fix The dialog is shown for any error run_native returns, including one after the window was up, so "could not start its window" and "updating the graphics driver usually fixes this" overstated what is known. From review. Co-Authored-By: Claude Opus 5.5 --- apps/materialcraft/src/start_failure.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/materialcraft/src/start_failure.rs b/apps/materialcraft/src/start_failure.rs index 836ae6ba..5552e0f0 100644 --- a/apps/materialcraft/src/start_failure.rs +++ b/apps/materialcraft/src/start_failure.rs @@ -10,9 +10,10 @@ //! Now the reason also goes to an error dialog, as FilmCraft does since 0.14.0. The dialog keeps //! the process alive until it is dismissed; the exit code afterwards is still the error's. -/// What the dialog and the log say. +/// What the dialog and the log say. Any error `run_native` returns lands here, also one after the +/// window was up, so graphics is only the likely cause, not the certain one. pub(crate) fn message(error: &eframe::Error) -> String { - format!("MaterialCraft could not start its window: {error}\n\nUpdating the graphics driver usually fixes this.") + format!("MaterialCraft's window could not start or stopped with an error: {error}\n\nIf this keeps happening, updating the graphics driver often fixes it.") } /// Logs the failure and shows it in a dialog, which stays until the user closes it. @@ -29,7 +30,7 @@ mod tests { #[test] fn the_message_names_the_cause_and_what_to_do() { let text = message(&eframe::Error::AppCreation("no adapter".into())); - assert!(text.starts_with("MaterialCraft could not start its window"), "{text}"); + assert!(text.starts_with("MaterialCraft's window could not start or stopped"), "{text}"); assert!(text.contains("no adapter"), "{text}"); assert!(text.contains("graphics driver"), "{text}"); } From 5a7fe7b6b6c7fbe03d8a8188533acf6d831425e2 Mon Sep 17 00:00:00 2001 From: smittie2000 Date: Wed, 4 Nov 2026 14:17:30 +0200 Subject: [PATCH 19/91] start_failure: an app start-up error doesn't blame the graphics From CodeRabbit: an error from the app creator (AppCreation, e.g. a --control file it can't write) comes after the window and renderer started, so "update the graphics driver" doesn't apply. It now says only that the app couldn't start; other errors keep the window/graphics text. Tested both ways (the new test fails with the AppCreation arm disabled). Co-Authored-By: Claude Opus 5.5 --- apps/materialcraft/src/start_failure.rs | 27 +++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/apps/materialcraft/src/start_failure.rs b/apps/materialcraft/src/start_failure.rs index 5552e0f0..17596045 100644 --- a/apps/materialcraft/src/start_failure.rs +++ b/apps/materialcraft/src/start_failure.rs @@ -10,10 +10,17 @@ //! Now the reason also goes to an error dialog, as FilmCraft does since 0.14.0. The dialog keeps //! the process alive until it is dismissed; the exit code afterwards is still the error's. -/// What the dialog and the log say. Any error `run_native` returns lands here, also one after the -/// window was up, so graphics is only the likely cause, not the certain one. +/// What the dialog and the log say. Any error `run_native` returns lands here. One from the app's +/// own start-up (`AppCreation`, e.g. a `--control` file it can't write) says only that it couldn't +/// start. Any other comes from the window or graphics, possibly after the window was up, so +/// graphics is named as the likely cause, not the certain one. pub(crate) fn message(error: &eframe::Error) -> String { - format!("MaterialCraft's window could not start or stopped with an error: {error}\n\nIf this keeps happening, updating the graphics driver often fixes it.") + match error { + eframe::Error::AppCreation(_) => format!("MaterialCraft could not start: {error}"), + _ => format!( + "MaterialCraft's window could not start or stopped with an error: {error}\n\nIf this keeps happening, updating the graphics driver often fixes it." + ), + } } /// Logs the failure and shows it in a dialog, which stays until the user closes it. @@ -28,10 +35,18 @@ mod tests { use super::*; #[test] - fn the_message_names_the_cause_and_what_to_do() { - let text = message(&eframe::Error::AppCreation("no adapter".into())); + fn a_window_or_graphics_error_names_the_driver_as_the_likely_fix() { + let text = message(&eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable)); assert!(text.starts_with("MaterialCraft's window could not start or stopped"), "{text}"); - assert!(text.contains("no adapter"), "{text}"); + assert!(text.contains("no valid format for the surface"), "{text}"); assert!(text.contains("graphics driver"), "{text}"); } + + #[test] + fn an_app_start_up_error_does_not_blame_the_graphics() { + let text = message(&eframe::Error::AppCreation("can't write the control file".into())); + assert!(text.starts_with("MaterialCraft could not start"), "{text}"); + assert!(text.contains("can't write the control file"), "{text}"); + assert!(!text.contains("graphics"), "{text}"); + } } From d4492ac255c6a4a4765996b510baf020cedd7d03 Mon Sep 17 00:00:00 2001 From: GrosFineasss Date: Wed, 4 Nov 2026 15:32:30 +0200 Subject: [PATCH 20/91] Connect a wire dragged from an unconnected input Pressing an unconnected input started no gesture, so a wire could only be pulled from an output. It now starts a wire that ends on an output and runs the same graph.connect. Dropping it anywhere else changes nothing. Dragging from an output and unplugging a connected input work as before. Refs #13 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/graph_view.rs | 71 ++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index e9407e65..fada148d 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -1,9 +1,10 @@ //! The graph editor: a pannable, zoomable canvas of node cards (colored header, live thumbnail, //! size label), bezier wires between typed ports, frames, comments and navigation pins. //! -//! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire -//! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route -//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to +//! Gestures: left-drag a node to move it (the selection moves together), drag from an output to wire +//! it (dropping on empty canvas opens the node search, wired), drag from an unconnected input to an +//! output to wire it the other way, drag a connected input to unplug and re-route it, drag the empty +//! canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to //! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or //! double-click the canvas for the node search, right-click for menus, drop library items to add //! them. Every edit is an engine command; the gestures only draw previews until they commit. @@ -35,6 +36,7 @@ enum Drag { Nodes { delta: Vec2 }, Box { start: Pos2 }, Wire { from: (NodeId, String), detached: Option<(NodeId, String)> }, + WireFromInput { to: (NodeId, String) }, Pan, Frame { id: u64, delta: Vec2, resize: bool, nodes: Vec }, Comment { id: u64, delta: Vec2 }, @@ -609,6 +611,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent)); } } + Some(Drag::WireFromInput { to }) => { + if let (Some(p), Some(dst)) = (pointer, app.graph.ports.iter().find(|h| !h.output && h.node == to.0 && h.port == to.1)) { + bezier(&painter, p, dst.pos, Stroke::new(2.0, tk.accent)); + } + } _ => {} } @@ -689,6 +696,8 @@ fn handle_input( app.graph.drag = Some(Drag::Wire { from: (h.node, h.port.clone()), detached: None }); } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { app.graph.drag = Some(Drag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); + } else { + app.graph.drag = Some(Drag::WireFromInput { to: (h.node, h.port.clone()) }); } } else if let Some((id, title, grip)) = frames.iter().find(|(_, t, g)| t.contains(p) || g.contains(p)) { let resize = grip.contains(p) && !title.contains(p); @@ -784,6 +793,12 @@ fn handle_input( } } } + Drag::WireFromInput { to } => { + let source = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| h.output).cloned(); + if let Some(s) = source { + app.run("graph.connect", json!({"from": s.node.0, "fromPort": s.port, "to": to.0.0, "toPort": to.1})); + } + } Drag::Frame { id, delta, resize, nodes } => { if delta.length() > 0.5 && let Some(f) = app.session.graph().ok().and_then(|g| g.frames.iter().find(|f| f.id == id)).cloned() @@ -1119,6 +1134,56 @@ mod tests { assert!(app.graph.search.is_some()); } + #[test] + fn wires_connect_when_dragged_from_either_end() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.run("file.new", json!({"template": "empty"})); + let id = |v: Option| v.and_then(|v| v["id"].as_u64()).unwrap(); + let noise = id(app.run("graph.node.add", json!({"def": "perlin_noise", "at": [0, 0]}))); + let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); + let ctx = egui::Context::default(); + let frame = |app: &mut MaterialCraftApp, events: Vec| { + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }) + .textures_delta + .clear(); + }; + for _ in 0..3 { + frame(&mut app, Vec::new()); + } + let port = |app: &MaterialCraftApp, node: u64, output: bool, name: &str| { + app.graph.ports.iter().find(|h| h.node.0 == node && h.output == output && h.port == name).map(|h| h.pos).unwrap() + }; + let output = port(&app, noise, true, "output"); + let foreground = port(&app, blend, false, "foreground"); + let background = port(&app, blend, false, "background"); + let empty = app.graph.view.left_top() + vec2(5.0, 5.0); + let drag = |app: &mut MaterialCraftApp, from: Pos2, to: Pos2| { + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(from)]); + frame(app, vec![button(from, true)]); + frame(app, vec![egui::Event::PointerMoved(to)]); + frame(app, vec![button(to, false)]); + }; + let source = |app: &MaterialCraftApp| app.session.graph().unwrap().input_of(NodeId(blend), "foreground").map(|c| (c.from.0, c.from_port.clone())); + + // From the input: only an output finishes the wire, and a miss changes nothing. + drag(&mut app, foreground, empty); + assert_eq!(source(&app), None); + assert!(app.graph.search.is_none()); + drag(&mut app, foreground, background); + assert_eq!(source(&app), None); + drag(&mut app, foreground, output); + assert_eq!(source(&app), Some((noise, "output".to_string()))); + + // From the output, as before. + app.run("graph.disconnect", json!({"to": blend, "toPort": "foreground"})); + drag(&mut app, output, foreground); + assert_eq!(source(&app), Some((noise, "output".to_string()))); + } + #[test] fn node_search_shortcuts_respect_hover_and_keyboard_focus() { for key in [egui::Key::Space, egui::Key::Tab] { From 1eaa87a3ede546b90015d77da16661027f2fc049 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 08:43:44 -0500 Subject: [PATCH 21/91] Apply interface scale after pointer release --- crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/tests/interface_scale.rs | 89 +++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/interface_scale.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5bce4e0e..4adc7092 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -217,7 +217,8 @@ impl MaterialCraftApp { self.styled = Some(style); } let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); - if (ctx.zoom_factor() - scale).abs() > 1e-3 { + // Rescaling during a drag moves the control under the pointer and feeds back into its value. + if (ctx.zoom_factor() - scale).abs() > 1e-3 && !ctx.input(|i| i.pointer.any_down()) { ctx.set_zoom_factor(scale); } control::poll(self, ctx); diff --git a/crates/ui-egui/tests/interface_scale.rs b/crates/ui-egui/tests/interface_scale.rs new file mode 100644 index 00000000..90d22e03 --- /dev/null +++ b/crates/ui-egui/tests/interface_scale.rs @@ -0,0 +1,89 @@ +//! Changing interface scale must not move its slider under a held pointer. +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; + +fn harness(scale: f32, render: bool) -> Harness<'static, MaterialCraftApp> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.windows.preferences = true; + app.ui.prefs.ui_scale = scale; + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + h +} + +// Keep the physical window and pointer fixed, just as a native window does when zoom changes. +fn point(h: &mut Harness<'static, MaterialCraftApp>, physical: Pos2, pressed: Option) { + let zoom = h.ctx.zoom_factor(); + let pos = physical / zoom; + h.input_mut().screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0) / zoom)); + h.event(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.step(); +} + +fn drag_scale(h: &mut Harness<'static, MaterialCraftApp>, fraction: f32) { + let initial = h.ctx.zoom_factor(); + let track = h.get(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).rect(); + let start = track.center() * initial; + let target = pos2(track.left() + track.width() * fraction, track.center().y) * initial; + point(h, start, None); + point(h, start, Some(true)); + point(h, target, None); + let chosen = h.state().ui.prefs.ui_scale; + assert!((chosen - initial).abs() > 0.1, "the drag did not change the setting"); + for _ in 0..15 { + point(h, target, None); + assert!((h.state().ui.prefs.ui_scale - chosen).abs() < 0.001, "scale drifted under a stationary pointer"); + assert!((h.ctx.zoom_factor() - initial).abs() < 0.001, "zoom changed while dragging"); + } + point(h, target, Some(false)); + h.run_steps(5); + assert!((h.state().ui.prefs.ui_scale - chosen).abs() < 0.001, "release changed the chosen value"); + assert!((h.ctx.zoom_factor() - chosen).abs() < 0.001, "release did not apply the chosen scale"); +} + +#[test] +fn scale_drags_are_stable_and_apply_on_release() { + for (initial, fraction) in [(1.0, 0.7), (1.0, 0.1), (1.5, 0.2)] { + let mut h = harness(initial, false); + drag_scale(&mut h, fraction); + } +} + +#[test] +fn scale_track_click_applies_after_release() { + let mut h = harness(1.0, false); + let track = h.get(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).rect(); + let target = pos2(track.left() + track.width() * 0.8, track.center().y); + point(&mut h, target, None); + point(&mut h, target, Some(true)); + assert_eq!(h.ctx.zoom_factor(), 1.0); + point(&mut h, target, Some(false)); + h.run_steps(5); + assert!(h.state().ui.prefs.ui_scale > 1.5); + assert!((h.ctx.zoom_factor() - h.state().ui.prefs.ui_scale).abs() < 0.001); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn scale_drag_screenshot() { + let mut h = harness(1.0, true); + drag_scale(&mut h, 0.7); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("interface-scale-after-drag.png")).unwrap(); +} From 4c3363037656411cb71c28c202ca6853a7426747 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 13:13:08 -0500 Subject: [PATCH 22/91] Clarify node resolution while previewing --- crates/ui-egui/src/graph_view.rs | 18 ++++- crates/ui-egui/tests/preview_resolution.rs | 91 ++++++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/preview_resolution.rs diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index e9407e65..6845bf2e 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -520,7 +520,23 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max); if let Some(img) = result.and_then(|r| r.outputs.first()) { let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }; - let txt = format!("{}x{} - {}{}", img.w, img.h, if img.is_gray() { "L" } else { "C" }, bits); + let format = format!("{}{}", if img.is_gray() { "L" } else { "C" }, bits); + let txt = if let Some(limit) = app.session.preview_size { + if error.is_none() { + let [pw, ph] = g.size_px(); + resp.clone().on_hover_text(format!( + "{} x {} ({format}bpc)\n{}: {pw} x {ph}\n{}: {limit} px\n{}", + img.w, + img.h, + 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")) + } else { + format!("{}x{} - {format}", img.w, img.h) + }; painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim); } if n.def == "output" { diff --git a/crates/ui-egui/tests/preview_resolution.rs b/crates/ui-egui/tests/preview_resolution.rs new file mode 100644 index 00000000..3054a712 --- /dev/null +++ b/crates/ui-egui/tests/preview_resolution.rs @@ -0,0 +1,91 @@ +//! Node cards distinguish editing previews from configured graph resolution. +use egui::{Event, epaint::Shape, vec2}; +use egui_kittest::Harness; +use materialcraft_engine::core::NodeId; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(preview: u32, render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = preview; + app.ui.graph_camera.zoom = 1.0; + let id = NodeId(app.run("graph.node.add", json!({"def":"uniform"})).unwrap()["id"].as_u64().unwrap()); + app.apply_prefs(); + app.session.cook(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + (h, id) +} + +fn texts(shape: &Shape, out: &mut Vec) { + match shape { + Shape::Text(t) => out.push(t.galley.text().to_owned()), + Shape::Vec(shapes) => { + for s in shapes { + texts(s, out); + } + } + _ => {} + } +} +fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec { + let mut out = Vec::new(); + for s in &h.output().shapes { + texts(&s.shape, &mut out); + } + out +} + +#[test] +fn node_resolution_explains_the_preview_cap() { + let (mut h, id) = harness(512, false); + let img = &h.state().session.cooked.nodes[&id].outputs[0]; + assert_eq!((img.w, img.h), (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.nodes[&id].outputs[0]; + assert_eq!((img.w, img.h), (1024, 1024)); +} + +#[test] +fn full_size_mode_retains_the_resolution_and_format() { + let (h, id) = harness(0, false); + let img = &h.state().session.cooked.nodes[&id].outputs[0]; + assert_eq!((img.w, img.h), (1024, 1024)); + assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h)); + assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview")); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn preview_resolution_screenshots() { + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + for (preview, name) in [(512, "preview"), (0, "full-size")] { + let (mut h, id) = harness(preview, true); + h.render().unwrap().save(dir.join(format!("{name}.png"))).unwrap(); + if preview > 0 { + let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1; + h.event(Event::PointerMoved(rect.center())); + h.run_steps(90); + h.render().unwrap().save(dir.join("preview-tooltip.png")).unwrap(); + } + } +} From bdfc3daabd4cb02827e6f113598b867c1e31e85f Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Wed, 4 Nov 2026 21:58:48 +0000 Subject: [PATCH 23/91] cli: accept --automation-read-root / --automation-write-root (#55) materialcraft-cli mcp and serve now take the --automation-*-root spelling the other crafting apps use, as aliases of --read-root / --write-root. The parser stores them under the short names, so the last root given wins whichever spelling it used. Adds unit tests and a note in the protocol doc. Fixes #55 Co-Authored-By: Claude Opus --- apps/materialcraft-cli/src/main.rs | 47 +++++++++++++++++++++++++++--- docs/control-protocol.md | 3 +- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 57868c09..349746d8 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -40,7 +40,8 @@ USAGE: render: real displacement from the height output, ambient occlusion and a key light. materialcraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] MCP server on stdio: headless (file access only below the roots), or bridged to - `materialcraft --control `. + `materialcraft --control `. --automation-read-root / --automation-write-root are + the same as --read-root / --write-root (mcp and serve). materialcraft-cli serve [--port ] [--read-root ] [--write-root ] JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. @@ -60,10 +61,14 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("cook", &["--graph", "--set"], &["--full"]), ("export", &["--graph", "--set", "--format", "--depth", "--pattern"], &[]), ("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--set", "--tiling", "--displacement"], &["--full", "--hq"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root"], &[]), + ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), + ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), ]; +/// (alias, flag): the `--automation-*-root` spelling the other crafting apps use, stored under the +/// short name so the last root given wins whichever spelling it used. +const ALIASES: &[(&str, &str)] = &[("--automation-read-root", "--read-root"), ("--automation-write-root", "--write-root")]; + struct Args { pos: Vec, flags: Vec<(String, Option)>, @@ -91,7 +96,8 @@ fn parse(cmd: &str, raw: &[String]) -> Result { while let Some(x) = it.next() { if valued.contains(&x.as_str()) { let v = it.next().ok_or_else(|| format!("{x} needs a value"))?; - a.flags.push((x.clone(), Some(v.clone()))); + let name = ALIASES.iter().find(|(alias, _)| alias == x).map_or(x.as_str(), |(_, flag)| flag); + a.flags.push((name.to_string(), Some(v.clone()))); } else if bare.contains(&x.as_str()) { a.flags.push((x.clone(), None)); } else if x.starts_with('-') && x.len() > 1 && x.parse::().is_err() { @@ -301,3 +307,36 @@ fn workspace(a: &Args) -> Result { let ws = AuthorizedWorkspace::new(r.map(std::path::Path::new), w.map(std::path::Path::new)).map_err(|e| e.to_string())?; Ok(Filesystem::Workspace(ws)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(v: &[&str]) -> Vec { + v.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn automation_root_flags_are_aliases_of_the_short_ones() { + for cmd in ["mcp", "serve"] { + let a = parse(cmd, &strings(&["--automation-read-root", "/r", "--automation-write-root", "/w"])).unwrap(); + assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}"); + let a = parse(cmd, &strings(&["--read-root", "/r", "--write-root", "/w"])).unwrap(); + assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}"); + } + } + + #[test] + fn the_last_root_flag_wins_whatever_its_spelling() { + let a = parse("mcp", &strings(&["--read-root", "/a", "--automation-read-root", "/b"])).unwrap(); + assert_eq!(a.get("--read-root"), Some("/b")); + let a = parse("mcp", &strings(&["--automation-write-root", "/a", "--write-root", "/b"])).unwrap(); + assert_eq!(a.get("--write-root"), Some("/b")); + } + + #[test] + fn automation_root_flags_need_a_value_and_stay_unknown_elsewhere() { + assert!(parse("mcp", &strings(&["--automation-read-root"])).is_err()); + assert!(parse("cook", &strings(&["--automation-read-root", "/r"])).is_err()); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 75488a5c..726cb5d6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -5,7 +5,8 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: 1. **MCP** (`materialcraft-cli mcp`): headless (an in-process session, files only below - `--read-root` / `--write-root`) or bridged to the running app (`--bridge `). + `--read-root` / `--write-root`, also spelled `--automation-read-root` / + `--automation-write-root` as in the other crafting apps; `serve` takes them too) or bridged to the running app (`--bridge `). 2. **JSON lines** (`materialcraft-cli serve`): the same methods on stdio, or on `127.0.0.1:` behind a token. 3. **The app's control channel** (`materialcraft --control `): one JSON request per line, From 9b51c35dd74189ced6e27e3558629ce351b77a90 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 19:14:56 -0500 Subject: [PATCH 24/91] Keep keyboard-selected node search results visible --- crates/ui-egui/src/graph_view.rs | 69 +++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph_view.rs index ee877da9..c3a1f2d9 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph_view.rs @@ -1114,7 +1114,7 @@ fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) { pick = Some(d.id); } egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { - for (i, d) in list.iter().enumerate().take(60) { + for (i, d) in list.iter().enumerate() { let r = ui.add( egui::Button::selectable(i == s.sel, format!("{} ", d.label)) .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), @@ -1456,4 +1456,71 @@ mod tests { assert!(p.y > r.top() + HEADER_H && p.y < r.bottom() - FOOTER_H); } } + fn search_harness(render: bool) -> egui_kittest::Harness<'static, MaterialCraftApp> { + let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + let pointer = h.state().graph.view.center(); + h.event(egui::Event::PointerMoved(pointer)); + h.step(); + h.key_press(egui::Key::Tab); + h.step(); + assert!(h.state().graph.search.is_some()); + h + } + + fn select_result_after_cutoff(h: &mut egui_kittest::Harness<'static, MaterialCraftApp>) -> &'static str { + for _ in 0..60 { + h.key_press(egui::Key::ArrowDown); + h.step(); + } + h.run_steps(3); // Let scroll_to_me bring the selected row into view. + let selected = h.state().graph.search.as_ref().unwrap().sel; + assert_eq!(selected, 60); + let def = matches("")[selected]; + let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); + fn visible(shape: &egui::epaint::Shape, clip: Rect, popup: Rect, label: &str) -> bool { + match shape { + egui::epaint::Shape::Text(t) => popup.contains(t.pos) && clip.contains(t.pos) && t.galley.text().trim_start().starts_with(label), + egui::epaint::Shape::Vec(v) => v.iter().any(|s| visible(s, clip, popup, label)), + _ => false, + } + } + assert!( + h.output().shapes.iter().any(|s| visible(&s.shape, s.clip_rect, popup, def.label)), + "keyboard-selected result {selected} ({}) is not visible in the popup", + def.label + ); + def.id + } + + #[test] + fn keyboard_search_selection_after_sixty_results_is_visible_and_inserts() { + let mut h = search_harness(false); + let expected = select_result_after_cutoff(&mut h); + h.key_press(egui::Key::Enter); + h.step(); + assert!(h.state().graph.search.is_none()); + let graph = h.state().session.graph().unwrap(); + assert_eq!(graph.nodes.len(), 1); + assert_eq!(graph.nodes[0].def, expected); + } + + #[test] + #[ignore = "requires an offscreen GPU"] + fn search_result_after_sixty_screenshot() { + let mut h = search_harness(true); + select_result_after_cutoff(&mut h); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("search-result-61.png")).unwrap(); + } } From ff310018eff28d1934ec7130a9e1759c6c5fd3c2 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 19:56:16 -0500 Subject: [PATCH 25/91] Make round parameter values reachable by dragging --- crates/ui-egui/src/widgets.rs | 9 ++- crates/ui-egui/tests/slider_round_values.rs | 89 +++++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/tests/slider_round_values.rs diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4b2d5dbd..69f1546e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -45,8 +45,13 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI if (resp.dragged() || resp.clicked()) && let Some(p) = resp.interact_pointer_pos() { - let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); - let v = lo + (hi - lo) * t; + let value_at = |x: f32| { + let t = ((x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); + f64::from(lo) + (f64::from(hi) - f64::from(lo)) * f64::from(t) + }; + // Use the same round-value aiming as egui's standard sliders, within one physical pixel. + let radius = ui.input(|i| i.aim_radius()); + let v = egui::emath::smart_aim::best_in_range_f64(value_at(p.x - radius), value_at(p.x + radius)) as f32; if (v - *value).abs() > f32::EPSILON { *value = v; resp.mark_changed(); diff --git a/crates/ui-egui/tests/slider_round_values.rs b/crates/ui-egui/tests/slider_round_values.rs new file mode 100644 index 00000000..8a257500 --- /dev/null +++ b/crates/ui-egui/tests/slider_round_values.rs @@ -0,0 +1,89 @@ +//! Pointer drags should reach nearby round values, as standard egui sliders do. +use egui::{Event, Modifiers, PointerButton, pos2, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_engine::core::{NodeId, Value}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(ppp: f32, render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap()); + app.session.reset_history(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + (h, id) +} + +fn drag_near(h: &mut Harness<'static, MaterialCraftApp>, label: &str, index: usize, value: f32, lo: f32, hi: f32) { + let rect = h.get_all(By::new().role(egui::accesskit::Role::Slider).label(label)).nth(index).unwrap().rect(); + let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y); + // Aim slightly off the exact value, within one physical pixel. + let target = pos2(rect.left() + 5.0 + (rect.width() - 10.0) * (value - lo) / (hi - lo) + 0.4 / h.ctx.pixels_per_point(), rect.center().y); + h.event(Event::PointerMoved(start)); + h.step(); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.event(Event::PointerMoved(start + vec2(10.0, 0.0))); + h.step(); + h.event(Event::PointerMoved(target)); + h.step(); + h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.step(); + h.run_steps(3); +} +fn rotation(h: &Harness<'static, MaterialCraftApp>, id: NodeId) -> f32 { + match h.state().session.graph().unwrap().node(id).unwrap().params.get("rotation") { + Some(Value::Float(v)) => *v, + None => 0.0, + other => panic!("unexpected rotation {other:?}"), + } +} + +#[test] +fn dragging_can_reach_exact_round_angles_at_multiple_pixel_scales() { + for ppp in [1.0, 2.0] { + for angle in [90.0, -90.0, 0.0, 360.0, -360.0] { + let (mut h, id) = harness(ppp, false); + drag_near(&mut h, "Rotation", 0, angle, -360.0, 360.0); + assert_eq!(rotation(&h, id), angle / 360.0, "angle={angle}, pixels_per_point={ppp}"); + if angle == 90.0 { + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(rotation(&h, id), 0.0); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(rotation(&h, id), 0.25); + } + } + } +} + +#[test] +fn fractional_parameter_values_remain_reachable() { + let (mut h, id) = harness(1.0, false); + drag_near(&mut h, "X", 1, 1.5, 0.01, 10.0); + drag_near(&mut h, "X", 0, -0.5, -1.0, 1.0); + let n = h.state().session.graph().unwrap().node(id).unwrap(); + assert_eq!(n.params.get("scale"), Some(&Value::Float2([1.5, 1.0]))); + assert_eq!(n.params.get("offset"), Some(&Value::Float2([-0.5, 0.0]))); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn exact_angle_screenshot() { + let (mut h, id) = harness(1.0, true); + drag_near(&mut h, "Rotation", 0, 90.0, -360.0, 360.0); + assert_eq!(rotation(&h, id), 0.25); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("rotation-90.png")).unwrap(); +} From f421d10b3fbfaf199f2c58c1fe3c19f503230111 Mon Sep 17 00:00:00 2001 From: Belligerently Date: Wed, 4 Nov 2026 20:18:15 -0500 Subject: [PATCH 26/91] Recognize Histogram Scan and Auto Levels SBS aliases --- crates/formats/src/sbs.rs | 19 +++- crates/formats/tests/sbs_library_aliases.rs | 117 ++++++++++++++++++++ 2 files changed, 133 insertions(+), 3 deletions(-) create mode 100644 crates/formats/tests/sbs_library_aliases.rs diff --git a/crates/formats/src/sbs.rs b/crates/formats/src/sbs.rs index 5beb8207..ff6431b9 100644 --- a/crates/formats/src/sbs.rs +++ b/crates/formats/src/sbs.rs @@ -1074,8 +1074,13 @@ impl<'text> Reader<'text, '_> { if let Some(node) = node { for param in instance_params() { let param_name = child_value(param, "name").unwrap_or(""); - match def.param(param_name) { - Some(param_def) => self.set_param(node, param_name, ¶m_def.default, param_def.options.len(), param, &graph_name), + let id = match (def.id, param_name) { + ("histogram_scan", "Position") => "position", + ("histogram_scan", "Contrast") => "contrast", + _ => param_name, + }; + match def.param(id) { + Some(param_def) => self.set_param(node, id, ¶m_def.default, param_def.options.len(), param, &graph_name), None => self.warnings.add(format!("`{}`: parameter `{param_name}` has no MaterialCraft equivalent and was ignored", def.id)), } } @@ -1086,7 +1091,15 @@ impl<'text> Reader<'text, '_> { let port_for = |identifier: &str| if def.output_index(identifier).is_some() { identifier.to_string() } else { first_output.clone() }; let unbridged = output_uids.iter().filter(|(uid, _)| !bridgings.iter().any(|(b, _)| b == uid)).map(|(uid, _)| (uid.clone(), first_output.clone())); let outputs = bridgings.iter().map(|(uid, identifier)| (uid.clone(), port_for(identifier))).chain(unbridged).collect(); - let inputs = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect(); + let mut inputs: HashMap<_, _> = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect(); + let input_alias = match def.id { + "histogram_scan" => Some("Input_1"), + "auto_levels" => Some("Input"), + _ => None, + }; + if let Some(alias) = input_alias { + inputs.insert(alias.to_string(), "input".to_string()); + } ReadNode { id, index, inputs, outputs, open_inputs: false } } diff --git a/crates/formats/tests/sbs_library_aliases.rs b/crates/formats/tests/sbs_library_aliases.rs new file mode 100644 index 00000000..a90a104f --- /dev/null +++ b/crates/formats/tests/sbs_library_aliases.rs @@ -0,0 +1,117 @@ +//! The reported library-node aliases must preserve imported settings and connections. +use materialcraft_core::{Graph, Package, Value}; +use materialcraft_formats::sbs::{read_sbs, write_sbs}; + +fn plain_xml(bytes: &[u8]) -> String { + let text = String::from_utf8(bytes.to_vec()).unwrap(); + // Exercise XML import rather than the writer's embedded exact native-package copy. + format!("{}", text.split("") - } else { - break; - }; - match rest[skip_open.len()..].find(skip_close) { - Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], - None => return false, - } - } - - rest.strip_prefix("' || c == '/' || c.is_whitespace())) -} - -// --------------------------------------------------------------------------------------------- -// Warnings -// --------------------------------------------------------------------------------------------- - -/// Warning lines, deduplicated with counts, in first-seen order. -#[derive(Default)] -struct Warnings { - lines: Vec<(String, usize)>, - line_index: HashMap, -} - -impl Warnings { - fn add(&mut self, message: impl Into) { - let message = message.into(); - if let Some(line) = self.line_index.get(&message).and_then(|&i| self.lines.get_mut(i)) { - line.1 += 1; - return; - } - - self.line_index.insert(message.clone(), self.lines.len()); - self.lines.push((message, 1)); - } - - fn finish(self) -> Vec { - let total = self.lines.len(); - let mut out: Vec = - self.lines.into_iter().take(MAX_WARNINGS).map(|(line, count)| if count > 1 { format!("{line} (×{count})") } else { line }).collect(); - if total > MAX_WARNINGS { - out.push(format!("…and {} more warnings", total - MAX_WARNINGS)); - } - out - } -} - -// --------------------------------------------------------------------------------------------- -// Atomic filters -// --------------------------------------------------------------------------------------------- - -/// How an SBS parameter becomes a MaterialCraft one. -#[derive(Clone, Copy, PartialEq)] -enum ParamConversion { - /// By the MaterialCraft parameter's type. - ByType, - /// An SBS boolean that is `true` for option 0 of a two-option MaterialCraft choice. - TrueIsFirstOption, -} - -use ParamConversion::{ByType, TrueIsFirstOption}; - -/// An SBS atomic filter and the MaterialCraft atomic node it maps to. -struct FilterMap { - sbs: &'static str, - def: &'static str, - /// (SBS input identifier, MaterialCraft input port). - inputs: &'static [(&'static str, &'static str)], - /// (SBS parameter, MaterialCraft parameter, conversion). - params: &'static [(&'static str, &'static str, ParamConversion)], -} - -const FILTERS: &[FilterMap] = &[ - FilterMap { sbs: "uniform", def: "uniform", inputs: &[], params: &[("outputcolor", "color", ByType), ("colorswitch", "mode", TrueIsFirstOption)] }, - FilterMap { - sbs: "blend", - def: "blend", - inputs: &[("source", "foreground"), ("destination", "background"), ("opacity", "mask")], - params: &[("blendingmode", "mode", ByType), ("opacitymult", "opacity", ByType)], - }, - FilterMap { sbs: "blur", def: "blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity", ByType)] }, - FilterMap { - sbs: "shuffle", - def: "channels_shuffle", - inputs: &[("input1", "input1"), ("input2", "input2")], - params: &[("channelred", "red", ByType), ("channelgreen", "green", ByType), ("channelblue", "blue", ByType), ("channelalpha", "alpha", ByType)], - }, - FilterMap { sbs: "curve", def: "curve", inputs: &[("input1", "input")], params: &[] }, - FilterMap { - sbs: "dirmotionblur", - def: "directional_blur", - inputs: &[("input1", "input")], - params: &[("intensity", "intensity", ByType), ("mblurangle", "angle", ByType)], - }, - FilterMap { - sbs: "directionalwarp", - def: "directional_warp", - inputs: &[("input1", "input"), ("inputintensity", "intensity_input")], - params: &[("intensity", "intensity", ByType), ("warpangle", "angle", ByType)], - }, - FilterMap { - sbs: "distance", - def: "distance", - inputs: &[("mask", "mask"), ("source", "source")], - params: &[("distance", "distance", ByType), ("combinedistance", "combine", ByType)], - }, - FilterMap { - sbs: "emboss", - def: "emboss", - inputs: &[("input1", "input"), ("inputgradient", "height")], - params: &[ - ("intensity", "intensity", ByType), - ("lightangle", "light_angle", ByType), - ("highlightcolor", "highlight", ByType), - ("shadowcolor", "shadow", ByType), - ], - }, - FilterMap { - sbs: "dyngradient", - def: "gradient_dynamic", - inputs: &[("input1", "input"), ("input2", "gradient"), ("inputgradient", "gradient")], - params: &[("position", "position", ByType), ("orientation", "orientation", ByType)], - }, - FilterMap { sbs: "gradient", def: "gradient_map", inputs: &[("input1", "input")], params: &[("colorswitch", "mode", TrueIsFirstOption)] }, - FilterMap { sbs: "grayscaleconversion", def: "grayscale_conversion", inputs: &[("input1", "input")], params: &[] }, - FilterMap { - sbs: "hsl", - def: "hsl", - inputs: &[("input1", "input")], - params: &[("hue", "hue", ByType), ("saturation", "saturation", ByType), ("luminance", "lightness", ByType)], - }, - FilterMap { sbs: "bitmap", def: "bitmap", inputs: &[], params: &[] }, - FilterMap { - sbs: "levels", - def: "levels", - inputs: &[("input1", "input")], - params: &[ - ("levelinlow", "in_low", ByType), - ("levelinmid", "in_mid", ByType), - ("levelinhigh", "in_high", ByType), - ("leveloutlow", "out_low", ByType), - ("levelouthigh", "out_high", ByType), - ], - }, - FilterMap { - sbs: "normal", - def: "normal", - inputs: &[("input1", "input")], - params: &[("intensity", "intensity", ByType), ("inversedy", "format", TrueIsFirstOption), ("input2alpha", "height_alpha", ByType)], - }, - FilterMap { - sbs: "pixelprocessor", - def: "pixel_processor", - inputs: &[("input", "input0"), ("input:1", "input1"), ("input:2", "input2"), ("input:3", "input3")], - params: &[], - }, - FilterMap { sbs: "valueprocessor", def: "value_processor", inputs: &[("input", "input0")], params: &[] }, - FilterMap { sbs: "sharpen", def: "sharpen", inputs: &[("input1", "input")], params: &[("intensity", "intensity", ByType)] }, - FilterMap { - sbs: "transformation", - def: "transformation", - inputs: &[("input1", "input")], - params: &[("offset", "offset", ByType), ("mattecolor", "matte", ByType)], - }, - FilterMap { sbs: "warp", def: "warp", inputs: &[("input1", "input"), ("inputgradient", "gradient")], params: &[("intensity", "intensity", ByType)] }, - FilterMap { sbs: "passthrough", def: "dot", inputs: &[("input", "input"), ("input1", "input")], params: &[] }, - FilterMap { sbs: "text", def: "text", inputs: &[], params: &[("text", "text", ByType)] }, - FilterMap { sbs: "svg", def: "svg", inputs: &[], params: &[] }, - FilterMap { sbs: "fxmaps", def: "fx_map", inputs: &[], params: &[] }, -]; - -/// SBS parameters every node has, read as base parameters. -const BASE_PARAMS: &[&str] = &["outputsize", "format", "randomseed", "tiling", "pixelsize", "pixelratio", "quality"]; - -/// Filter parameters handled in code or knowingly ignored, so they raise no warning. -const HANDLED_PARAMS: &[(&str, &str)] = &[ - ("bitmap", "bitmapresourcepath"), - ("bitmap", "colorspace"), - ("grayscaleconversion", "channelsweights"), - ("transformation", "matrix22"), - ("curve", "exposecurve"), -]; - -fn filter_by_sbs_name(name: &str) -> Option<&'static FilterMap> { - FILTERS.iter().find(|f| f.sbs == name) -} - -fn filter_by_def(def: &str) -> Option<&'static FilterMap> { - FILTERS.iter().find(|f| f.def == def) -} - -/// The MaterialCraft usage index of an SBS usage name; unknown names are "any". -fn usage_index(name: &str) -> u32 { - let ids = materialcraft_nodes::atomic::USAGE_IDS; - let name = name.trim(); - let index = ids.iter().position(|u| u.eq_ignore_ascii_case(name)).or_else(|| name.eq_ignore_ascii_case("diffuse").then_some(0)); - index.unwrap_or(ids.len().saturating_sub(1)) as u32 -} - -fn usage_name(index: u32) -> &'static str { - materialcraft_nodes::atomic::USAGE_IDS.get(index as usize).copied().unwrap_or("any") -} - -// --------------------------------------------------------------------------------------------- -// Values -// --------------------------------------------------------------------------------------------- - -/// A constant as SBS stores it. -#[derive(Clone, Debug, PartialEq)] -enum SbsValue { - Floats(Vec), - Ints(Vec), - Bool(bool), - Text(String), -} - -/// Up to 16 whitespace-separated floats; bad or non-finite ones read as 0. -fn parse_floats(text: &str) -> Vec { - text.split_whitespace().take(16).map(|t| t.parse::().ok().filter(|v| v.is_finite()).unwrap_or(0.0)).collect() -} - -/// Up to 16 whitespace-separated integers, saturated to `i32`; bad ones read as 0. -fn parse_ints(text: &str) -> Vec { - let parse = |t: &str| t.parse::().map(|v| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32).or_else(|_| t.parse::().map(|v| v as i32)); - text.split_whitespace().take(16).map(|t| parse(t).unwrap_or(0)).collect() -} - -/// The constant under `holder` (a `paramValue`, `defaultValue` or `constValue` element). -fn sbs_constant(holder: XmlNode) -> Option { - let element = holder.children().find(|c| c.is_element())?; - let text = element.attribute("v").unwrap_or(""); - let tag = element.tag_name().name(); - - if tag == "constantValueBool" { - Some(SbsValue::Bool(parse_ints(text).first().is_some_and(|b| *b != 0) || text.trim().eq_ignore_ascii_case("true"))) - } else if tag == "constantValueString" { - Some(SbsValue::Text(text.to_string())) - } else if tag.starts_with("constantValueFloat") { - Some(SbsValue::Floats(parse_floats(text))) - } else if tag.starts_with("constantValueInt") { - Some(SbsValue::Ints(parse_ints(text))) - } else { - None - } -} - -impl SbsValue { - /// Component `i` as a float (the first component when there are fewer). - fn float(&self, i: usize) -> f32 { - match self { - SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0), - SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0) as f32, - SbsValue::Bool(b) => f32::from(u8::from(*b)), - SbsValue::Text(_) => 0.0, - } - } - - /// Component `i` as an integer (the first component when there are fewer). - fn int(&self, i: usize) -> i32 { - match self { - SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0), - SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0).round() as i32, - SbsValue::Bool(b) => i32::from(*b), - SbsValue::Text(_) => 0, - } - } - - fn truthy(&self) -> bool { - match self { - SbsValue::Bool(b) => *b, - SbsValue::Text(s) => s == "1" || s.eq_ignore_ascii_case("true"), - _ => self.float(0) != 0.0, - } - } - - fn component_count(&self) -> usize { - match self { - SbsValue::Floats(v) => v.len(), - SbsValue::Ints(v) => v.len(), - _ => 1, - } - } -} - -/// `value` as the type of `like` (a parameter default); `options` is an enum's option count. -fn to_param_value(like: &Value, value: &SbsValue, options: usize) -> Option { - let f = |i| value.float(i); - - Some(match like { - Value::Float(_) => Value::Float(f(0)), - Value::Float2(_) => Value::Float2([f(0), f(1)]), - Value::Float3(_) => Value::Float3([f(0), f(1), f(2)]), - Value::Float4(_) => Value::Float4([f(0), f(1), f(2), f(3)]), - // SBS colors are stored as displayed (sRGB); MaterialCraft's are linear - Value::Color(_) if value.component_count() >= 3 => { - let alpha = if value.component_count() >= 4 { f(3) } else { 1.0 }; - Value::Color([srgb_to_linear(f(0)), srgb_to_linear(f(1)), srgb_to_linear(f(2)), alpha]) - } - Value::Color(_) => { - let gray = srgb_to_linear(f(0)); - Value::Color([gray, gray, gray, 1.0]) - } - Value::Int(_) => Value::Int(value.int(0)), - Value::Int2(_) => Value::Int2([value.int(0), value.int(1)]), - Value::Bool(_) => Value::Bool(value.truthy()), - Value::Enum(_) => { - let last = options.saturating_sub(1).min(i32::MAX as usize) as i32; - Value::Enum(value.int(0).clamp(0, last) as u32) - } - Value::Text(_) => match value { - SbsValue::Text(s) => Value::Text(s.clone()), - _ => return None, - }, - Value::Curve(_) | Value::Gradient(_) | Value::Function(_) => return None, - }) -} - -/// `value` as the MaterialCraft value of the same shape (for exposed inputs and instance parameters). -fn to_natural_value(value: &SbsValue) -> Value { - let f = |i| value.float(i); - - match value { - SbsValue::Bool(b) => Value::Bool(*b), - SbsValue::Text(s) => Value::Text(s.clone()), - SbsValue::Ints(v) if v.len() <= 1 => Value::Int(value.int(0)), - SbsValue::Ints(_) => Value::Int2([value.int(0), value.int(1)]), - SbsValue::Floats(v) => match v.len() { - 0 | 1 => Value::Float(f(0)), - 2 => Value::Float2([f(0), f(1)]), - 3 => Value::Float3([f(0), f(1), f(2)]), - _ => Value::Float4([f(0), f(1), f(2), f(3)]), - }, - } -} - -/// SBS type codes of exposed graph inputs. -mod type_code { - pub const COLOR_IMAGE: i64 = 1; - pub const GRAY_IMAGE: i64 = 2; - pub const BOOL: i64 = 4; - pub const INT1: i64 = 16; - pub const INT2: i64 = 32; - pub const INT3: i64 = 64; - pub const INT4: i64 = 128; - pub const FLOAT1: i64 = 256; - pub const FLOAT2: i64 = 512; - pub const FLOAT3: i64 = 1024; - pub const FLOAT4: i64 = 2048; - pub const STRING: i64 = 16384; -} - -/// An exposed input's default from its SBS type code. -fn exposed_default(code: i64, value: Option<&SbsValue>) -> Value { - use type_code::*; - - let value = value.cloned().unwrap_or(SbsValue::Floats(vec![0.0])); - let f = |i| value.float(i); - match code { - BOOL => Value::Bool(value.truthy()), - INT1 => Value::Int(value.int(0)), - INT2 | INT3 | INT4 => Value::Int2([value.int(0), value.int(1)]), - FLOAT1 => Value::Float(f(0)), - FLOAT2 => Value::Float2([f(0), f(1)]), - FLOAT3 => Value::Float3([f(0), f(1), f(2)]), - FLOAT4 => Value::Float4([f(0), f(1), f(2), f(3)]), - STRING => match &value { - SbsValue::Text(s) => Value::Text(s.clone()), - _ => Value::Text(String::new()), - }, - _ => to_natural_value(&value), - } -} - -fn exposed_type_code(value: &Value) -> i64 { - use type_code::*; - - match value { - Value::Bool(_) => BOOL, - Value::Int(_) | Value::Enum(_) => INT1, - Value::Int2(_) => INT2, - Value::Float(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) => FLOAT1, - Value::Float2(_) => FLOAT2, - Value::Float3(_) => FLOAT3, - Value::Float4(_) | Value::Color(_) => FLOAT4, - Value::Text(_) => STRING, - } -} - -/// `v` for XML, with non-finite values written as 0. -fn format_float(v: f32) -> String { - if v.is_finite() { format!("{v}") } else { "0".into() } -} - -/// The SBS constant element for `value` (`None` for curves, gradients and functions). -fn constant_xml(value: &Value) -> Option { - let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::>().join(" "); - let (tag, text) = match value { - Value::Float(x) => ("constantValueFloat1", format_float(*x)), - Value::Float2(x) => ("constantValueFloat2", join(x)), - Value::Float3(x) => ("constantValueFloat3", join(x)), - Value::Float4(x) => ("constantValueFloat4", join(x)), - Value::Color(c) => ("constantValueFloat4", join(&[linear_to_srgb(c[0]), linear_to_srgb(c[1]), linear_to_srgb(c[2]), c[3]])), - Value::Int(i) => ("constantValueInt32", i.to_string()), - Value::Int2(i) => ("constantValueInt2", format!("{} {}", i[0], i[1])), - Value::Enum(e) => ("constantValueInt32", e.to_string()), - Value::Bool(b) => ("constantValueBool", u8::from(*b).to_string()), - Value::Text(s) => ("constantValueString", s.clone()), - Value::Curve(_) | Value::Gradient(_) | Value::Function(_) => return None, - }; - - Some(format!("<{tag} v=\"{}\"/>", xml_escape(&text))) -} - -// --------------------------------------------------------------------------------------------- -// XML helpers -// --------------------------------------------------------------------------------------------- - -fn child_element<'a, 'input>(node: XmlNode<'a, 'input>, tag: &str) -> Option> { - node.children().find(|c| c.is_element() && c.tag_name().name() == tag) -} - -fn children_named<'a, 'input: 'a>(node: XmlNode<'a, 'input>, tag: &'a str) -> impl Iterator> + 'a { - node.children().filter(move |c| c.is_element() && c.tag_name().name() == tag) -} - -/// The `v` attribute of child element `tag`, how SBS stores every scalar. -fn child_value<'a>(node: XmlNode<'a, '_>, tag: &str) -> Option<&'a str> { - child_element(node, tag).and_then(|c| c.attribute("v")) -} - -/// `text` escaped for XML attributes and text, without characters XML 1.0 can't hold. -fn xml_escape(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - for c in text.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - '\t' => out.push_str(" "), - '\n' => out.push_str(" "), - '\r' => out.push_str(" "), - c if (c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}' => {} - c => out.push(c), - } - } - out -} - -/// FNV-1a (64 bits) of the `` an exact copy was written with. -fn content_hash(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, b| (hash ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)) -} - -fn base64_engine() -> base64::engine::GeneralPurpose { - base64::engine::general_purpose::STANDARD -} - -/// Decode embedded data: base64 of a big-endian u32 length followed by zlib-compressed bytes. -fn decode_embedded(strdata: &str) -> std::result::Result, String> { - let raw = base64_engine().decode(strdata.split_whitespace().collect::()).map_err(|e| format!("bad base64: {e}"))?; - let (length, compressed) = raw.split_at_checked(4).ok_or("too short")?; - let length = u32::from_be_bytes([length[0], length[1], length[2], length[3]]) as usize; - if length > MAX_EMBEDDED_BYTES { - return Err(format!("{length} bytes is over the {MAX_EMBEDDED_BYTES}-byte limit")); - } - - let mut out = Vec::with_capacity(length.min(1 << 24)); - let mut decoder = flate2::read::ZlibDecoder::new(compressed).take(MAX_EMBEDDED_BYTES as u64 + 1); - decoder.read_to_end(&mut out).map_err(|e| format!("bad compressed data: {e}"))?; - if out.len() != length { - return Err(format!("{} bytes where {length} were declared", out.len())); - } - Ok(out) -} - -fn encode_embedded(bytes: &[u8]) -> Result { - let length = u32::try_from(bytes.len()).map_err(|_| FormatError::Io("resource too large".into()))?; - let mut encoder = flate2::write::ZlibEncoder::new(length.to_be_bytes().to_vec(), flate2::Compression::default()); - encoder.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?; - let raw = encoder.finish().map_err(|e| FormatError::Io(e.to_string()))?; - Ok(base64_engine().encode(raw)) -} - -// --------------------------------------------------------------------------------------------- -// Reading -// --------------------------------------------------------------------------------------------- - -/// Read an SBS package; `name` is its file name and `linked` loads files it links to by relative path. -pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option>) -> Result { - if bytes.len() > MAX_SBS_BYTES { - return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); - } - - let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; - let text = text.trim_start_matches('\u{feff}'); - let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES }; - let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?; - let root = doc.root_element(); - if root.tag_name().name() != "package" { - return Err(FormatError::BadPackage("not an SBS package (the root element is not )".into())); - } - - let mut warnings = Warnings::default(); - let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); - let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); - let package_name = match child_value(root, "identifier").map(str::trim) { - Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), - _ if !file_stem.is_empty() => file_stem.to_string(), - _ => "Untitled package".to_string(), - }; - let mut reader = - Reader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 }; - for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { - if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { - reader.dependencies.insert(uid.to_string(), file.to_string()); - } - } - - // Resources first: the exact copy and the SBS graphs both use them - let content = child_element(root, "content"); - let mut pkg = Package::new(&package_name); - let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); - if let Some(content) = content { - reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); - } - - if let Some(content) = content - && let Some(mut exact) = read_exact_copy(root, &text[content.range()], reader.warnings) - { - for resource in &mut exact.resources { - match pkg.resources.iter().find(|r| r.name == resource.name) { - Some(found) => resource.bytes = found.bytes.clone(), - None => reader.warnings.add(format!("resource `{}` is missing from the file", resource.name)), - } - } - report_placeholders(&exact, reader.warnings); - return Ok(SbsRead { pkg: exact, warnings: warnings.finish(), exact: true }); - } - - // Name every graph first so instances can refer to graphs defined later in the file - let mut names: Vec = Vec::new(); - for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { - let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); - let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); - reader.graph_names.insert(path.clone(), unique.clone()); - names.push(unique); - } - if graph_elements.len() > MAX_GRAPHS { - reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); - } - - for ((_, graph), name) in graph_elements.iter().zip(names) { - let graph = reader.read_graph(*graph, name); - pkg.graphs.push(graph); - } - if pkg.graphs.is_empty() { - reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); - pkg.graphs.push(Graph::new("Graph")); - } - - report_placeholders(&pkg, reader.warnings); - Ok(SbsRead { pkg, warnings: warnings.finish(), exact: false }) -} - -/// One warning per missing node kind and graph. -fn report_placeholders(pkg: &Package, warnings: &mut Warnings) { - for graph in &pkg.graphs { - let mut counts: BTreeMap = BTreeMap::new(); - for node in graph.nodes.iter().filter(|n| n.def == MISSING_NODE) { - let name = match node.params.get("sbs_name") { - Some(Value::Text(s)) if !s.is_empty() => s.clone(), - _ => node.label.clone(), - }; - *counts.entry(name).or_default() += 1; - } - - for (name, count) in counts { - let times = if count > 1 { format!(" ×{count}") } else { String::new() }; - warnings.add(format!("graph `{}`: missing node `{name}`{times} is not in MaterialCraft's library yet; kept as a placeholder", graph.name)); - } - } -} - -/// The exact MaterialCraft copy, if present and written for exactly this `content`. -fn read_exact_copy(root: XmlNode, content: &str, warnings: &mut Warnings) -> Option { - let comment = root.children().filter(|c| c.is_comment()).filter_map(|c| c.text()).find(|t| t.trim_start().starts_with(EXACT_MARK))?; - let field = |key: &str| comment.split_whitespace().find_map(|part| part.strip_prefix(key)); - - if field("version=").and_then(|v| v.parse::().ok()) != Some(EXACT_VERSION) { - warnings.add("the MaterialCraft data in this file is from another version; the graphs were read from the SBS data"); - return None; - } - if field("hash=") != Some(format!("{:016x}", content_hash(content.as_bytes())).as_str()) { - warnings.add("this file was changed outside MaterialCraft since it was saved; the graphs were read from the SBS data"); - return None; - } - - let decoded = decode_embedded(field("data=").unwrap_or("")).and_then(|json| serde_json::from_slice::(&json).map_err(|e| e.to_string())); - decoded.map_err(|e| warnings.add(format!("the MaterialCraft data in this file is damaged ({e}); the graphs were read from the SBS data"))).ok() -} - -fn unique_name(taken: &[String], base: &str) -> String { - let free = |name: &str| !taken.iter().any(|t| t == name); - if free(base) { - return base.to_string(); - } - (1..).map(|i| format!("{base}_{i}")).find(|name| free(name)).unwrap_or_else(|| base.to_string()) -} - -struct Reader<'text, 'warnings> { - text: &'text str, - warnings: &'warnings mut Warnings, - /// Dependency uid → file name. - dependencies: HashMap, - /// Package path (`Folder/Graph`) → graph name. - graph_names: HashMap, - /// Package path (`Resources/Bitmap`) → resource name. - resource_names: HashMap, - node_count: usize, -} - -/// A node being read, as wires from the SBS data find it. -struct ReadNode { - id: NodeId, - /// Position in `Graph::nodes`. - index: usize, - /// SBS input identifier → MaterialCraft port. - inputs: HashMap, - /// (SBS output uid, MaterialCraft port), in output order. - outputs: Vec<(String, String)>, - /// Placeholders and graph instances take whatever inputs wires arrive at. - open_inputs: bool, -} - -/// Add a node and return it with its position in `graph.nodes`. -fn push_node<'g>(graph: &'g mut Graph, def: &str, pos: [f32; 2]) -> (NodeId, usize, Option<&'g mut Node>) { - let id = graph.add_node(def, pos); - let index = graph.nodes.len() - 1; - (id, index, graph.nodes.last_mut()) -} - -impl<'text> Reader<'text, '_> { - /// Walk `content` and nested groups: queue graphs, load resources, note what is skipped. - fn collect_items<'a>( - &mut self, - content: XmlNode<'a, 'text>, - folder: &str, - pkg: &mut Package, - graphs: &mut Vec<(String, XmlNode<'a, 'text>)>, - linked: &dyn Fn(&str) -> Option>, - ) { - for item in content.children().filter(|c| c.is_element()) { - let identifier = child_value(item, "identifier").unwrap_or("").trim().to_string(); - let path = if folder.is_empty() { identifier.clone() } else { format!("{folder}/{identifier}") }; - - match item.tag_name().name() { - "graph" => graphs.push((path, item)), - "group" => { - if let Some(group_content) = child_element(item, "content") { - self.collect_items(group_content, &path, pkg, graphs, linked); - } - } - "resource" if pkg.resources.len() >= MAX_RESOURCES => self.warnings.add(format!("only the first {MAX_RESOURCES} resources were read")), - "resource" => self.read_resource(item, &identifier, &path, pkg, linked), - "function" => self.warnings.add(format!("function graph `{path}` is not imported yet (SBS function graphs)")), - "mdl_graph" | "mdlGraph" => self.warnings.add(format!("MDL graph `{path}` is not supported")), - other => self.warnings.add(format!("package item <{other}> `{path}` is not supported")), - } - } - } - - fn read_resource(&mut self, item: XmlNode, identifier: &str, path: &str, pkg: &mut Package, linked: &dyn Fn(&str) -> Option>) { - let kind = child_value(item, "type").unwrap_or("bitmap"); - let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase(); - let source = child_element(item, "source"); - let mut bytes: Option> = None; - let mut why_missing = String::new(); - - if let Some(embedded) = source.and_then(|s| child_element(s, "binembedded")) { - match decode_embedded(child_value(embedded, "strdata").unwrap_or("")) { - Ok(data) => bytes = Some(data), - Err(e) => why_missing = format!("its embedded data is damaged ({e})"), - } - } - - if bytes.is_none() { - let external_copy = source.and_then(|s| child_element(s, "externalcopy")).and_then(|e| child_value(e, "filename")); - for file in [external_copy, child_value(item, "filepath")].into_iter().flatten().filter(|p| !p.trim().is_empty()) { - if file.contains("://") { - why_missing = format!("it links to `{file}`, which is not available"); - continue; - } - match linked(file) { - Some(data) => { - bytes = Some(data); - break; - } - None => why_missing = format!("its file `{file}` was not found next to the package"), - } - } - } - - let taken: Vec = pkg.resources.iter().map(|r| r.name.clone()).collect(); - let name = unique_name(&taken, if identifier.is_empty() { "resource" } else { identifier }); - self.resource_names.insert(path.to_string(), name.clone()); - match bytes { - Some(data) => { - let ext = if kind == "svg" { "svg".to_string() } else { format }; - pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); - } - None => { - let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; - self.warnings.add(format!("resource `{path}` could not be loaded: {why}")); - } - } - } - - /// Split a `pkg:///path?dependency=uid` reference into the path and the dependency's file name. - fn resolve_reference(&self, url: &str) -> (String, Option) { - let url = url.trim(); - let rest = url.strip_prefix("pkg:///").or_else(|| url.strip_prefix("pkg://")).unwrap_or(url); - let (path, query) = rest.split_once('?').unwrap_or((rest, "")); - let dependency = query.split('&').find_map(|kv| kv.strip_prefix("dependency=")).and_then(|uid| self.dependencies.get(uid).cloned()); - (path.trim_matches('/').to_string(), dependency) - } - - fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph { - let mut graph = Graph::new(&name); - - // The default parent size option ("11x11", log2 sizes) - for option in child_element(element, "options").into_iter().flat_map(|o| children_named(o, "option")) { - if child_value(option, "name") == Some("defaultParentSize") - && let Some((width, height)) = child_value(option, "value").and_then(|v| v.split_once('x')) - { - let log2 = |s: &str| s.trim().parse::().unwrap_or(10).clamp(i64::from(MIN_SIZE_LOG2), i64::from(MAX_SIZE_LOG2)) as u32; - graph.size = [log2(width), log2(height)]; - } - } - - if let Some(attributes) = child_element(element, "attributes") { - let text = |tag: &str| child_value(attributes, tag).unwrap_or("").to_string(); - graph.attributes.category = text("category"); - graph.attributes.description = text("description"); - graph.attributes.author = text("author"); - graph.attributes.tags = text("tags"); - } - - let image_inputs = self.read_graph_inputs(element, &mut graph); - let outputs = read_graph_outputs(element); - - let mut read_nodes: HashMap = HashMap::new(); - let comp_nodes: Vec = child_element(element, "compNodes").into_iter().flat_map(|c| children_named(c, "compNode")).collect(); - for comp_node in &comp_nodes { - if self.node_count >= MAX_NODES { - self.warnings.add(format!("only the first {MAX_NODES} nodes were read")); - break; - } - - let Some(uid) = child_value(*comp_node, "uid").map(str::to_string) else { continue }; - if read_nodes.contains_key(&uid) { - self.warnings.add(format!("graph `{name}`: duplicate node uid {uid} skipped")); - continue; - } - - self.node_count += 1; - let node = self.read_node(&mut graph, *comp_node, &image_inputs, &outputs); - read_nodes.insert(uid, node); - } - - let wires = self.read_wires(&mut graph, &comp_nodes, &read_nodes); - connect_all(&mut graph, wires, self.warnings); - self.read_canvas_items(element, &mut graph); - graph - } - - /// Exposed value inputs go into `graph`; image inputs are returned as uid → (identifier, gray). - fn read_graph_inputs(&mut self, element: XmlNode, graph: &mut Graph) -> HashMap { - let mut image_inputs = HashMap::new(); - for input in child_element(element, "paraminputs").into_iter().flat_map(|p| children_named(p, "paraminput")) { - let id = child_value(input, "identifier").unwrap_or("input").to_string(); - let code = child_value(input, "type").and_then(|t| t.trim().parse::().ok()).unwrap_or(type_code::FLOAT1); - if code == type_code::COLOR_IMAGE || code == type_code::GRAY_IMAGE { - image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), (id, code == type_code::GRAY_IMAGE)); - continue; - } - if graph.exposed.iter().any(|e| e.id == id) { - continue; - } - - let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref()); - let label = child_element(input, "attributes").and_then(|a| child_value(a, "label")).filter(|l| !l.is_empty()).unwrap_or(&id).to_string(); - let (mut min, mut max) = (0.0, 1.0); - let widget_options = child_element(input, "defaultWidget").and_then(|w| child_element(w, "options")); - for option in widget_options.into_iter().flat_map(|o| children_named(o, "option")) { - let value = - child_value(option, "value").and_then(|v| v.split_whitespace().next()).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()); - match (child_value(option, "name"), value) { - (Some("min"), Some(v)) => min = v, - (Some("max"), Some(v)) => max = v, - _ => {} - } - } - - let group = child_value(input, "group").unwrap_or("").to_string(); - graph.exposed.push(ExposedParam { id, label, group, default, min, max, options: Vec::new() }); - } - image_inputs - } - - /// Every wire of the graph, resolved to MaterialCraft nodes and ports, in file order. - fn read_wires(&mut self, graph: &mut Graph, comp_nodes: &[XmlNode], read_nodes: &HashMap) -> Vec { - let name = graph.name.clone(); - let mut wires = Vec::new(); - - for comp_node in comp_nodes { - let Some(to) = child_value(*comp_node, "uid").and_then(|u| read_nodes.get(u)) else { continue }; - for connection in child_element(*comp_node, "connections").into_iter().flat_map(|c| children_named(c, "connection")) { - let sbs_input = child_value(connection, "identifier").unwrap_or(""); - let Some(from) = child_value(connection, "connRef").and_then(|u| read_nodes.get(u)) else { - self.warnings.add(format!("graph `{name}`: a wire from a node that is not in the file was dropped")); - continue; - }; - - let output_uid = child_value(connection, "connRefOutput").unwrap_or(""); - let from_port = from.outputs.iter().find(|(uid, _)| uid == output_uid).or(from.outputs.first()).map(|(_, port)| port.clone()); - let Some(from_port) = from_port else { - self.warnings.add(format!("graph `{name}`: a wire from a node with no outputs was dropped")); - continue; - }; - - let to_port = match to.inputs.get(sbs_input) { - Some(port) => port.clone(), - None if to.open_inputs => { - if let Some(node) = graph.nodes.get_mut(to.index) { - add_placeholder_input(node, sbs_input); - } - sbs_input.to_string() - } - None => { - let def = graph.nodes.get(to.index).map_or("", |n| n.def.as_str()); - self.warnings.add(format!("graph `{name}`: `{def}` has no input `{sbs_input}`; its wire was dropped")); - continue; - } - }; - wires.push(Connection { from: from.id, from_port, to: to.id, to_port }); - } - } - wires - } - - /// Frames and comments. - fn read_canvas_items(&mut self, element: XmlNode, graph: &mut Graph) { - for item in child_element(element, "GUIObjects").into_iter().flat_map(|o| children_named(o, "GUIObject")) { - let layout = child_element(item, "GUILayout"); - let pos = layout.and_then(|l| child_value(l, "gpos")).map(parse_floats).unwrap_or_default(); - let size = layout.and_then(|l| child_value(l, "size")).map(parse_floats).unwrap_or_default(); - let (x, y) = (pos.first().copied().unwrap_or(0.0), pos.get(1).copied().unwrap_or(0.0)); - let width = size.first().copied().unwrap_or(180.0).max(8.0); - let height = size.get(1).copied().unwrap_or(70.0).max(8.0); - let text = child_value(item, "GUIName").unwrap_or("").to_string(); - - match child_value(item, "type") { - Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { - let c = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); - let color = if c.len() >= 4 { [srgb_to_linear(c[0]), srgb_to_linear(c[1]), srgb_to_linear(c[2]), c[3]] } else { [0.2, 0.4, 0.8, 0.25] }; - let id = graph.alloc_id(); - let title = child_value(item, "title").unwrap_or("").to_string(); - graph.frames.push(Frame { id, title, description: text, rect: [x, y, width, height], color }); - } - Some("COMMENT") => { - let id = graph.alloc_id(); - graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); - } - Some(other) => self.warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), - None => {} - } - } - } - - /// Read one `compNode` into `graph`. - fn read_node( - &mut self, - graph: &mut Graph, - comp_node: XmlNode<'_, 'text>, - image_inputs: &HashMap, - outputs: &HashMap, - ) -> ReadNode { - let gpos = child_element(comp_node, "GUILayout").and_then(|l| child_value(l, "gpos")).map(parse_floats).unwrap_or_default(); - let pos = [gpos.first().copied().unwrap_or(0.0) - NODE_HALF_SIZE[0], gpos.get(1).copied().unwrap_or(0.0) - NODE_HALF_SIZE[1]]; - let output_uids: Vec<(String, bool)> = child_element(comp_node, "compOutputs") - .into_iter() - .flat_map(|o| children_named(o, "compOutput")) - .map(|o| (child_value(o, "uid").unwrap_or("").to_string(), child_value(o, "comptype") == Some("2"))) - .collect(); - let all_outputs_to = |port: &str| output_uids.iter().map(|(uid, _)| (uid.clone(), port.to_string())).collect::>(); - let text = self.text; - - let Some(implementation) = child_element(comp_node, "compImplementation").and_then(|i| i.children().find(|c| c.is_element())) else { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - fill_placeholder(node, "other", "empty node", "", None, &output_uids, None); - } - return ReadNode { id, index, inputs: HashMap::new(), outputs: Vec::new(), open_inputs: true }; - }; - - let params = child_element(implementation, "parameters"); - match implementation.tag_name().name() { - "compInputBridge" => { - let entry = child_value(implementation, "entry").unwrap_or(""); - let fallback = || ("input".to_string(), output_uids.first().is_some_and(|(_, gray)| *gray)); - let (identifier, gray) = image_inputs.get(entry).cloned().unwrap_or_else(fallback); - let (id, index, node) = push_node(graph, if gray { "input_grayscale" } else { "input_color" }, pos); - if let Some(node) = node { - node.params.insert("identifier".into(), Value::Text(identifier)); - node.base = read_base_params(params); - } - ReadNode { id, index, inputs: HashMap::new(), outputs: all_outputs_to("output"), open_inputs: false } - } - "compOutputBridge" => { - let output = child_value(implementation, "output").unwrap_or(""); - let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), usage_index("any"))); - let (id, index, node) = push_node(graph, "output", pos); - if let Some(node) = node { - node.params.insert("identifier".into(), Value::Text(identifier)); - node.params.insert("usage".into(), Value::Enum(usage)); - } - let inputs = HashMap::from([("inputNodeOutput".to_string(), "input".to_string())]); - ReadNode { id, index, inputs, outputs: Vec::new(), open_inputs: false } - } - "compFilter" => { - let filter_name = child_value(implementation, "filter").unwrap_or(""); - let graph_name = graph.name.clone(); - match filter_by_sbs_name(filter_name).filter(|f| find(f.def).is_some()) { - Some(filter) => { - let (id, index, node) = push_node(graph, filter.def, pos); - if let Some(node) = node { - self.read_filter_params(node, filter, params, &graph_name); - node.base = read_base_params(params); - } - let inputs = filter.inputs.iter().map(|(sbs, port)| (sbs.to_string(), port.to_string())).collect(); - ReadNode { id, index, inputs, outputs: all_outputs_to("output"), open_inputs: false } - } - None => { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - fill_placeholder(node, "filter", filter_name, "", params.map(|p| &text[p.range()]), &output_uids, None); - } - ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(&output_uids, None), open_inputs: true } - } - } - } - "compInstance" => self.read_instance(graph, implementation, pos, &output_uids), - other => { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - fill_placeholder(node, "other", other, "", None, &output_uids, None); - } - ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(&output_uids, None), open_inputs: true } - } - } - } - - /// An instance: of a graph in this package, of a library node MaterialCraft has, or a placeholder. - fn read_instance(&mut self, graph: &mut Graph, implementation: XmlNode<'_, 'text>, pos: [f32; 2], output_uids: &[(String, bool)]) -> ReadNode { - let graph_name = graph.name.clone(); - let (path, dependency) = self.resolve_reference(child_value(implementation, "path").unwrap_or("")); - let params = child_element(implementation, "parameters"); - let bridgings: Vec<(String, String)> = child_element(implementation, "outputBridgings") - .into_iter() - .flat_map(|b| children_named(b, "outputBridging")) - .map(|b| (child_value(b, "uid").unwrap_or("").to_string(), child_value(b, "identifier").unwrap_or("output").to_string())) - .collect(); - let instance_params = - || params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))); - - let own_graph = dependency.as_deref().is_none_or(|d| d == SELF_DEPENDENCY).then(|| self.graph_names.get(&path).cloned()).flatten(); - if let Some(sub_graph) = own_graph { - let (id, index, node) = push_node(graph, "graph_instance", pos); - if let Some(node) = node { - node.params.insert("graph".into(), Value::Text(sub_graph)); - for param in instance_params() { - if let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) { - node.params.insert(child_value(param, "name").unwrap_or("").to_string(), to_natural_value(&value)); - } - } - node.base = read_base_params(params); - } - return ReadNode { id, index, inputs: HashMap::new(), outputs: bridgings, open_inputs: true }; - } - - let short_name = path.rsplit('/').next().unwrap_or(&path).to_string(); - let library_def = find(&short_name).filter(|d| d.id != "graph_instance" && d.id != "output" && !d.id.starts_with("input_")); - let Some(def) = library_def else { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - let raw_params = params.map(|p| &self.text[p.range()]); - fill_placeholder(node, "instance", &short_name, dependency.as_deref().unwrap_or(""), raw_params, output_uids, Some(&bridgings)); - node.params.insert("sbs_path".into(), Value::Text(path)); - } - return ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(output_uids, Some(&bridgings)), open_inputs: true }; - }; - - let (id, index, node) = push_node(graph, def.id, pos); - if let Some(node) = node { - for param in instance_params() { - let param_name = child_value(param, "name").unwrap_or(""); - match def.param(param_name) { - Some(param_def) => self.set_param(node, param_name, ¶m_def.default, param_def.options.len(), param, &graph_name), - None => self.warnings.add(format!("`{}`: parameter `{param_name}` has no MaterialCraft equivalent and was ignored", def.id)), - } - } - node.base = read_base_params(params); - } - - let first_output = def.outputs.first().map_or("output", |o| o.id).to_string(); - let port_for = |identifier: &str| if def.output_index(identifier).is_some() { identifier.to_string() } else { first_output.clone() }; - let unbridged = output_uids.iter().filter(|(uid, _)| !bridgings.iter().any(|(b, _)| b == uid)).map(|(uid, _)| (uid.clone(), first_output.clone())); - let outputs = bridgings.iter().map(|(uid, identifier)| (uid.clone(), port_for(identifier))).chain(unbridged).collect(); - let inputs = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect(); - ReadNode { id, index, inputs, outputs, open_inputs: false } - } - - /// Set MaterialCraft parameter `id` (default `like`) from the SBS `` element `param`. - fn set_param(&mut self, node: &mut Node, id: &str, like: &Value, options: usize, param: XmlNode, graph_name: &str) { - let Some(param_value) = child_element(param, "paramValue") else { return }; - - if let Some(value) = sbs_constant(param_value) { - match to_param_value(like, &value, options) { - Some(value) => { - node.params.insert(id.to_string(), value); - } - None => self.warnings.add(format!("`{}`: parameter `{id}` has a value type MaterialCraft can't read yet; kept the default", node.def)), - } - return; - } - - // A parameter linked to a graph input is a function of one `get_*` node naming it - let Some(dynamic) = child_element(param_value, "dynamicValue") else { return }; - let function_nodes: Vec = child_element(dynamic, "paramNodes").into_iter().flat_map(|p| children_named(p, "paramNode")).collect(); - if let [only] = function_nodes.as_slice() - && child_value(*only, "function").is_some_and(|f| f.starts_with("get_")) - && let Some(input) = only.descendants().find(|c| c.tag_name().name() == "constantValueString").and_then(|c| c.attribute("v")) - { - node.bindings.insert(id.to_string(), input.to_string()); - return; - } - self.warnings.add(format!("graph `{graph_name}`: `{}` parameter `{id}` is driven by a function; imported its default", node.def)); - } - - fn read_filter_params(&mut self, node: &mut Node, filter: &FilterMap, params: Option, graph_name: &str) { - let Some(def) = find(filter.def) else { return }; - - let filter_params: Vec = - params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))).collect(); - for param in &filter_params { - let param_name = child_value(*param, "name").unwrap_or(""); - let value = child_element(*param, "paramValue").and_then(sbs_constant); - - if let Some(&(_, mc_name, conversion)) = filter.params.iter().find(|(sbs, _, _)| *sbs == param_name) { - let Some(param_def) = def.param(mc_name) else { continue }; - - match (conversion, value) { - (TrueIsFirstOption, Some(v)) => { - node.params.insert(mc_name.into(), Value::Enum(if v.truthy() { 0 } else { 1 })); - } - (TrueIsFirstOption, None) => {} - (ByType, _) => self.set_param(node, mc_name, ¶m_def.default, param_def.options.len(), *param, graph_name), - } - continue; - } - - match (filter.sbs, param_name, value) { - ("bitmap", "bitmapresourcepath", Some(SbsValue::Text(url))) => { - let (path, _) = self.resolve_reference(&url); - match self.resource_names.get(&path) { - Some(name) => { - node.params.insert("resource".into(), Value::Text(name.clone())); - } - None => self.warnings.add(format!("graph `{graph_name}`: Bitmap uses resource `{path}`, which is not in the package")), - } - } - ("grayscaleconversion", "channelsweights", Some(weights)) => { - for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() { - node.params.insert(channel.into(), Value::Float(weights.float(i))); - } - } - ("transformation", "matrix22", Some(matrix)) => { - let (a, b, c, d) = (matrix.float(0), matrix.float(1), matrix.float(2), matrix.float(3)); - let (scale_x, scale_y) = ((a * a + c * c).sqrt(), (b * b + d * d).sqrt()); - if scale_x > 1e-6 && scale_y > 1e-6 { - node.params.insert("scale".into(), Value::Float2([scale_x, scale_y])); - node.params.insert("rotation".into(), Value::Float(c.atan2(a) / std::f32::consts::TAU)); - } - } - _ if HANDLED_PARAMS.contains(&(filter.sbs, param_name)) => {} - _ => self.warnings.add(format!("`{}`: SBS parameter `{param_name}` is not supported yet and was ignored", filter.def)), - } - } - - let not_imported = match filter.sbs { - "curve" => Some("curve points"), - "gradient" => Some("gradient keys"), - "pixelprocessor" | "valueprocessor" => Some("function graph"), - "svg" => Some("vector shapes"), - "fxmaps" => Some("pattern settings"), - _ => None, - }; - if let Some(what) = not_imported - && !filter_params.is_empty() - { - self.warnings.add(format!("graph `{graph_name}`: the {what} of `{}` nodes are not imported yet; they use MaterialCraft's defaults", filter.def)); - } - } -} - -/// Graph outputs as uid → (identifier, usage index). -fn read_graph_outputs(element: XmlNode) -> HashMap { - let mut outputs = HashMap::new(); - for output in child_element(element, "graphOutputs").into_iter().flat_map(|o| children_named(o, "graphoutput")) { - let identifier = child_value(output, "identifier").unwrap_or("output").to_string(); - let usage = child_element(output, "usages") - .and_then(|u| child_element(u, "usage")) - .and_then(|u| child_value(u, "name")) - .map_or(usage_index("any"), usage_index); - outputs.insert(child_value(output, "uid").unwrap_or("").to_string(), (identifier, usage)); - } - outputs -} - -/// Output size, format and random seed. -fn read_base_params(params: Option) -> BaseParams { - let mut base = BaseParams::default(); - for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) { - let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::().ok()).unwrap_or(1); - let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue }; - - match child_value(param, "name") { - Some("outputsize") => { - base.size_mode = match relative_to { - 0 => SizeMode::Absolute, - 2 => SizeMode::RelativeToParent, - _ => SizeMode::RelativeToInput, - }; - let limit = |log2: i32| log2.clamp(-(MAX_SIZE_LOG2 as i32), MAX_SIZE_LOG2 as i32); - base.size = [limit(value.int(0)), limit(value.int(1))]; - } - Some("format") if relative_to == 0 => { - base.format = match value.int(0) { - 0 => OutputFormat::U8, - 1 => OutputFormat::U16, - 2 => OutputFormat::F16, - 3 => OutputFormat::F32, - _ => OutputFormat::Inherit, - } - } - Some("randomseed") if relative_to == 0 => base.seed = value.int(0), - _ => {} - } - } - base -} - -/// Connect `wires` in one pass: the last wire into an input wins, and wires that would close a cycle are dropped. -fn connect_all(graph: &mut Graph, wires: Vec, warnings: &mut Warnings) { - let graph_name = graph.name.clone(); - let cycle_warning = || format!("graph `{graph_name}`: a wire that would make a cycle was dropped"); - - let mut last_into_input: HashMap<(NodeId, String), usize> = HashMap::new(); - let mut kept: Vec> = Vec::with_capacity(wires.len()); - for wire in wires { - if wire.from == wire.to { - warnings.add(cycle_warning()); - continue; - } - if let Some(previous) = last_into_input.insert((wire.to, wire.to_port.clone()), kept.len()) - && let Some(slot) = kept.get_mut(previous) - { - *slot = None; - } - kept.push(Some(wire)); - } - let wires: Vec = kept.into_iter().flatten().collect(); - - // Kahn's algorithm: nodes it can't order lie on or after a cycle - let mut in_degree: HashMap = HashMap::new(); - let mut downstream: HashMap> = HashMap::new(); - for wire in &wires { - *in_degree.entry(wire.to).or_default() += 1; - downstream.entry(wire.from).or_default().push(wire.to); - } - let mut ready: VecDeque = graph.nodes.iter().map(|n| n.id).filter(|id| !in_degree.contains_key(id)).collect(); - let mut ordered: HashSet = HashSet::new(); - while let Some(id) = ready.pop_front() { - ordered.insert(id); - for next in downstream.get(&id).into_iter().flatten() { - if let Some(degree) = in_degree.get_mut(next) { - *degree -= 1; - if *degree == 0 { - ready.push_back(*next); - } - } - } - } - - // Wires among unordered nodes go through the cycle-checked path, one at a time - let (safe, risky): (Vec, Vec) = wires.into_iter().partition(|w| ordered.contains(&w.from) || ordered.contains(&w.to)); - graph.connections = safe; - for wire in risky { - if graph.connect(wire.from, &wire.from_port, wire.to, &wire.to_port).is_err() { - warnings.add(cycle_warning()); - } - } -} - -/// Fill in a [`MISSING_NODE`] placeholder with what writing it back needs. -fn fill_placeholder( - node: &mut Node, - kind: &str, - name: &str, - package: &str, - raw_params: Option<&str>, - output_uids: &[(String, bool)], - bridgings: Option<&[(String, String)]>, -) { - node.label = name.to_string(); - node.params.insert("sbs_kind".into(), Value::Text(kind.into())); - node.params.insert("sbs_name".into(), Value::Text(name.into())); - if !package.is_empty() { - node.params.insert("sbs_package".into(), Value::Text(package.into())); - } - if let Some(raw) = raw_params { - node.params.insert("sbs_parameters".into(), Value::Text(raw.into())); - } - - let mut seen = BTreeSet::new(); - let outputs: Vec = placeholder_outputs(output_uids, bridgings) - .into_iter() - .filter(|(_, port)| seen.insert(port.clone())) - .map(|(uid, port)| if output_uids.iter().any(|(u, gray)| *u == uid && *gray) { format!("{port}:gray") } else { port }) - .collect(); - node.params.insert("outputs".into(), Value::Text(outputs.join(","))); - node.params.insert("inputs".into(), Value::Text(String::new())); -} - -/// (Output uid, port) of a placeholder in output order: the instance's bridgings, else `output`, `output_2`… -fn placeholder_outputs(output_uids: &[(String, bool)], bridgings: Option<&[(String, String)]>) -> Vec<(String, String)> { - let bridged = |uid: &str| bridgings.and_then(|b| b.iter().find(|(u, _)| u == uid)).map(|(_, identifier)| identifier.clone()); - let mut outputs: Vec<(String, String)> = output_uids - .iter() - .enumerate() - .map(|(i, (uid, _))| (uid.clone(), bridged(uid).unwrap_or_else(|| if i == 0 { "output".to_string() } else { format!("output_{}", i + 1) }))) - .collect(); - - for (uid, identifier) in bridgings.unwrap_or_default() { - if !outputs.iter().any(|(u, _)| u == uid) { - outputs.push((uid.clone(), identifier.clone())); - } - } - outputs -} - -/// Record a wire arriving at placeholder input `port`. -fn add_placeholder_input(node: &mut Node, port: &str) { - if port.is_empty() || port.contains(',') { - return; - } - - let (mut inputs, _) = missing_ports(node); - if !inputs.iter().any(|p| p == port) { - inputs.push(port.to_string()); - node.params.insert("inputs".into(), Value::Text(inputs.join(","))); - } -} - -// --------------------------------------------------------------------------------------------- -// Writing -// --------------------------------------------------------------------------------------------- - -/// Write `pkg` as an SBS package (UTF-8 XML) with bitmaps embedded and MaterialCraft's exact copy at the end. -pub fn write_sbs(pkg: &Package) -> Result> { - let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; - let self_uid = writer.next_uid(); - let library_uid = writer.next_uid(); - - let mut content = String::from(""); - for graph in &pkg.graphs { - writer.write_graph(&mut content, pkg, graph, self_uid, library_uid); - } - if !pkg.resources.is_empty() { - let _ = write!(content, "", writer.next_uid()); - for resource in &pkg.resources { - let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); - let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); - let _ = write!( - content, - "", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - resource.bytes.len(), - encode_embedded(resource.bytes.as_slice())? - ); - } - content.push_str(""); - } - content.push_str(""); - - let mut out = String::with_capacity(content.len() + 4096); - let _ = write!( - out, - "", - xml_escape(&pkg.name) - ); - let write_dependency = |out: &mut String, file: &str, uid: u64| { - let _ = write!( - out, - "", - xml_escape(file) - ); - }; - write_dependency(&mut out, SELF_DEPENDENCY, self_uid); - write_dependency(&mut out, LIBRARY_DEPENDENCY, library_uid); - for (file, uid) in &writer.external_packages { - write_dependency(&mut out, file, *uid); - } - out.push_str(""); - out.push_str(&content); - - // The exact copy; resource bytes live in the resources above - let json = serde_json::to_vec(pkg).map_err(|e| FormatError::Io(e.to_string()))?; - let hash = content_hash(content.as_bytes()); - let _ = write!(out, "", encode_embedded(&json)?); - out.push_str("\n"); - Ok(out.into_bytes()) -} - -struct SbsWriter { - last_uid: u64, - /// Packages placeholders come from: file name → dependency uid. - external_packages: BTreeMap, -} - -/// An output port's SBS type: 1 color, 2 grayscale. -fn sbs_output_type(kind: PortKind) -> u8 { - if kind == PortKind::Gray { 2 } else { 1 } -} - -/// Text parameter `key` of `node`, or `default` when unset or empty. -fn text_param(node: &Node, key: &str, default: &str) -> String { - match node.params.get(key) { - Some(Value::Text(s)) if !s.is_empty() => s.clone(), - _ => default.to_string(), - } -} - -/// A node's output ports as (port, SBS type, uid). -type WrittenOutputs = Vec<(String, u8, u64)>; - -impl SbsWriter { - fn next_uid(&mut self) -> u64 { - self.last_uid = self.last_uid.saturating_add(1); - self.last_uid - } - - fn external_package_uid(&mut self, file: &str) -> u64 { - if let Some(uid) = self.external_packages.get(file) { - return *uid; - } - - let uid = self.next_uid(); - self.external_packages.insert(file.to_string(), uid); - uid - } - - /// The output ports of `node` as (port, SBS type). - fn output_ports(pkg: &Package, node: &Node) -> Vec<(String, u8)> { - match node.def.as_str() { - "output" => Vec::new(), - "graph_instance" => { - let sub_graph = match node.params.get("graph") { - Some(Value::Text(name)) => pkg.graph_by_name(name).map(|(_, g)| g), - _ => None, - }; - let outputs = sub_graph.into_iter().flat_map(|g| g.nodes.iter().filter(|o| o.def == "output")); - outputs.map(|o| (text_param(o, "identifier", "output"), 1)).collect() - } - def if def == MISSING_NODE => missing_ports(node).1.into_iter().map(|(id, gray)| (id, if gray { 2 } else { 1 })).collect(), - def => match find(def) { - Some(def) => def.outputs.iter().map(|o| (o.id.to_string(), sbs_output_type(o.kind))).collect(), - None => vec![("output".into(), 1)], - }, - } - } - - fn write_graph(&mut self, out: &mut String, pkg: &Package, graph: &Graph, self_uid: u64, library_uid: u64) { - let _ = write!(out, "", xml_escape(&graph.name), self.next_uid()); - let attributes = &graph.attributes; - if !(attributes.category.is_empty() && attributes.description.is_empty() && attributes.author.is_empty() && attributes.tags.is_empty()) { - let _ = write!( - out, - "", - xml_escape(&attributes.category), - xml_escape(&attributes.description), - xml_escape(&attributes.author), - xml_escape(&attributes.tags) - ); - } - - let mut node_uids: HashMap = HashMap::new(); - let mut node_outputs: HashMap = HashMap::new(); - for node in &graph.nodes { - node_uids.insert(node.id, self.next_uid()); - let outputs = Self::output_ports(pkg, node).into_iter().map(|(port, kind)| (port, kind, self.next_uid())).collect(); - node_outputs.insert(node.id, outputs); - } - - let input_entries = self.write_graph_inputs(out, graph); - let output_uids = self.write_graph_outputs(out, graph); - - let mut wires_into: HashMap> = HashMap::new(); - for wire in &graph.connections { - wires_into.entry(wire.to).or_default().push(wire); - } - out.push_str(""); - for node in &graph.nodes { - let uid = node_uids.get(&node.id).copied().unwrap_or(0); - let (x, y) = (node.pos[0] + NODE_HALF_SIZE[0], node.pos[1] + NODE_HALF_SIZE[1]); - let _ = write!(out, "", format_float(x), format_float(y)); - - let outputs = node_outputs.get(&node.id).map_or(&[][..], Vec::as_slice); - if !outputs.is_empty() { - out.push_str(""); - for (_, kind, output_uid) in outputs { - let _ = write!(out, ""); - } - out.push_str(""); - } - - let filter = filter_by_def(&node.def); - let wires = wires_into.get(&node.id).map_or(&[][..], Vec::as_slice); - if !wires.is_empty() { - out.push_str(""); - for wire in wires { - let Some(from_uid) = node_uids.get(&wire.from) else { continue }; - let Some((_, _, output_uid)) = node_outputs.get(&wire.from).and_then(|o| o.iter().find(|(port, _, _)| *port == wire.from_port)) else { - continue; - }; - - let identifier = if node.def == "output" { - "inputNodeOutput".to_string() - } else { - let mapped = filter.and_then(|f| f.inputs.iter().find(|(_, port)| *port == wire.to_port)); - mapped.map_or(wire.to_port.clone(), |(sbs, _)| sbs.to_string()) - }; - let _ = write!( - out, - "", - xml_escape(&identifier) - ); - } - out.push_str(""); - } - - out.push_str(""); - let ids = NodeUids { input_entry: input_entries.get(&node.id).copied(), graph_output: output_uids.get(&node.id).copied(), self_uid, library_uid }; - self.write_implementation(out, node, outputs, ids); - out.push_str(""); - } - out.push_str(""); - - write_canvas_items(out, graph, self); - let [width, height] = graph.size.map(|s| s.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)); - let _ = write!(out, ""); - for uid in graph.nodes.iter().filter_map(|n| output_uids.get(&n.id)) { - let _ = write!(out, ""); - } - out.push_str(""); - } - - /// Image inputs (input nodes) and exposed values; returns input node → paraminput uid. - fn write_graph_inputs(&mut self, out: &mut String, graph: &Graph) -> HashMap { - let mut entries = HashMap::new(); - out.push_str(""); - - for node in graph.nodes.iter().filter(|n| n.def == "input_color" || n.def == "input_grayscale") { - let uid = self.next_uid(); - entries.insert(node.id, uid); - let default = match node.params.get("default") { - Some(color @ Value::Color(_)) => constant_xml(color).unwrap_or_default(), - _ => "".into(), - }; - let code = if node.def == "input_grayscale" { type_code::GRAY_IMAGE } else { type_code::COLOR_IMAGE }; - let _ = write!( - out, - "{default}", - xml_escape(&text_param(node, "identifier", "input")) - ); - } - - for exposed in &graph.exposed { - let default = constant_xml(&exposed.default).unwrap_or_else(|| "".into()); - let group = if exposed.group.is_empty() { String::new() } else { format!("", xml_escape(&exposed.group)) }; - let _ = write!( - out, - "{default}{group}", - xml_escape(&exposed.id), - self.next_uid(), - xml_escape(&exposed.label), - exposed_type_code(&exposed.default), - format_float(exposed.min), - format_float(exposed.max) - ); - } - - out.push_str(""); - entries - } - - /// Graph outputs (output nodes); returns output node → graphoutput uid. - fn write_graph_outputs(&mut self, out: &mut String, graph: &Graph) -> HashMap { - let mut output_uids = HashMap::new(); - out.push_str(""); - - for node in graph.nodes.iter().filter(|n| n.def == "output") { - let uid = self.next_uid(); - output_uids.insert(node.id, uid); - let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0).max(0) as u32; - let identifier = text_param(node, "identifier", "output"); - let label = if node.label.is_empty() { identifier.clone() } else { node.label.clone() }; - let _ = write!( - out, - "", - xml_escape(&identifier), - xml_escape(&label), - usage_name(usage) - ); - } - - out.push_str(""); - output_uids - } - - /// The `compImplementation` body of `node`. - fn write_implementation(&mut self, out: &mut String, node: &Node, outputs: &[(String, u8, u64)], ids: NodeUids) { - let base = base_params_xml(&node.base); - - match node.def.as_str() { - "output" => { - let _ = write!(out, "", ids.graph_output.unwrap_or(0)); - } - "input_color" | "input_grayscale" => { - let _ = write!(out, "{base}", ids.input_entry.unwrap_or(0)); - } - "graph_instance" => { - let sub_graph = text_param(node, "graph", ""); - let params: String = node.params.iter().filter(|(k, _)| *k != "graph").filter_map(|(k, v)| param_xml(k, v)).collect(); - let _ = write!( - out, - "{base}{params}", - xml_escape(&sub_graph), - ids.self_uid - ); - write_bridgings(out, outputs); - out.push_str(""); - } - def if def == MISSING_NODE => { - let name = text_param(node, "sbs_name", &node.label); - let raw_params = match node.params.get("sbs_parameters") { - Some(Value::Text(s)) if is_parameters_element(s) => s.clone(), - _ => "".into(), - }; - if text_param(node, "sbs_kind", "instance") == "filter" { - let _ = write!(out, "{raw_params}", xml_escape(&name)); - return; - } - - let package = text_param(node, "sbs_package", ""); - let dependency = if package.is_empty() { ids.library_uid } else { self.external_package_uid(&package) }; - let path = text_param(node, "sbs_path", &name); - let _ = write!(out, "{raw_params}", xml_escape(&path)); - write_bridgings(out, outputs); - out.push_str(""); - } - def => match (filter_by_def(def), find(def)) { - (Some(filter), Some(catalog_def)) => { - let _ = write!(out, "{base}", filter.sbs); - let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default)); - for (sbs_name, mc_name, conversion) in filter.params { - let Some(value) = value_of(mc_name) else { continue }; - let value = if *conversion == TrueIsFirstOption { Value::Bool(value.as_i32() == Some(0)) } else { value.clone() }; - out.push_str(¶m_xml(sbs_name, &value).unwrap_or_default()); - } - out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid)); - out.push_str(""); - } - _ => { - let params: String = node.params.iter().filter_map(|(k, v)| param_xml(k, v)).collect(); - let _ = write!( - out, - "{base}{params}", - xml_escape(def), - ids.library_uid - ); - write_bridgings(out, outputs); - out.push_str(""); - } - }, - } - } -} - -/// The uids a node's implementation refers to. -#[derive(Clone, Copy)] -struct NodeUids { - input_entry: Option, - graph_output: Option, - self_uid: u64, - library_uid: u64, -} - -/// Filter parameters that don't map one to one: the bitmap path, grayscale weights, the 2×2 matrix. -fn special_filter_params_xml<'a>(filter: &str, value_of: &dyn Fn(&str) -> Option<&'a Value>, self_uid: u64) -> String { - match filter { - "bitmap" => match value_of("resource") { - Some(Value::Text(name)) if !name.is_empty() => { - param_xml("bitmapresourcepath", &Value::Text(format!("pkg:///Resources/{name}?dependency={self_uid}"))).unwrap_or_default() - } - _ => String::new(), - }, - "grayscaleconversion" => { - let weight = |channel: &str| value_of(channel).and_then(Value::as_f32).unwrap_or(0.0); - param_xml("channelsweights", &Value::Float4([weight("red"), weight("green"), weight("blue"), weight("alpha")])).unwrap_or_default() - } - "transformation" => { - let scale = match value_of("scale") { - Some(Value::Float2(s)) => *s, - _ => [1.0, 1.0], - }; - let (sin, cos) = (value_of("rotation").and_then(Value::as_f32).unwrap_or(0.0) * std::f32::consts::TAU).sin_cos(); - param_xml("matrix22", &Value::Float4([scale[0] * cos, -scale[1] * sin, scale[0] * sin, scale[1] * cos])).unwrap_or_default() - } - _ => String::new(), - } -} - -/// Frames (framed comments) and comments. -fn write_canvas_items(out: &mut String, graph: &Graph, writer: &mut SbsWriter) { - out.push_str(""); - - for frame in &graph.frames { - let [x, y, width, height] = frame.rect.map(format_float); - let [r, g, b] = [0, 1, 2].map(|i| format_float(linear_to_srgb(frame.color[i]))); - let _ = write!( - out, - "<frameColor v=\"{r} {g} {b} {}\"/><isTitleVisible v=\"1\"/><isFrameVisible v=\"1\"/></GUIObject>", - xml_escape(&frame.description), - writer.next_uid(), - xml_escape(&frame.title), - format_float(frame.color[3]) - ); - } - - for comment in &graph.comments { - let [x, y] = comment.pos.map(format_float); - let [width, height] = comment.size.map(format_float); - let _ = write!( - out, - "<GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"{x} {y} 0\"/><size v=\"{width} {height}\"/></GUILayout><GUIName v=\"{}\"/><uid v=\"{}\"/><isFrameVisible v=\"0\"/></GUIObject>", - xml_escape(&comment.text), - writer.next_uid() - ); - } - - out.push_str("</GUIObjects>"); -} - -fn write_bridgings(out: &mut String, outputs: &[(String, u8, u64)]) { - out.push_str("<outputBridgings>"); - for (port, _, uid) in outputs { - let _ = write!(out, "<outputBridging><uid v=\"{uid}\"/><identifier v=\"{}\"/></outputBridging>", xml_escape(port)); - } - out.push_str("</outputBridgings>"); -} - -/// One `<parameter>` element (`None` for values SBS constants can't hold). -fn param_xml(name: &str, value: &Value) -> Option<String> { - Some(format!("<parameter><name v=\"{}\"/><relativeTo v=\"0\"/><paramValue>{}</paramValue></parameter>", xml_escape(name), constant_xml(value)?)) -} - -fn base_params_xml(base: &BaseParams) -> String { - let mut out = String::new(); - - if base.size_mode != SizeMode::RelativeToInput || base.size != [0, 0] { - let relative_to = match base.size_mode { - SizeMode::Absolute => 0, - SizeMode::RelativeToInput => 1, - SizeMode::RelativeToParent => 2, - }; - let [width, height] = base.size; - let _ = write!( - out, - "<parameter><name v=\"outputsize\"/><relativeTo v=\"{relative_to}\"/><paramValue><constantValueInt2 v=\"{width} {height}\"/></paramValue></parameter>" - ); - } - - let format = match base.format { - OutputFormat::Inherit => None, - OutputFormat::U8 => Some(0), - OutputFormat::U16 => Some(1), - OutputFormat::F16 => Some(2), - OutputFormat::F32 => Some(3), - }; - if let Some(format) = format { - let _ = write!(out, "<parameter><name v=\"format\"/><relativeTo v=\"0\"/><paramValue><constantValueInt1 v=\"{format}\"/></paramValue></parameter>"); - } - - if base.seed != 0 { - let _ = write!( - out, - "<parameter><name v=\"randomseed\"/><relativeTo v=\"0\"/><paramValue><constantValueInt1 v=\"{}\"/></paramValue></parameter>", - base.seed - ); - } - out -} - -/// Whether `xml` is one well-formed `<parameters>` element, the raw SBS a placeholder keeps. -fn is_parameters_element(xml: &str) -> bool { - let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1_000_000 }; - xml.len() < (16 << 20) && roxmltree::Document::parse_with_options(xml, options).is_ok_and(|d| d.root_element().tag_name().name() == "parameters") -} - -#[cfg(test)] -mod tests { - use super::*; - use materialcraft_core::Graph; - - fn no_linked_files(_: &str) -> Option<Vec<u8>> { - None - } - - /// The SBS data of a written package without the exact copy, as another program would leave it. - fn without_exact_copy(bytes: &[u8]) -> String { - let text = String::from_utf8(bytes.to_vec()).unwrap(); - format!("{}</package>", &text[..text.find("<!--").unwrap()]) - } - - fn sample_package() -> Package { - let mut pkg = Package::new("Bricks"); - let mut graph = Graph::new("Wall"); - graph.size = [9, 9]; - - let bricks = graph.add_node("brick_generator", [0.0, 0.0]); - let blur = graph.add_node("blur", [150.0, 0.0]); - let uniform = graph.add_node("uniform", [0.0, 150.0]); - let blend = graph.add_node("blend", [300.0, 0.0]); - let output = graph.add_node("output", [450.0, 0.0]); - graph.connect(bricks, "output", blur, "input").unwrap(); - graph.connect(blur, "output", blend, "foreground").unwrap(); - graph.connect(uniform, "output", blend, "background").unwrap(); - graph.connect(blend, "output", output, "input").unwrap(); - - let blur_node = graph.node_mut(blur).unwrap(); - blur_node.params.insert("intensity".into(), Value::Float(4.5)); - blur_node.base.size_mode = SizeMode::Absolute; - blur_node.base.size = [8, 8]; - graph.node_mut(uniform).unwrap().params.insert("color".into(), Value::Color([0.25, 0.5, 0.75, 1.0])); - graph.node_mut(blend).unwrap().params.insert("mode".into(), Value::Enum(3)); - let output_node = graph.node_mut(output).unwrap(); - output_node.params.insert("usage".into(), Value::Enum(4)); - output_node.params.insert("identifier".into(), Value::Text("height".into())); - // Only the exact copy can carry a curve - graph.node_mut(bricks).unwrap().params.insert("curvy".into(), Value::Curve(materialcraft_core::Curve::default())); - graph.frames.push(Frame { - id: 90, - title: "Frame & <title>".into(), - description: "note".into(), - rect: [-10.0, -10.0, 300.0, 200.0], - color: [0.1, 0.2, 0.3, 0.4], - }); - 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 png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); - pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); - pkg - } - - #[test] - fn sniffs_sbs() { - assert!(is_sbs(b"<?xml version=\"1.0\"?>\n<package><content/></package>")); - assert!(is_sbs(b"\xef\xbb\xbf<package>")); - assert!(is_sbs(b"<!-- hi --><package >")); - assert!(!is_sbs(b"<packages>")); - assert!(!is_sbs(b"PK\x03\x04zip")); - assert!(!is_sbs(b"<?xml")); - assert!(!is_sbs(b"")); - } - - #[test] - fn exact_round_trip() { - let pkg = sample_package(); - let bytes = write_sbs(&pkg).unwrap(); - assert!(is_sbs(&bytes)); - - let read = read_sbs(&bytes, "Bricks.sbs", &no_linked_files).unwrap(); - assert!(read.exact, "{:?}", read.warnings); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_eq!(read.pkg.graphs, pkg.graphs); - assert_eq!(read.pkg.resources[0].bytes, pkg.resources[0].bytes); - assert_eq!(read.pkg.name, "Bricks"); - } - - /// The SBS data alone carries the graph. - #[test] - fn structural_round_trip() { - let pkg = sample_package(); - let plain = without_exact_copy(&write_sbs(&pkg).unwrap()); - let read = read_sbs(plain.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - assert!(!read.exact); - - let (original, back) = (&pkg.graphs[0], &read.pkg.graphs[0]); - assert_eq!(back.name, "Wall"); - assert_eq!(back.size, [9, 9]); - assert_eq!(back.nodes.len(), original.nodes.len()); - assert_eq!(back.connections.len(), original.connections.len()); - for (a, b) in original.nodes.iter().zip(&back.nodes) { - assert_eq!(a.def, b.def); - assert!((a.pos[0] - b.pos[0]).abs() < 1e-3 && (a.pos[1] - b.pos[1]).abs() < 1e-3); - assert_eq!(a.base, b.base); - } - - assert_eq!(back.nodes[1].params.get("intensity"), Some(&Value::Float(4.5))); - let Some(Value::Color(color)) = back.nodes[2].params.get("color") else { panic!("uniform color") }; - assert!((color[0] - 0.25).abs() < 1e-3 && (color[2] - 0.75).abs() < 1e-3); - assert_eq!(back.nodes[3].params.get("mode"), Some(&Value::Enum(3))); - assert_eq!(back.nodes[4].params.get("usage"), Some(&Value::Enum(4))); - assert_eq!(back.nodes[4].params.get("identifier"), Some(&Value::Text("height".into()))); - assert_eq!(back.frames[0].title, "Frame & <title>"); - assert_eq!(read.pkg.resources[0].bytes, pkg.resources[0].bytes); - - let blend = back.nodes[3].id; - assert_eq!(back.input_of(blend, "foreground").map(|c| c.from), Some(back.nodes[1].id)); - assert_eq!(back.input_of(blend, "background").map(|c| c.from), Some(back.nodes[2].id)); - } - - #[test] - fn edited_file_falls_back_to_sbs_data() { - let text = String::from_utf8(write_sbs(&sample_package()).unwrap()).unwrap().replace("<identifier v=\"Wall\"/>", "<identifier v=\"Wall2\"/>"); - let read = read_sbs(text.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - - assert!(!read.exact); - assert_eq!(read.pkg.graphs[0].name, "Wall2"); - assert!(read.warnings.iter().any(|w| w.contains("changed outside")), "{:?}", read.warnings); - } - - #[test] - fn damaged_exact_copy_falls_back_with_a_warning() { - let text = String::from_utf8(write_sbs(&sample_package()).unwrap()).unwrap(); - let data_start = text.find("data=").unwrap() + "data=".len(); - let data_end = data_start + text[data_start..].find(' ').unwrap(); - let damaged = format!("{}AAAAAAAAAAAA{}", &text[..data_start], &text[data_end..]); - let read = read_sbs(damaged.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - - assert!(!read.exact); - assert_eq!(read.pkg.graphs[0].nodes.len(), 5); - assert!(read.warnings.iter().any(|w| w.contains("damaged")), "{:?}", read.warnings); - } - - #[test] - fn missing_nodes_are_placeholders_that_survive_saving() { - let xml = r#"<?xml version="1.0"?><package><identifier v="P"/><dependencies><dependency><filename v="sbs://noise_fancy.sbs"/><uid v="7"/></dependency></dependencies><content><graph><identifier v="G"/> - <compNodes> - <compNode><uid v="1"/><GUILayout><gpos v="0 0 0"/></GUILayout><compOutputs><compOutput><uid v="11"/><comptype v="2"/></compOutput></compOutputs> - <compImplementation><compInstance><path v="pkg:///fancy_noise?dependency=7"/><parameters><parameter><name v="scale"/><paramValue><constantValueFloat1 v="3"/></paramValue></parameter></parameters> - <outputBridgings><outputBridging><uid v="11"/><identifier v="noise"/></outputBridging></outputBridgings></compInstance></compImplementation></compNode> - <compNode><uid v="2"/><GUILayout><gpos v="200 0 0"/></GUILayout><compOutputs><compOutput><uid v="21"/><comptype v="1"/></compOutput></compOutputs> - <connections><connection><identifier v="input1"/><connRef v="1"/><connRefOutput v="11"/></connection></connections> - <compImplementation><compFilter><filter v="blur"/><parameters><parameter><name v="intensity"/><paramValue><constantValueFloat1 v="6"/></paramValue></parameter><parameter><name v="bogus"/><paramValue><constantValueFloat1 v="6"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode> - <compNode><uid v="3"/><GUILayout><gpos v="400 0 0"/></GUILayout><compOutputs><compOutput><uid v="31"/><comptype v="1"/></compOutput></compOutputs> - <connections><connection><identifier v="weird_in"/><connRef v="2"/><connRefOutput v="21"/></connection></connections> - <compImplementation><compFilter><filter v="futurefilter"/><parameters/></compFilter></compImplementation></compNode> - </compNodes></graph></content></package>"#; - let read = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); - let graph = &read.pkg.graphs[0]; - assert_eq!(graph.nodes.len(), 3); - assert_eq!(graph.connections.len(), 2); - - let fancy = &graph.nodes[0]; - assert_eq!(fancy.def, MISSING_NODE); - assert_eq!(fancy.label, "fancy_noise"); - assert_eq!(missing_ports(fancy).1, vec![("noise".to_string(), true)]); - assert_eq!(graph.nodes[1].params.get("intensity"), Some(&Value::Float(6.0))); - assert_eq!(graph.input_of(graph.nodes[1].id, "input").map(|c| c.from_port.as_str()), Some("noise")); - assert_eq!(missing_ports(&graph.nodes[2]).0, vec!["weird_in".to_string()]); - for expected in ["missing node `fancy_noise`", "missing node `futurefilter`", "bogus"] { - assert!(read.warnings.iter().any(|w| w.contains(expected)), "{expected}: {:?}", read.warnings); - } - - // Saved and read back from the SBS data alone, the placeholders are written as they came - let text = String::from_utf8(write_sbs(&read.pkg).unwrap()).unwrap(); - assert!(text.contains("sbs://noise_fancy.sbs")); - assert!(text.contains("pkg:///fancy_noise?dependency=")); - assert!(text.contains("<filter v=\"futurefilter\"/>")); - let back = read_sbs(without_exact_copy(text.as_bytes()).as_bytes(), "p.sbs", &no_linked_files).unwrap(); - let back_graph = &back.pkg.graphs[0]; - assert_eq!(back_graph.nodes[0].def, MISSING_NODE); - assert_eq!(back_graph.nodes[0].params.get("sbs_parameters"), fancy.params.get("sbs_parameters")); - assert_eq!(back_graph.connections.len(), 2); - } - - /// Wires are connected in one pass: the last wire into an input wins and a cycle loses one wire. - #[test] - fn wires_keep_the_last_per_input_and_drop_cycles() { - let node = |uid: u32, wires: &str| { - format!( - "<compNode><uid v=\"{uid}\"/><compOutputs><compOutput><uid v=\"{}\"/></compOutput></compOutputs><connections>{wires}</connections><compImplementation><compFilter><filter v=\"blend\"/></compFilter></compImplementation></compNode>", - uid + 100 - ) - }; - let wire = |input: &str, from: u32| { - format!("<connection><identifier v=\"{input}\"/><connRef v=\"{from}\"/><connRefOutput v=\"{}\"/></connection>", from + 100) - }; - let xml = format!( - "<package><content><graph><identifier v=\"G\"/><compNodes>{}{}{}{}</compNodes></graph></content></package>", - node(1, ""), - node(2, &format!("{}{}", wire("source", 1), wire("source", 4))), - node(3, &wire("source", 2)), - node(4, &wire("source", 3)) - ); - let read = read_sbs(xml.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - let graph = &read.pkg.graphs[0]; - - // 2 takes 4 (the last wire), which closes 2 → 3 → 4 → 2, so one wire of that loop is dropped - assert_eq!(graph.connections.len(), 2); - assert!(graph.input_of(graph.nodes[1].id, "foreground").is_none_or(|c| c.from == graph.nodes[3].id)); - assert_eq!(graph.topo_order().len(), 4); - assert!(read.warnings.iter().any(|w| w.contains("cycle")), "{:?}", read.warnings); - } - - #[test] - fn hostile_input_is_an_error_or_a_warning_never_a_panic() { - let cases: &[&str] = &[ - "", - "<package", - "<notpackage/>", - "<!DOCTYPE package [<!ENTITY x \"y\">]><package/>", - "<package><content><graph/></content></package>", - "<package><content><graph><compNodes><compNode/><compNode><uid v=\"1\"/><compImplementation><compInstance/></compImplementation></compNode><compNode><uid v=\"1\"/></compNode></compNodes></graph></content></package>", - "<package><content><graph><options><option><name v=\"defaultParentSize\"/><value v=\"99999x-4\"/></option></options><compNodes><compNode><uid v=\"1\"/><connections><connection><identifier v=\"input1\"/><connRef v=\"1\"/><connRefOutput v=\"9\"/></connection></connections><compImplementation><compFilter><filter v=\"blur\"/><parameters><parameter><name v=\"outputsize\"/><relativeTo v=\"0\"/><paramValue><constantValueInt2 v=\"99999999999 nan\"/></paramValue></parameter><parameter><name v=\"intensity\"/><paramValue><constantValueFloat1 v=\"inf\"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph></content></package>", - "<package><content><resource><identifier v=\"r\"/><source><binembedded><strdata v=\"////\"/></binembedded></source></resource><resource><identifier v=\"s\"/><source><binembedded><strdata v=\"f////w==\"/></binembedded></source></resource><resource><identifier v=\"t\"/><filepath v=\"../../etc/passwd\"/></resource></content></package>", - "<package><content/><!-- materialcraft-package version=1 hash=0 data=AAAA --></package>", - "<package><content><group><content><group><content><graph><identifier v=\"Deep\"/></graph></content></group></content></group><function><identifier v=\"f\"/></function><weird/></content></package>", - ]; - for case in cases { - if let Ok(read) = read_sbs(case.as_bytes(), "x.sbs", &no_linked_files) { - assert!(!read.pkg.graphs.is_empty(), "{case}"); - } - } - assert!(read_sbs(b"\xff\xfe", "x.sbs", &no_linked_files).is_err()); - - let nested = read_sbs(cases[9].as_bytes(), "x.sbs", &no_linked_files).unwrap(); - assert_eq!(nested.pkg.graphs[0].name, "Deep"); - let clamped = read_sbs(cases[6].as_bytes(), "x.sbs", &no_linked_files).unwrap(); - assert_eq!(clamped.pkg.graphs[0].size, [MAX_SIZE_LOG2, MIN_SIZE_LOG2]); - assert!(clamped.pkg.graphs[0].connections.is_empty(), "a self-wire is a cycle"); - } - - #[test] - fn linked_resources_load_through_the_callback() { - let xml = "<package><content><resource><identifier v=\"img\"/><type v=\"bitmap\"/><format v=\"png\"/><source><externalcopy><filename v=\"p.resources/img.png\"/></externalcopy></source></resource></content></package>"; - - let found = read_sbs(xml.as_bytes(), "p.sbs", &|path| (path == "p.resources/img.png").then(|| vec![1, 2, 3])).unwrap(); - assert_eq!(found.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]); - - let not_found = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); - assert!(not_found.pkg.resources.is_empty()); - assert!(not_found.warnings.iter().any(|w| w.contains("img")), "{:?}", not_found.warnings); - } - - #[test] - fn embedded_data_round_trips_and_checks_its_length() { - let data: Vec<u8> = (0..5000u32).map(|i| (i * 7 % 251) as u8).collect(); - let encoded = encode_embedded(&data).unwrap(); - assert_eq!(decode_embedded(&encoded).unwrap(), data); - - let mut raw = base64_engine().decode(&encoded).unwrap(); - raw[3] ^= 1; - assert!(decode_embedded(&base64_engine().encode(raw)).unwrap_err().contains("declared")); - } - - /// The sample with every node of the reference library loads softly and round-trips exactly. - #[test] - fn the_all_nodes_sample_loads_with_warnings() { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs"); - let bytes = std::fs::read(dir.join("all_nodes.sbs")).unwrap(); - assert!(is_sbs(&bytes)); - - let read = read_sbs(&bytes, "all_nodes.sbs", &|path| std::fs::read(dir.join(path)).ok()).unwrap(); - let graph = &read.pkg.graphs[0]; - let placeholders = graph.nodes.iter().filter(|n| n.def == MISSING_NODE).count(); - assert_eq!(graph.nodes.len(), 536); - assert!(graph.nodes.len() - placeholders >= 100, "{placeholders} placeholders"); - assert!(placeholders > 300, "{placeholders} placeholders"); - assert!(read.warnings.iter().any(|w| w.contains("missing node `3D_perlin_noise`")), "{:?}", &read.warnings[..5]); - assert!(read.pkg.resources.iter().any(|r| r.name == "Untitled_Bitmap" && !r.bytes.is_empty())); - let svg = read.pkg.resources.iter().find(|r| r.name == "Untitled_Vector_Graphics").unwrap(); - assert!(String::from_utf8_lossy(svg.bytes.as_slice()).contains("<svg")); - assert_eq!(graph.frames.len(), 26); - assert_eq!(graph.size, [11, 11]); - - let back = read_sbs(&write_sbs(&read.pkg).unwrap(), "x.sbs", &no_linked_files).unwrap(); - assert!(back.exact); - assert_eq!(back.pkg.graphs, read.pkg.graphs); - } -} diff --git a/crates/formats/src/sbs/base_parameters.rs b/crates/formats/src/sbs/base_parameters.rs new file mode 100644 index 00000000..812bffb1 --- /dev/null +++ b/crates/formats/src/sbs/base_parameters.rs @@ -0,0 +1,82 @@ +use super::sbs_value::sbs_constant; +use super::xml::{child_element, child_value, children_named}; +use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, SizeMode}; +use roxmltree::Node as XmlNode; +use std::fmt::Write as _; + +pub(super) fn read_base_params(params: Option<XmlNode>) -> BaseParameters { + let mut base = BaseParameters::default(); + for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) { + let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::<i32>().ok()).unwrap_or(1); + let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue }; + + match child_value(param, "name") { + Some("outputsize") => { + base.size_mode = match relative_to { + 0 => SizeMode::Absolute, + 2 => SizeMode::RelativeToParent, + _ => SizeMode::RelativeToInput, + }; + + let limit = |log2: i32| log2.clamp(-(MAX_SIZE_LOG2 as i32), MAX_SIZE_LOG2 as i32); + base.size = [limit(value.int(0)), limit(value.int(1))]; + } + Some("format") if relative_to == 0 => { + base.format = match value.int(0) { + 0 => OutputFormat::U8, + 1 => OutputFormat::U16, + 2 => OutputFormat::F16, + 3 => OutputFormat::F32, + _ => OutputFormat::Inherit, + } + } + Some("randomseed") if relative_to == 0 => base.seed = value.int(0), + Some("tiling") if relative_to == 0 => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0], + _ => {} + } + } + base +} + +pub(super) fn base_params_xml(base: &BaseParameters) -> String { + let mut out = String::new(); + + if base.size_mode != SizeMode::RelativeToInput || base.size != [0, 0] { + let relative_to = match base.size_mode { + SizeMode::Absolute => 0, + SizeMode::RelativeToInput => 1, + SizeMode::RelativeToParent => 2, + }; + + let [width, height] = base.size; + let _ = write!( + out, + "<parameter><name v=\"outputsize\"/><relativeTo v=\"{relative_to}\"/><paramValue><constantValueInt2 v=\"{width} {height}\"/></paramValue></parameter>" + ); + } + + let format = match base.format { + OutputFormat::Inherit => None, + OutputFormat::U8 => Some(0), + OutputFormat::U16 => Some(1), + OutputFormat::F16 => Some(2), + OutputFormat::F32 => Some(3), + }; + + if let Some(format) = format { + let _ = write!(out, "<parameter><name v=\"format\"/><relativeTo v=\"0\"/><paramValue><constantValueInt32 v=\"{format}\"/></paramValue></parameter>"); + } + + if base.seed != 0 { + let _ = write!( + out, + "<parameter><name v=\"randomseed\"/><relativeTo v=\"0\"/><paramValue><constantValueInt32 v=\"{}\"/></paramValue></parameter>", + base.seed + ); + } + if base.tiling != [true, true] { + let code = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1); + out.push_str(&super::node_parameter::param_xml("tiling", &materialcraft_core::Value::Int(code)).unwrap_or_default()); + } + out +} diff --git a/crates/formats/src/sbs/canvas.rs b/crates/formats/src/sbs/canvas.rs new file mode 100644 index 00000000..efb3450a --- /dev/null +++ b/crates/formats/src/sbs/canvas.rs @@ -0,0 +1,45 @@ +use super::sbs_writer::SbsWriter; +use super::xml::{format_float, xml_escape}; +use materialcraft_core::{Graph, linear_to_srgb}; +use std::fmt::Write as _; + +pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) { + output.push_str("<GUIObjects>"); + + for frame in &graph.frames { + let [x, y, width, height] = frame.rect.map(format_float); + let [red, green, blue] = [0, 1, 2].map(|channel| format_float(linear_to_srgb(frame.color[channel]))); + let _ = write!( + output, + "<GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"{x} {y} -100\"/><size v=\"{width} {height}\"/></GUILayout><GUIName v=\"{}\"/><uid v=\"{}\"/><title v=\"{}\"/><frameColor v=\"{red} {green} {blue} {}\"/><isTitleVisible v=\"{}\"/><isFrameVisible v=\"1\"/></GUIObject>", + xml_escape(&frame.description), + writer.next_uid(), + xml_escape(&frame.title), + format_float(frame.color[3]), + u8::from(frame.title_visible) + ); + } + + for comment in &graph.comments { + let [x, y] = comment.pos.map(format_float); + let [width, height] = comment.size.map(format_float); + let _ = write!( + output, + "<GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"{x} {y} 0\"/><size v=\"{width} {height}\"/></GUILayout><GUIName v=\"{}\"/><uid v=\"{}\"/><isFrameVisible v=\"0\"/></GUIObject>", + xml_escape(&comment.text), + writer.next_uid() + ); + } + + for pin in &graph.pins { + let [x, y] = pin.pos.map(format_float); + let _ = write!( + output, + "<GUIObject><type v=\"PIN\"/><GUILayout><gpos v=\"{x} {y} 0\"/></GUILayout><GUIName v=\"{}\"/><uid v=\"{}\"/></GUIObject>", + xml_escape(&pin.name), + writer.next_uid() + ); + } + + output.push_str("</GUIObjects>"); +} diff --git a/crates/formats/src/sbs/connection.rs b/crates/formats/src/sbs/connection.rs new file mode 100644 index 00000000..8178825b --- /dev/null +++ b/crates/formats/src/sbs/connection.rs @@ -0,0 +1,54 @@ +use super::warnings::Warnings; +use materialcraft_core::{Connection, Graph, NodeId}; +use std::collections::{HashMap, HashSet, VecDeque}; + +pub(super) fn connect_all(graph: &mut Graph, wires: Vec<Connection>, warnings: &mut Warnings) { + let graph_name = graph.name.clone(); + let cycle_warning = || format!("graph `{graph_name}`: a wire that would make a cycle was dropped"); + + let mut last_into_input: HashMap<(NodeId, String), usize> = HashMap::new(); + let mut kept: Vec<Option<Connection>> = Vec::with_capacity(wires.len()); + for wire in wires { + if wire.from == wire.to { + warnings.add(cycle_warning()); + continue; + } + if let Some(previous) = last_into_input.insert((wire.to, wire.to_port.clone()), kept.len()) + && let Some(slot) = kept.get_mut(previous) + { + *slot = None; + } + kept.push(Some(wire)); + } + let wires: Vec<Connection> = kept.into_iter().flatten().collect(); + + // Kahn's algorithm: nodes it can't order lie on or after a cycle + let mut in_degree: HashMap<NodeId, usize> = HashMap::new(); + let mut downstream: HashMap<NodeId, Vec<NodeId>> = HashMap::new(); + for wire in &wires { + *in_degree.entry(wire.to).or_default() += 1; + downstream.entry(wire.from).or_default().push(wire.to); + } + let mut ready: VecDeque<NodeId> = graph.nodes.iter().map(|n| n.id).filter(|id| !in_degree.contains_key(id)).collect(); + let mut ordered: HashSet<NodeId> = HashSet::new(); + while let Some(id) = ready.pop_front() { + ordered.insert(id); + for next in downstream.get(&id).into_iter().flatten() { + if let Some(degree) = in_degree.get_mut(next) { + *degree -= 1; + if *degree == 0 { + ready.push_back(*next); + } + } + } + } + + // Wires among unordered nodes go through the cycle-checked path, one at a time + let (safe, risky): (Vec<Connection>, Vec<Connection>) = wires.into_iter().partition(|w| ordered.contains(&w.from) || ordered.contains(&w.to)); + graph.connections = safe; + for wire in risky { + if graph.connect(wire.from, &wire.from_port, wire.to, &wire.to_port).is_err() { + warnings.add(cycle_warning()); + } + } +} diff --git a/crates/formats/src/sbs/constant.rs b/crates/formats/src/sbs/constant.rs new file mode 100644 index 00000000..6314e7b2 --- /dev/null +++ b/crates/formats/src/sbs/constant.rs @@ -0,0 +1,20 @@ +pub(super) const MAX_SBS_BYTES: usize = 256 << 20; + +pub(super) const MAX_EMBEDDED_BYTES: usize = 256 << 20; + +pub(super) const MAX_XML_NODES: u32 = 8_000_000; + +pub(super) const MAX_GRAPHS: usize = 4096; + +pub(super) const MAX_NODES: usize = 100_000; + +pub(super) const MAX_RESOURCES: usize = 4096; + +pub(super) const FORMAT_VERSION: &str = "1.1.0.202401"; + +pub const SBS_EXT: &str = "sbs"; +pub(super) const MAX_WARNINGS: usize = 600; +pub(super) const SNIFF_BYTES: usize = 4096; +pub(super) const SELF_DEPENDENCY: &str = "?himself"; +pub(super) const FIRST_UID: u64 = 1_000_000_000; +pub(super) const NODE_HALF_SIZE: [f32; 2] = [50.0, 40.0]; diff --git a/crates/formats/src/sbs/embedded.rs b/crates/formats/src/sbs/embedded.rs new file mode 100644 index 00000000..6e284cb8 --- /dev/null +++ b/crates/formats/src/sbs/embedded.rs @@ -0,0 +1,32 @@ +use super::constant::MAX_EMBEDDED_BYTES; +use crate::{FormatError, Result}; +use base64::Engine as _; +use std::io::{Read, Write}; + +pub(super) fn base64_engine() -> base64::engine::GeneralPurpose { + base64::engine::general_purpose::STANDARD +} +pub(super) fn decode_embedded(strdata: &str) -> std::result::Result<Vec<u8>, String> { + let raw = base64_engine().decode(strdata.split_whitespace().collect::<String>()).map_err(|e| format!("bad base64: {e}"))?; + let (length, compressed) = raw.split_at_checked(4).ok_or("too short")?; + let length = u32::from_be_bytes([length[0], length[1], length[2], length[3]]) as usize; + if length > MAX_EMBEDDED_BYTES { + return Err(format!("{length} bytes is over the {MAX_EMBEDDED_BYTES}-byte limit")); + } + + let mut out = Vec::with_capacity(length.min(1 << 24)); + let mut decoder = flate2::read::ZlibDecoder::new(compressed).take(MAX_EMBEDDED_BYTES as u64 + 1); + decoder.read_to_end(&mut out).map_err(|e| format!("bad compressed data: {e}"))?; + if out.len() != length { + return Err(format!("{} bytes where {length} were declared", out.len())); + } + Ok(out) +} + +pub(super) fn encode_embedded(bytes: &[u8]) -> Result<String> { + let length = u32::try_from(bytes.len()).map_err(|_| FormatError::Io("resource too large".into()))?; + let mut encoder = flate2::write::ZlibEncoder::new(length.to_be_bytes().to_vec(), flate2::Compression::default()); + encoder.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?; + let raw = encoder.finish().map_err(|e| FormatError::Io(e.to_string()))?; + Ok(base64_engine().encode(raw)) +} diff --git a/crates/formats/src/sbs/filter_map.rs b/crates/formats/src/sbs/filter_map.rs new file mode 100644 index 00000000..3a87b7f0 --- /dev/null +++ b/crates/formats/src/sbs/filter_map.rs @@ -0,0 +1,125 @@ +pub(super) struct FilterMap { + pub(super) sbs: &'static str, + pub(super) def: &'static str, + pub(super) inputs: &'static [(&'static str, &'static str)], + pub(super) params: &'static [(&'static str, &'static str)], +} + +pub(super) const FILTERS: &[FilterMap] = &[ + FilterMap { sbs: "motionblur", def: "motion_blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity"), ("shiftangle", "shiftangle")] }, + FilterMap { sbs: "uniform", def: "uniform", inputs: &[], params: &[("outputcolor", "color"), ("colorswitch", "color_mode")] }, + FilterMap { + sbs: "blend", + def: "blend", + inputs: &[("source", "foreground"), ("destination", "background"), ("opacity", "mask")], + params: &[("blendingmode", "mode"), ("opacitymult", "opacity"), ("alphablending", "alpha")], + }, + FilterMap { sbs: "blur", def: "blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity")] }, + FilterMap { + sbs: "shuffle", + def: "channels_shuffle", + inputs: &[("input1", "input1"), ("input2", "input2")], + params: &[("channelred", "red"), ("channelgreen", "green"), ("channelblue", "blue"), ("channelalpha", "alpha")], + }, + FilterMap { sbs: "curve", def: "curve", inputs: &[("input1", "input")], params: &[] }, + FilterMap { sbs: "dirmotionblur", def: "directional_blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity"), ("mblurangle", "angle")] }, + FilterMap { + sbs: "directionalwarp", + def: "directional_warp", + inputs: &[("input1", "input"), ("inputintensity", "intensity_input")], + params: &[("intensity", "intensity"), ("warpangle", "angle")], + }, + FilterMap { + sbs: "distance", + def: "distance", + inputs: &[("mask", "mask"), ("source", "source")], + params: &[("distance", "distance"), ("combinedistance", "combine")], + }, + FilterMap { + sbs: "emboss", + def: "emboss", + inputs: &[("input1", "input"), ("inputgradient", "height")], + params: &[("intensity", "intensity"), ("lightangle", "light_angle"), ("highlightcolor", "highlight"), ("shadowcolor", "shadow")], + }, + FilterMap { + sbs: "dyngradient", + def: "gradient_dynamic", + inputs: &[("input1", "input"), ("input2", "gradient"), ("inputgradient", "gradient")], + params: &[("position", "position"), ("orientation", "orientation")], + }, + FilterMap { sbs: "gradient", def: "gradient_map", inputs: &[("input1", "input")], params: &[("colorswitch", "color_mode")] }, + FilterMap { + sbs: "grayscaleconversion", + def: "grayscale_conversion", + inputs: &[("input1", "input")], + params: &[("alphamult", "flatten_alpha"), ("mattelevel", "matte")], + }, + FilterMap { sbs: "hsl", def: "hsl", inputs: &[("input1", "input")], params: &[("hue", "hue"), ("saturation", "saturation"), ("luminance", "lightness")] }, + FilterMap { sbs: "bitmap", def: "bitmap", inputs: &[], params: &[("colorswitch", "color_mode")] }, + FilterMap { + sbs: "levels", + def: "levels", + inputs: &[("input1", "input")], + params: &[("levelinlow", "in_low"), ("levelinmid", "in_mid"), ("levelinhigh", "in_high"), ("leveloutlow", "out_low"), ("levelouthigh", "out_high")], + }, + FilterMap { + sbs: "normal", + def: "normal", + inputs: &[("input1", "input")], + params: &[("intensity", "intensity"), ("inversedy", "opengl"), ("input2alpha", "height_alpha")], + }, + FilterMap { + sbs: "pixelprocessor", + def: "pixel_processor", + inputs: &[("input", "input0")], + params: &[("perpixel", "function"), ("colorswitch", "color_mode")], + }, + FilterMap { sbs: "valueprocessor", def: "value_processor", inputs: &[("input", "input0")], params: &[("function", "function")] }, + FilterMap { sbs: "sharpen", def: "sharpen", inputs: &[("input1", "input")], params: &[("intensity", "intensity")] }, + FilterMap { + sbs: "transformation", + def: "transformation", + inputs: &[("input1", "input")], + params: &[("offset", "offset"), ("mattecolor", "matte"), ("matrix22", "matrix"), ("filtering", "filtering")], + }, + FilterMap { sbs: "warp", def: "warp", inputs: &[("input1", "input"), ("inputgradient", "gradient")], params: &[("intensity", "intensity")] }, + FilterMap { sbs: "passthrough", def: "dot", inputs: &[("input", "input"), ("input1", "input")], params: &[] }, + FilterMap { + sbs: "text", + def: "text", + inputs: &[("background", "background")], + params: &[ + ("colorswitch", "color_mode"), + ("background", "background"), + ("text", "text"), + ("fontdata", "fontdata"), + ("fontsize", "fontsize"), + ("alignment", "alignment"), + ("position", "position"), + ("matrix22", "matrix"), + ], + }, + FilterMap { sbs: "svg", def: "svg", inputs: &[("background", "background")], params: &[("colorswitch", "color_mode"), ("background", "background")] }, + FilterMap { + sbs: "fxmaps", + def: "fx_map", + inputs: &[("background", "background"), ("input", "pattern0")], + params: &[("colorswitch", "color_mode"), ("background", "background"), ("opacitymult", "opacity")], + }, +]; +pub(super) const BASE_PARAMS: &[&str] = &["outputsize", "format", "randomseed", "tiling", "pixelsize", "pixelratio", "quality"]; +pub(super) const HANDLED_PARAMS: &[(&str, &str)] = &[ + ("bitmap", "bitmapresourcepath"), + ("bitmap", "colorspace"), + ("grayscaleconversion", "channelsweights"), + ("transformation", "matrix22"), + ("curve", "exposecurve"), +]; + +pub(super) fn filter_by_sbs_name(name: &str) -> Option<&'static FilterMap> { + FILTERS.iter().find(|f| f.sbs == name) +} + +pub(super) fn filter_by_def(def: &str) -> Option<&'static FilterMap> { + FILTERS.iter().find(|f| f.def == def) +} diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs new file mode 100644 index 00000000..e66e99bb --- /dev/null +++ b/crates/formats/src/sbs/function_graph.rs @@ -0,0 +1,131 @@ +use super::sbs_value::{constant_xml, sbs_constant, to_natural_value}; +use super::sbs_writer::SbsWriter; +use super::xml::{child_element, child_value, children_named, parse_floats, xml_escape}; +use materialcraft_core::{FunctionGraph, FunctionNode, Value}; +use materialcraft_nodes::function; +use roxmltree::Node as XmlNode; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; + +pub(super) fn read(element: XmlNode<'_, '_>) -> Result<FunctionGraph, String> { + let mut graph = FunctionGraph { output: child_value(element, "rootnode").and_then(|value| value.parse().ok()), nodes: Vec::new() }; + let mut ids = BTreeSet::new(); + for element in child_element(element, "paramNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramNode")) { + if graph.nodes.len() >= 4096 { + return Err("function exceeds the 4096-node limit".into()); + } + let id = child_value(element, "uid").and_then(|value| value.parse().ok()).ok_or("function node has no valid uid")?; + if !ids.insert(id) { + return Err(format!("duplicate function uid {id}")); + } + let op = child_value(element, "function").ok_or("function node has no operation")?; + let definition = function::definition(op).ok_or_else(|| format!("unsupported function `{op}`"))?; + let mut inputs = vec![None; definition.inputs.len()]; + for connection in child_element(element, "connections").into_iter().flat_map(|connections| children_named(connections, "connection")) { + let port = child_value(connection, "identifier").unwrap_or(""); + let index = definition.inputs.iter().position(|input| *input == port).ok_or_else(|| format!("{op}: unknown input `{port}`"))?; + let source = child_value(connection, "connRef").and_then(|value| value.parse().ok()).ok_or("invalid function connection")?; + let input = inputs.get_mut(index).ok_or("invalid input index")?; + if input.replace(source).is_some() { + return Err(format!("{op}: duplicate input `{port}`")); + } + } + + let value = child_element(element, "funcDatas") + .into_iter() + .flat_map(|data| children_named(data, "funcData")) + .find(|data| child_value(*data, "name") == Some(op)) + .and_then(|data| child_element(data, "constantValue")) + .and_then(sbs_constant) + .map(|value| to_natural_value(&value)); + let position = child_element(element, "GUILayout").and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); + graph.nodes.push(FunctionNode { + id, + op: op.into(), + inputs, + type_code: child_value(element, "type").and_then(|value| value.parse().ok()).unwrap_or(0), + value: value.or_else(|| native_default(op)), + pos: [position.first().copied().unwrap_or(0.0), position.get(1).copied().unwrap_or(0.0)], + }); + } + + if graph.output.is_some_and(|id| !ids.contains(&id)) { + return Err("function result references a missing node".into()); + } + if graph.nodes.iter().flat_map(|node| node.inputs.iter().flatten()).any(|id| !ids.contains(id)) { + return Err("function connection references a missing node".into()); + } + Ok(graph) +} + +fn native_default(op: &str) -> Option<Value> { + Some(match op { + "const_float1" => Value::Float(0.0), + "const_float4" => Value::Float4([0.0; 4]), + "swizzle2" | "iswizzle2" => Value::Int2([0; 2]), + "swizzle3" | "iswizzle3" => Value::Int3([0; 3]), + "swizzle4" | "iswizzle4" => Value::Int4([0; 4]), + _ => return function::default_value(op), + }) +} + +pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result<String, String> { + if graph.nodes.len() > 4096 { + return Err("function exceeds the 4096-node limit".into()); + } + let types = function::node_types(graph)?; + let identifiers: BTreeMap<_, _> = graph.nodes.iter().map(|node| (node.id, writer.next_uid())).collect(); + let mut output = String::from("<dynamicValue>"); + if let Some(root) = graph.output.and_then(|root| identifiers.get(&root)) { + let _ = write!(output, "<rootnode v=\"{root}\"/>"); + } + output.push_str("<paramNodes>"); + for node in &graph.nodes { + let definition = function::definition(&node.op).ok_or_else(|| format!("cannot save unknown function `{}`", node.op))?; + let inferred = types.get(&node.id).copied().unwrap_or(256); + let code = if node.type_code == 0 { inferred } else { node.type_code }; + let _ = write!( + output, + "<paramNode><uid v=\"{}\"/><function v=\"{}\"/><type v=\"{code}\"/><GUILayout><gpos v=\"{} {} 0\"/></GUILayout><connections>", + identifiers.get(&node.id).copied().ok_or("missing function uid")?, + xml_escape(&node.op), + node.pos[0], + node.pos[1] + ); + for (input, source) in definition.inputs.iter().zip(&node.inputs) { + if let Some(source) = source.and_then(|source| identifiers.get(&source)) { + let _ = write!(output, "<connection><identifier v=\"{}\"/><connRef v=\"{source}\"/></connection>", xml_escape(input)); + } + } + output.push_str("</connections>"); + if let Some(value) = &node.value { + let constant = constant_xml(value).ok_or("function data must be a scalar or vector constant")?; + let _ = + write!(output, "<funcDatas><funcData><name v=\"{}\"/><constantValue>{constant}</constantValue></funcData></funcDatas>", xml_escape(&node.op)); + } + output.push_str("</paramNode>"); + } + output.push_str("</paramNodes></dynamicValue>"); + Ok(output) +} + +pub(super) fn binding(identifier: &str, value: &Value) -> Result<FunctionGraph, String> { + use materialcraft_core::ValueType; + + let operation = match ValueType::of(value).ok_or("only scalar and vector parameters can be exposed")? { + ValueType::Boolean => "get_bool", + ValueType::Integer => "get_integer1", + ValueType::Integer2 => "get_integer2", + ValueType::Integer3 => "get_integer3", + ValueType::Integer4 => "get_integer4", + ValueType::Float => "get_float1", + ValueType::Float2 => "get_float2", + ValueType::Float3 => "get_float3", + ValueType::Float4 => "get_float4", + ValueType::String => "get_string", + }; + + let mut graph = FunctionGraph::default(); + graph.output = Some(graph.add(operation, &[], Some(Value::Text(identifier.into())))); + Ok(graph) +} diff --git a/crates/formats/src/sbs/image_input.rs b/crates/formats/src/sbs/image_input.rs new file mode 100644 index 00000000..0ad462ff --- /dev/null +++ b/crates/formats/src/sbs/image_input.rs @@ -0,0 +1,15 @@ +use materialcraft_nodes::{MAX_IMAGE_INPUTS, image_input_prefix}; + +pub(super) fn read(definition: &str, identifier: &str) -> Option<String> { + let prefix = image_input_prefix(definition)?; + + let index = if identifier == "input" { 0 } else { identifier.strip_prefix("input:")?.parse::<usize>().ok()? }; + (index < MAX_IMAGE_INPUTS).then(|| format!("{prefix}{index}")) +} + +pub(super) fn write(definition: &str, identifier: &str) -> Option<String> { + let prefix = image_input_prefix(definition)?; + + let index = identifier.strip_prefix(prefix)?.parse::<usize>().ok()?; + (index < MAX_IMAGE_INPUTS).then(|| if index == 0 { "input".into() } else { format!("input:{index}") }) +} diff --git a/crates/formats/src/sbs/input_bridge.rs b/crates/formats/src/sbs/input_bridge.rs new file mode 100644 index 00000000..f800707d --- /dev/null +++ b/crates/formats/src/sbs/input_bridge.rs @@ -0,0 +1,7 @@ +use materialcraft_core::Value; + +pub(super) struct InputBridge { + pub identifier: String, + pub type_code: u32, + pub default: Value, +} diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs new file mode 100644 index 00000000..7083cb5b --- /dev/null +++ b/crates/formats/src/sbs/mod.rs @@ -0,0 +1,32 @@ +mod base_parameters; +mod canvas; +mod connection; +mod constant; +mod embedded; +mod filter_map; +mod function_graph; +mod image_input; +mod input_bridge; +mod node_identifiers; +mod node_parameter; +mod output; +mod parameter_array; +mod pattern_graph; +mod placeholder; +mod read_node; +mod sbs_read; +mod sbs_reader; +mod sbs_value; +mod sbs_writer; +mod standalone_function; +mod type_code; +mod warnings; +mod xml; + +pub use constant::SBS_EXT; +pub use sbs_read::SbsRead; +pub use sbs_reader::{is_sbs, read_sbs}; +pub use sbs_writer::write_sbs; + +#[cfg(test)] +mod tests; diff --git a/crates/formats/src/sbs/node_identifiers.rs b/crates/formats/src/sbs/node_identifiers.rs new file mode 100644 index 00000000..2a761667 --- /dev/null +++ b/crates/formats/src/sbs/node_identifiers.rs @@ -0,0 +1,6 @@ +#[derive(Clone, Copy)] +pub(super) struct NodeIdentifiers { + pub(super) input_entry: Option<u64>, + pub(super) graph_output: Option<u64>, + pub(super) self_uid: u64, +} diff --git a/crates/formats/src/sbs/node_parameter.rs b/crates/formats/src/sbs/node_parameter.rs new file mode 100644 index 00000000..9137a455 --- /dev/null +++ b/crates/formats/src/sbs/node_parameter.rs @@ -0,0 +1,30 @@ +use super::sbs_value::constant_xml; +use super::xml::xml_escape; +use materialcraft_core::{Node, Value}; + +pub(super) fn text_param(node: &Node, key: &str, default: &str) -> String { + match node.params.get(key) { + Some(Value::Text(s)) if !s.is_empty() => s.clone(), + _ => default.to_string(), + } +} +pub(super) fn param_xml(name: &str, value: &Value) -> Option<String> { + Some(format!("<parameter><name v=\"{}\"/><relativeTo v=\"0\"/><paramValue>{}</paramValue></parameter>", xml_escape(name), constant_xml(value)?)) +} +pub(super) fn special_filter_params_xml<'a>(filter: &str, value_of: &dyn Fn(&str) -> Option<&'a Value>, self_uid: u64) -> String { + match filter { + "bitmap" | "svg" => match value_of("resource") { + Some(Value::Text(name)) if !name.is_empty() => param_xml( + if filter == "svg" { "vectorresourcepath" } else { "bitmapresourcepath" }, + &Value::Text(format!("pkg:///Resources/{name}?dependency={self_uid}")), + ) + .unwrap_or_default(), + _ => String::new(), + }, + "grayscaleconversion" => { + let weight = |channel: &str| value_of(channel).and_then(Value::as_f32).unwrap_or(0.0); + param_xml("channelsweights", &Value::Float4([weight("red"), weight("green"), weight("blue"), weight("alpha")])).unwrap_or_default() + } + _ => String::new(), + } +} diff --git a/crates/formats/src/sbs/output.rs b/crates/formats/src/sbs/output.rs new file mode 100644 index 00000000..865975b3 --- /dev/null +++ b/crates/formats/src/sbs/output.rs @@ -0,0 +1,49 @@ +use materialcraft_nodes::PortKind; + +pub(super) fn usage_index(name: &str) -> u32 { + let ids = materialcraft_nodes::atomic::USAGE_IDS; + let name = name.trim(); + let index = ids.iter().position(|u| u.eq_ignore_ascii_case(name)).or_else(|| name.eq_ignore_ascii_case("diffuse").then_some(0)); + index.unwrap_or(ids.len().saturating_sub(1)) as u32 +} + +pub(super) fn usage_name(index: u32) -> &'static str { + materialcraft_nodes::atomic::USAGE_IDS.get(index as usize).copied().unwrap_or("any") +} +pub(super) fn output_type(graph: &materialcraft_core::Graph, id: materialcraft_core::NodeId, port: &str) -> u32 { + if let Ok(Some(kind)) = materialcraft_nodes::output_value_type(graph, id) { + return kind as u32; + } + + let mut pending = vec![(id, port.to_string())]; + let mut visited = std::collections::BTreeSet::new(); + while let Some((id, port)) = pending.pop() { + if !visited.insert(id) { + continue; + } + + let Ok(node) = graph.node(id) else { continue }; + let Some(definition) = materialcraft_nodes::find(&node.def) else { return 1 }; + if let Some(parameter) = definition.param("color_mode") { + if node.params.get("color_mode").unwrap_or(¶meter.default).as_bool() == Some(true) { + return 1; + } + continue; + } + + match definition.outputs.iter().find(|output| output.id == port).map(|output| output.kind) { + Some(PortKind::Color) => return 1, + Some(PortKind::Gray) => continue, + _ => {} + } + + let sources = definition.inputs.iter().filter(|input| input.kind != PortKind::Gray).filter_map(|input| graph.input_of(id, input.id)); + for source in sources { + pending.push((source.from, source.from_port.clone())); + if node.def != "blend" { + break; + } + } + } + 2 +} diff --git a/crates/formats/src/sbs/parameter_array.rs b/crates/formats/src/sbs/parameter_array.rs new file mode 100644 index 00000000..e99e4c96 --- /dev/null +++ b/crates/formats/src/sbs/parameter_array.rs @@ -0,0 +1,93 @@ +use materialcraft_core::{Curve, CurvePoint, Gradient, GradientKey, Node, Value}; +use roxmltree::Node as XmlNode; +use std::collections::BTreeMap; +use std::fmt::Write; + +use super::node_parameter::param_xml; +use super::sbs_value::{sbs_constant, to_natural_value}; +use super::sbs_writer::SbsWriter; +use super::xml::{child_element, child_value, children_named}; + +pub(super) fn read(node: &mut Node, implementation: XmlNode<'_, '_>) { + for array in child_element(implementation, "paramsArrays").into_iter().flat_map(|arrays| children_named(arrays, "paramsArray")) { + let mut curve = Curve { points: Vec::new() }; + let mut gradient = Gradient { keys: Vec::new() }; + for cell in child_element(array, "paramsArrayCells").into_iter().flat_map(|cells| children_named(cells, "paramsArrayCell")).take(4096) { + let parameters: BTreeMap<_, _> = child_element(cell, "parameters") + .into_iter() + .flat_map(|parameters| children_named(parameters, "parameter")) + .filter_map(|parameter| Some((child_value(parameter, "name")?, to_natural_value(&sbs_constant(child_element(parameter, "paramValue")?)?)))) + .collect(); + let vector = |name| parameters.get(name).and_then(Value::as_vec4).map(|value| [value[0], value[1]]); + match child_value(array, "name") { + Some("curveluminance") => { + let position = vector("position").unwrap_or([0.0; 2]); + curve.points.push(CurvePoint { x: position[0], y: position[1], left: vector("left"), right: vector("right") }); + } + Some("gradientrgba" | "gradientluminance") => { + let position = parameters.get("position").and_then(Value::as_f32).unwrap_or(0.0); + let color = match parameters.get("value") { + Some(Value::Float(gray)) => [*gray, *gray, *gray, 1.0], + Some(value) => value.as_vec4().unwrap_or([0.0; 4]), + None => [0.0; 4], + }; + + let midpoint = parameters.get("midpoint").and_then(Value::as_f32).unwrap_or(0.5); + gradient.keys.push(GradientKey { pos: position, color, midpoint }); + } + _ => {} + } + } + if !curve.points.is_empty() { + curve.points.sort_by(|left, right| left.x.total_cmp(&right.x)); + node.params.insert("curve".into(), Value::Curve(curve)); + } + if !gradient.keys.is_empty() { + gradient.sort(); + node.params.insert("gradient".into(), Value::Gradient(gradient)); + } + } +} + +pub(super) fn write(value: &Value, writer: &mut SbsWriter) -> String { + let name = match value { + Value::Curve(_) => "curveluminance", + Value::Gradient(_) => "gradientrgba", + _ => return String::new(), + }; + + let mut output = format!("<paramsArrays><paramsArray><name v=\"{name}\"/><uid v=\"{}\"/><paramsArrayCells>", writer.next_uid()); + let mut cell = |parameters: Vec<(&str, Value)>| { + let _ = write!(output, "<paramsArrayCell><uid v=\"{}\"/><parameters>", writer.next_uid()); + for (name, value) in parameters { + output.push_str(¶m_xml(name, &value).unwrap_or_default()); + } + output.push_str("</parameters></paramsArrayCell>"); + }; + + match value { + Value::Curve(curve) => { + for (index, point) in curve.points.iter().enumerate() { + let position = [point.x, point.y]; + let left = index.checked_sub(1).and_then(|index| curve.segment(index)).map_or(position, |segment| segment[2]); + let right = curve.segment(index).map_or(position, |segment| segment[1]); + cell(vec![ + ("position", Value::Float2(position)), + ("left", Value::Float2(left)), + ("right", Value::Float2(right)), + ("isLeftBroken", Value::Bool(true)), + ("isRightBroken", Value::Bool(true)), + ("isLocked", Value::Bool(false)), + ]); + } + } + Value::Gradient(gradient) => { + for key in &gradient.keys { + cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(key.midpoint)), ("value", Value::Float4(key.color))]); + } + } + _ => {} + } + output.push_str("</paramsArrayCells></paramsArray></paramsArrays>"); + output +} diff --git a/crates/formats/src/sbs/pattern_graph.rs b/crates/formats/src/sbs/pattern_graph.rs new file mode 100644 index 00000000..6e707ad3 --- /dev/null +++ b/crates/formats/src/sbs/pattern_graph.rs @@ -0,0 +1,116 @@ +use materialcraft_core::{PatternGraph, PatternNode, PatternNodeKind, Value}; +use roxmltree::Node as XmlNode; +use std::collections::BTreeMap; +use std::fmt::Write; + +use super::node_parameter::param_xml; +use super::sbs_value::{sbs_constant, to_natural_value}; +use super::xml::{child_element, child_value, children_named, parse_floats, xml_escape}; +use super::{function_graph, sbs_writer::SbsWriter}; + +pub(super) fn read(element: XmlNode<'_, '_>) -> Result<PatternGraph, String> { + let mut data = BTreeMap::new(); + for element in child_element(element, "paramsGraphDatas").into_iter().flat_map(|data| children_named(data, "paramsGraphData")) { + if data.len() >= 4096 { + return Err("pattern graph exceeds the 4096-node limit".into()); + } + + let uid = child_value(element, "uid").ok_or("pattern data has no uid")?; + let mut parameters = BTreeMap::new(); + for parameter in child_element(element, "parameters").into_iter().flat_map(|parameters| children_named(parameters, "parameter")) { + let name = child_value(parameter, "name").ok_or("pattern parameter has no name")?; + let value = child_element(parameter, "paramValue").ok_or("pattern parameter has no value")?; + let value = match child_element(value, "dynamicValue") { + Some(function) => Value::Function(Box::new(function_graph::read(function)?)), + None => to_natural_value(&sbs_constant(value).ok_or("invalid pattern parameter value")?), + }; + + parameters.insert(name.to_string(), value); + } + if data.insert(uid, parameters).is_some() { + return Err("duplicate pattern data uid".into()); + } + } + + let mut graph = PatternGraph { root: child_value(element, "rootnode").and_then(|id| id.parse().ok()), nodes: Vec::new() }; + for element in child_element(element, "paramsGraphNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramsGraphNode")) { + if graph.nodes.len() >= 4096 { + return Err("pattern graph exceeds the 4096-node limit".into()); + } + + let id = child_value(element, "uid").and_then(|id| id.parse().ok()).ok_or("invalid pattern node uid")?; + let kind = PatternNodeKind::ALL.into_iter().find(|kind| Some(kind.native_id()) == child_value(element, "type")).ok_or("unknown pattern node type")?; + let mut children = vec![None; kind.child_count()]; + for connection in child_element(element, "connections").into_iter().flat_map(|connections| children_named(connections, "connection")) { + let identifier = child_value(connection, "identifier").ok_or("missing pattern child port")?; + let slot = (0..kind.child_count()).find(|slot| kind.child_port(*slot) == Some(identifier)).ok_or("invalid pattern child slot")?; + let child = child_value(connection, "connRef").and_then(|id| id.parse().ok()).ok_or("invalid pattern child uid")?; + if children.get_mut(slot).ok_or("invalid pattern child slot")?.replace(child).is_some() { + return Err("duplicate pattern connection".into()); + } + } + + let parameters = child_value(element, "data").and_then(|uid| data.get(uid)).cloned(); + let parameters = match parameters { + Some(parameters) => parameters, + None if kind == PatternNodeKind::Dot => BTreeMap::new(), + None => return Err("missing pattern data".into()), + }; + let position = child_element(element, "GUILayout").and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); + graph.nodes.push(PatternNode { + id, + kind, + children, + parameters, + position: [position.first().copied().unwrap_or(0.0), position.get(1).copied().unwrap_or(0.0)], + }); + } + graph.validate()?; + Ok(graph) +} + +pub(super) fn write(graph: &PatternGraph, writer: &mut SbsWriter) -> Result<String, String> { + graph.validate()?; + let identifiers: BTreeMap<_, _> = graph.nodes.iter().map(|node| (node.id, (writer.next_uid(), writer.next_uid()))).collect(); + let mut output = format!("<paramsGraphs><paramsGraph><name v=\"\"/><uid v=\"{}\"/>", writer.next_uid()); + if let Some((root, _)) = graph.root.and_then(|root| identifiers.get(&root)) { + let _ = write!(output, "<rootnode v=\"{root}\"/>"); + } + output.push_str("<paramsGraphDatas>"); + for node in &graph.nodes { + let (_, data) = identifiers.get(&node.id).ok_or("missing pattern uid")?; + let _ = write!(output, "<paramsGraphData><uid v=\"{data}\"/><type v=\"{}\"/><parameters>", node.kind.native_id()); + let definition = materialcraft_nodes::pattern::definition(node.kind).ok_or("missing pattern definition")?; + let mut parameters: BTreeMap<_, _> = definition.params.iter().map(|parameter| (parameter.id.to_string(), parameter.default.clone())).collect(); + parameters.extend(node.parameters.clone()); + for (name, value) in ¶meters { + if let Value::Function(function) = value { + let function = function_graph::write(function, writer)?; + let _ = write!(output, "<parameter><name v=\"{}\"/><paramValue>{function}</paramValue></parameter>", xml_escape(name)); + } else { + output.push_str(¶m_xml(name, value).ok_or("invalid pattern parameter")?); + } + } + output.push_str("</parameters></paramsGraphData>"); + } + output.push_str("</paramsGraphDatas><paramsGraphNodes>"); + for node in &graph.nodes { + let (uid, data) = identifiers.get(&node.id).ok_or("missing pattern uid")?; + let _ = write!( + output, + "<paramsGraphNode><uid v=\"{uid}\"/><type v=\"{}\"/><data v=\"{data}\"/><GUILayout><gpos v=\"{} {} 0\"/></GUILayout><connections>", + node.kind.native_id(), + node.position[0], + node.position[1] + ); + for (slot, child) in node.children.iter().enumerate() { + if let Some((uid, _)) = child.and_then(|child| identifiers.get(&child)) { + let port = node.kind.child_port(slot).ok_or("invalid pattern child slot")?; + let _ = write!(output, "<connection><identifier v=\"{port}\"/><connRef v=\"{uid}\"/></connection>"); + } + } + output.push_str("</connections></paramsGraphNode>"); + } + output.push_str("</paramsGraphNodes></paramsGraph></paramsGraphs>"); + Ok(output) +} diff --git a/crates/formats/src/sbs/placeholder.rs b/crates/formats/src/sbs/placeholder.rs new file mode 100644 index 00000000..d2258892 --- /dev/null +++ b/crates/formats/src/sbs/placeholder.rs @@ -0,0 +1,75 @@ +use super::warnings::Warnings; +use materialcraft_core::{MISSING_NODE, Node, Package, Value, missing_ports}; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn report_placeholders(pkg: &Package, warnings: &mut Warnings) { + for graph in &pkg.graphs { + let mut counts: BTreeMap<String, usize> = BTreeMap::new(); + for node in graph.nodes.iter().filter(|n| n.def == MISSING_NODE) { + let name = match node.params.get("sbs_name") { + Some(Value::Text(s)) if !s.is_empty() => s.clone(), + _ => node.label.clone(), + }; + *counts.entry(name).or_default() += 1; + } + + for (name, count) in counts { + let times = if count > 1 { format!(" ×{count}") } else { String::new() }; + warnings.add(format!("graph `{}`: missing node `{name}`{times} is not in MaterialCraft's library yet; kept as a placeholder", graph.name)); + } + } +} +pub(super) fn fill_placeholder( + node: &mut Node, + kind: &str, + name: &str, + package: &str, + raw_params: Option<&str>, + output_uids: &[(String, bool)], + bridgings: Option<&[(String, String)]>, +) { + node.label = name.to_string(); + node.params.insert("sbs_kind".into(), Value::Text(kind.into())); + node.params.insert("sbs_name".into(), Value::Text(name.into())); + if !package.is_empty() { + node.params.insert("sbs_package".into(), Value::Text(package.into())); + } + if let Some(raw) = raw_params { + node.params.insert("sbs_parameters".into(), Value::Text(raw.into())); + } + + let mut seen = BTreeSet::new(); + let outputs: Vec<String> = placeholder_outputs(output_uids, bridgings) + .into_iter() + .filter(|(_, port)| seen.insert(port.clone())) + .map(|(uid, port)| if output_uids.iter().any(|(u, gray)| *u == uid && *gray) { format!("{port}:gray") } else { port }) + .collect(); + node.params.insert("outputs".into(), Value::Text(outputs.join(","))); + node.params.insert("inputs".into(), Value::Text(String::new())); +} +pub(super) fn placeholder_outputs(output_uids: &[(String, bool)], bridgings: Option<&[(String, String)]>) -> Vec<(String, String)> { + let bridged = |uid: &str| bridgings.and_then(|b| b.iter().find(|(u, _)| u == uid)).map(|(_, identifier)| identifier.clone()); + let mut outputs: Vec<(String, String)> = output_uids + .iter() + .enumerate() + .map(|(i, (uid, _))| (uid.clone(), bridged(uid).unwrap_or_else(|| if i == 0 { "output".to_string() } else { format!("output_{}", i + 1) }))) + .collect(); + + for (uid, identifier) in bridgings.unwrap_or_default() { + if !outputs.iter().any(|(u, _)| u == uid) { + outputs.push((uid.clone(), identifier.clone())); + } + } + outputs +} +pub(super) fn add_placeholder_input(node: &mut Node, port: &str) { + if port.is_empty() || port.contains(',') { + return; + } + + let (mut inputs, _) = missing_ports(node); + if !inputs.iter().any(|p| p == port) { + inputs.push(port.to_string()); + node.params.insert("inputs".into(), Value::Text(inputs.join(","))); + } +} diff --git a/crates/formats/src/sbs/read_node.rs b/crates/formats/src/sbs/read_node.rs new file mode 100644 index 00000000..9ab8048a --- /dev/null +++ b/crates/formats/src/sbs/read_node.rs @@ -0,0 +1,10 @@ +use materialcraft_core::NodeId; +use std::collections::HashMap; + +pub(super) struct ReadNode { + pub(super) id: NodeId, + pub(super) index: usize, + pub(super) inputs: HashMap<String, String>, + pub(super) outputs: Vec<(String, String)>, + pub(super) open_inputs: bool, +} diff --git a/crates/formats/src/sbs/sbs_read.rs b/crates/formats/src/sbs/sbs_read.rs new file mode 100644 index 00000000..e4aec2f6 --- /dev/null +++ b/crates/formats/src/sbs/sbs_read.rs @@ -0,0 +1,7 @@ +use materialcraft_core::Package; + +#[derive(Debug)] +pub struct SbsRead { + pub pkg: Package, + pub warnings: Vec<String>, +} diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs new file mode 100644 index 00000000..12f0bdb9 --- /dev/null +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -0,0 +1,626 @@ +use super::base_parameters::read_base_params; +use super::connection::connect_all; +use super::constant::{MAX_GRAPHS, MAX_NODES, MAX_RESOURCES, MAX_SBS_BYTES, MAX_XML_NODES}; +use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY, SNIFF_BYTES}; +use super::embedded::decode_embedded; +use super::filter_map::{BASE_PARAMS, FilterMap, HANDLED_PARAMS, filter_by_sbs_name}; +use super::function_graph; +use super::input_bridge::InputBridge; +use super::output::usage_index; +use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs, report_placeholders}; +use super::read_node::ReadNode; +use super::sbs_read::SbsRead; +use super::sbs_value::{SbsValue, exposed_default, sbs_constant, to_natural_value, to_param_value}; +use super::type_code; +use super::warnings::Warnings; +use super::xml::{child_element, child_value, children_named, parse_floats}; +use crate::{FormatError, Result}; +use materialcraft_core::{ + Comment, Connection, ExposedParameter, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Pin, Resource, ResourceBytes, + Value, srgb_to_linear, +}; +use materialcraft_nodes::find; +use roxmltree::Node as XmlNode; +use std::collections::HashMap; + +pub(super) struct SbsReader<'text, 'warnings> { + pub(super) text: &'text str, + pub(super) warnings: &'warnings mut Warnings, + pub(super) dependencies: HashMap<String, String>, + pub(super) graph_names: HashMap<String, String>, + pub(super) resource_names: HashMap<String, String>, + pub(super) node_count: usize, +} + +impl<'text> SbsReader<'text, '_> { + pub(super) fn collect_items<'a>( + &mut self, + content: XmlNode<'a, 'text>, + folder: &str, + pkg: &mut Package, + graphs: &mut Vec<(String, XmlNode<'a, 'text>)>, + linked: &dyn Fn(&str) -> Option<Vec<u8>>, + ) { + let mut pending = vec![(folder.to_string(), content)]; + while let Some((folder, content)) = pending.pop() { + for item in content.children().filter(|child| child.is_element()) { + let identifier = child_value(item, "identifier").unwrap_or("").trim().to_string(); + let path = if folder.is_empty() { identifier.clone() } else { format!("{folder}/{identifier}") }; + + match item.tag_name().name() { + "graph" | "function" => graphs.push((path, item)), + "group" => { + if let Some(group_content) = child_element(item, "content") { + pending.push((path, group_content)); + } + } + "resource" if pkg.resources.len() >= MAX_RESOURCES => self.warnings.add(format!("only the first {MAX_RESOURCES} resources were read")), + "resource" => self.read_resource(item, &identifier, &path, pkg, linked), + "mdl_graph" | "mdlGraph" => self.warnings.add(format!("MDL graph `{path}` is not supported")), + other => self.warnings.add(format!("package item <{other}> `{path}` is not supported")), + } + } + } + } + + pub(super) fn read_resource(&mut self, item: XmlNode, identifier: &str, path: &str, pkg: &mut Package, linked: &dyn Fn(&str) -> Option<Vec<u8>>) { + let kind = child_value(item, "type").unwrap_or("bitmap"); + let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase(); + let source = child_element(item, "source"); + let mut bytes: Option<Vec<u8>> = None; + let mut why_missing = String::new(); + + if let Some(embedded) = source.and_then(|s| child_element(s, "binembedded")) { + match decode_embedded(child_value(embedded, "strdata").unwrap_or("")) { + Ok(data) => bytes = Some(data), + Err(e) => why_missing = format!("its embedded data is damaged ({e})"), + } + } + + if bytes.is_none() { + let external_copy = source.and_then(|s| child_element(s, "externalcopy")).and_then(|e| child_value(e, "filename")); + for file in [external_copy, child_value(item, "filepath")].into_iter().flatten().filter(|p| !p.trim().is_empty()) { + if file.contains("://") { + why_missing = format!("it links to `{file}`, which is not available"); + continue; + } + match linked(file) { + Some(data) => { + bytes = Some(data); + break; + } + None => why_missing = format!("its file `{file}` was not found next to the package"), + } + } + } + + let taken: Vec<String> = pkg.resources.iter().map(|r| r.name.clone()).collect(); + let name = unique_name(&taken, if identifier.is_empty() { "resource" } else { identifier }); + self.resource_names.insert(path.to_string(), name.clone()); + match bytes { + Some(data) => { + let ext = if kind == "svg" { "svg".to_string() } else { format }; + pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); + } + None => { + let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; + self.warnings.add(format!("resource `{path}` could not be loaded: {why}")); + } + } + } + pub(super) fn resolve_reference(&self, url: &str) -> (String, Option<String>) { + let url = url.trim(); + let rest = url.strip_prefix("pkg:///").or_else(|| url.strip_prefix("pkg://")).unwrap_or(url); + let (path, query) = rest.split_once('?').unwrap_or((rest, "")); + let dependency = query.split('&').find_map(|kv| kv.strip_prefix("dependency=")).and_then(|uid| self.dependencies.get(uid).cloned()); + (path.trim_matches('/').to_string(), dependency) + } + + pub(super) fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph { + let mut graph = Graph::new(&name); + graph.seed = read_base_params(child_element(element, "baseParameters")).seed; + + // The default parent size option ("11x11", log2 sizes) + for option in child_element(element, "options").into_iter().flat_map(|o| children_named(o, "option")) { + if child_value(option, "name") == Some("defaultParentSize") + && let Some((width, height)) = child_value(option, "value").and_then(|v| v.split_once('x')) + { + let log2 = |s: &str| s.trim().parse::<i64>().unwrap_or(10).clamp(i64::from(MIN_SIZE_LOG2), i64::from(MAX_SIZE_LOG2)) as u32; + graph.size = [log2(width), log2(height)]; + } + } + + if let Some(attributes) = child_element(element, "attributes") { + let text = |tag: &str| child_value(attributes, tag).unwrap_or("").to_string(); + graph.attributes.category = text("category"); + graph.attributes.description = text("description"); + graph.attributes.author = text("author"); + graph.attributes.tags = text("tags"); + } + + if element.has_tag_name("function") { + self.read_graph_inputs(element, &mut graph); + let dynamic = child_element(element, "paramValue").and_then(|value| child_element(value, "dynamicValue")); + let function = dynamic.ok_or_else(|| "missing function body".to_string()).and_then(super::function_graph::read); + graph.function = Some(match function { + Ok(function) => function, + Err(error) => { + self.warnings.add(format!("function graph `{name}`: {error}")); + materialcraft_core::FunctionGraph::default() + } + }); + if let Some(dynamic) = dynamic { + self.read_canvas_items(dynamic, &mut graph); + } + return graph; + } + + let image_inputs = self.read_graph_inputs(element, &mut graph); + let outputs = read_graph_outputs(element); + + let mut read_nodes: HashMap<String, ReadNode> = HashMap::new(); + let comp_nodes: Vec<XmlNode> = child_element(element, "compNodes").into_iter().flat_map(|c| children_named(c, "compNode")).collect(); + for comp_node in &comp_nodes { + if self.node_count >= MAX_NODES { + self.warnings.add(format!("only the first {MAX_NODES} nodes were read")); + break; + } + + let Some(uid) = child_value(*comp_node, "uid").map(str::to_string) else { continue }; + if read_nodes.contains_key(&uid) { + self.warnings.add(format!("graph `{name}`: duplicate node uid {uid} skipped")); + continue; + } + + self.node_count += 1; + let mut node = self.read_node(&mut graph, *comp_node, &image_inputs, &outputs); + for input in child_element(*comp_node, "inputValues").into_iter().flat_map(|inputs| children_named(inputs, "compInputValue")).take(64) { + let identifier = child_value(input, "identifier").unwrap_or(""); + let value_type = child_value(input, "type").and_then(|code| code.parse().ok()).and_then(materialcraft_core::ValueType::from_code); + if let Some(value_type) = value_type { + if let Some(document_node) = graph.nodes.get_mut(node.index) { + document_node.input_values.insert(identifier.to_string(), value_type); + } + node.inputs.insert(identifier.to_string(), identifier.to_string()); + } + } + read_nodes.insert(uid, node); + } + + let wires = self.read_wires(&mut graph, &comp_nodes, &read_nodes); + connect_all(&mut graph, wires, self.warnings); + self.read_canvas_items(element, &mut graph); + graph + } + pub(super) fn read_graph_inputs(&mut self, element: XmlNode, graph: &mut Graph) -> HashMap<String, InputBridge> { + let mut image_inputs = HashMap::new(); + for input in child_element(element, "paraminputs").into_iter().flat_map(|p| children_named(p, "paraminput")) { + let id = child_value(input, "identifier").unwrap_or("input").to_string(); + let code = child_value(input, "type").and_then(|t| t.trim().parse::<i64>().ok()).unwrap_or(type_code::FLOAT1); + if code == type_code::COLOR_IMAGE || code == type_code::GRAY_IMAGE { + let default = child_element(input, "defaultValue") + .and_then(sbs_constant) + .and_then(|value| to_param_value(&Value::Color([0.5, 0.5, 0.5, 1.0]), &value, 0)) + .unwrap_or(Value::Color([0.5, 0.5, 0.5, 1.0])); + image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default }); + continue; + } + if graph.exposed.iter().any(|e| e.id == id) { + continue; + } + + let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref()); + if child_value(input, "isConnectable") == Some("1") { + image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default }); + continue; + } + let label = child_element(input, "attributes").and_then(|a| child_value(a, "label")).filter(|l| !l.is_empty()).unwrap_or(&id).to_string(); + let (mut min, mut max) = (0.0, 1.0); + let widget_options = child_element(input, "defaultWidget").and_then(|w| child_element(w, "options")); + for option in widget_options.into_iter().flat_map(|o| children_named(o, "option")) { + let value = + child_value(option, "value").and_then(|v| v.split_whitespace().next()).and_then(|v| v.parse::<f32>().ok()).filter(|v| v.is_finite()); + match (child_value(option, "name"), value) { + (Some("min"), Some(v)) => min = v, + (Some("max"), Some(v)) => max = v, + _ => {} + } + } + + let group = child_value(input, "group").unwrap_or("").to_string(); + graph.exposed.push(ExposedParameter { id, label, group, default, min, max, options: Vec::new() }); + } + image_inputs + } + pub(super) fn read_wires(&mut self, graph: &mut Graph, comp_nodes: &[XmlNode], read_nodes: &HashMap<String, ReadNode>) -> Vec<Connection> { + let name = graph.name.clone(); + let mut wires = Vec::new(); + + for comp_node in comp_nodes { + let Some(to) = child_value(*comp_node, "uid").and_then(|u| read_nodes.get(u)) else { continue }; + for connection in child_element(*comp_node, "connections").into_iter().flat_map(|c| children_named(c, "connection")) { + let sbs_input = child_value(connection, "identifier").unwrap_or(""); + let Some(from) = child_value(connection, "connRef").and_then(|u| read_nodes.get(u)) else { + self.warnings.add(format!("graph `{name}`: a wire from a node that is not in the file was dropped")); + continue; + }; + + let output_uid = child_value(connection, "connRefOutput").unwrap_or(""); + let from_port = from.outputs.iter().find(|(uid, _)| uid == output_uid).or(from.outputs.first()).map(|(_, port)| port.clone()); + let Some(from_port) = from_port else { + self.warnings.add(format!("graph `{name}`: a wire from a node with no outputs was dropped")); + continue; + }; + + let port = + to.inputs.get(sbs_input).cloned().or_else(|| graph.nodes.get(to.index).and_then(|node| super::image_input::read(&node.def, sbs_input))); + let to_port = match port { + Some(port) => port, + None if to.open_inputs => { + if let Some(node) = graph.nodes.get_mut(to.index) { + add_placeholder_input(node, sbs_input); + } + sbs_input.to_string() + } + None => { + let def = graph.nodes.get(to.index).map_or("", |n| n.def.as_str()); + self.warnings.add(format!("graph `{name}`: `{def}` has no input `{sbs_input}`; its wire was dropped")); + continue; + } + }; + + wires.push(Connection { from: from.id, from_port, to: to.id, to_port }); + } + } + wires + } + + pub(super) fn read_canvas_items(&mut self, element: XmlNode, graph: &mut Graph) { + for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) { + let layout = child_element(item, "GUILayout"); + let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); + let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default(); + let x = position.first().copied().unwrap_or(0.0); + let y = position.get(1).copied().unwrap_or(0.0); + let width = size.first().copied().unwrap_or(180.0).max(8.0); + let height = size.get(1).copied().unwrap_or(70.0).max(8.0); + let text = child_value(item, "GUIName").unwrap_or("").to_string(); + + match child_value(item, "type") { + Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { + let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); + let color = match channels.as_slice() { + &[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha], + _ => [0.2, 0.4, 0.8, 0.25], + }; + let title = child_value(item, "title").unwrap_or("").to_string(); + let title_visible = child_value(item, "isTitleVisible") != Some("0"); + let id = graph.alloc_id(); + + graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color }); + } + Some("COMMENT") => { + let id = graph.alloc_id(); + graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); + } + Some("PIN") => { + let id = graph.alloc_id(); + graph.pins.push(Pin { id, name: text, pos: [x, y] }); + } + Some(other) => self.warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), + None => {} + } + } + } + + pub(super) fn read_node( + &mut self, + graph: &mut Graph, + comp_node: XmlNode<'_, 'text>, + image_inputs: &HashMap<String, InputBridge>, + outputs: &HashMap<String, (String, u32)>, + ) -> ReadNode { + let gpos = child_element(comp_node, "GUILayout").and_then(|l| child_value(l, "gpos")).map(parse_floats).unwrap_or_default(); + let pos = [gpos.first().copied().unwrap_or(0.0) - NODE_HALF_SIZE[0], gpos.get(1).copied().unwrap_or(0.0) - NODE_HALF_SIZE[1]]; + let output_uids: Vec<(String, bool)> = child_element(comp_node, "compOutputs") + .into_iter() + .flat_map(|o| children_named(o, "compOutput")) + .map(|o| (child_value(o, "uid").unwrap_or("").to_string(), child_value(o, "comptype") == Some("2"))) + .collect(); + let all_outputs_to = |port: &str| output_uids.iter().map(|(uid, _)| (uid.clone(), port.to_string())).collect::<Vec<_>>(); + let text = self.text; + + let Some(implementation) = child_element(comp_node, "compImplementation").and_then(|i| i.children().find(|c| c.is_element())) else { + let (id, index, node) = push_node(graph, MISSING_NODE, pos); + if let Some(node) = node { + fill_placeholder(node, "other", "empty node", "", None, &output_uids, None); + } + return ReadNode { id, index, inputs: HashMap::new(), outputs: Vec::new(), open_inputs: true }; + }; + + let params = child_element(implementation, "parameters"); + match implementation.tag_name().name() { + "compInputBridge" => { + let entry = child_value(implementation, "entry").unwrap_or(""); + let input = image_inputs.get(entry); + let code = input.map_or(1, |input| input.type_code); + let definition = match code { + 1 => "input_color", + 2 => "input_grayscale", + _ => "input_value", + }; + + let (id, index, node) = push_node(graph, definition, pos); + if let Some(node) = node { + let identifier = input.map_or("input", |input| input.identifier.as_str()); + node.params.insert("identifier".into(), Value::Text(identifier.to_string())); + if let Some(input) = input { + node.params.insert("default".into(), input.default.clone()); + } + node.base = read_base_params(params); + } + ReadNode { id, index, inputs: HashMap::new(), outputs: all_outputs_to("output"), open_inputs: false } + } + "compOutputBridge" => { + let output = child_value(implementation, "output").unwrap_or(""); + let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), usage_index("any"))); + let (id, index, node) = push_node(graph, "output", pos); + if let Some(node) = node { + node.params.insert("identifier".into(), Value::Text(identifier)); + node.params.insert("usage".into(), Value::Enum(usage)); + } + let inputs = HashMap::from([("inputNodeOutput".to_string(), "input".to_string())]); + ReadNode { id, index, inputs, outputs: Vec::new(), open_inputs: false } + } + "compFilter" => { + let filter_name = child_value(implementation, "filter").unwrap_or(""); + let graph_name = graph.name.clone(); + match filter_by_sbs_name(filter_name).filter(|f| find(f.def).is_some()) { + Some(filter) => { + let (id, index, node) = push_node(graph, filter.def, pos); + if let Some(node) = node { + self.read_filter_params(node, filter, params, &graph_name); + super::parameter_array::read(node, implementation); + node.base = read_base_params(params); + if filter.sbs == "fxmaps" + && let Some(pattern) = child_element(implementation, "paramsGraphs").and_then(|graphs| child_element(graphs, "paramsGraph")) + { + match super::pattern_graph::read(pattern) { + Ok(pattern) => { + node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern))); + } + Err(error) => self.warnings.add(format!("pattern graph: {error}")), + } + } + } + let inputs = filter.inputs.iter().map(|(sbs, port)| (sbs.to_string(), port.to_string())).collect(); + ReadNode { id, index, inputs, outputs: all_outputs_to("output"), open_inputs: false } + } + None => { + let (id, index, node) = push_node(graph, MISSING_NODE, pos); + if let Some(node) = node { + fill_placeholder(node, "filter", filter_name, "", params.map(|p| &text[p.range()]), &output_uids, None); + } + ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(&output_uids, None), open_inputs: true } + } + } + } + "compInstance" => self.read_instance(graph, implementation, pos, &output_uids), + other => { + let (id, index, node) = push_node(graph, MISSING_NODE, pos); + if let Some(node) = node { + fill_placeholder(node, "other", other, "", None, &output_uids, None); + } + ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(&output_uids, None), open_inputs: true } + } + } + } + pub(super) fn read_instance(&mut self, graph: &mut Graph, implementation: XmlNode<'_, 'text>, pos: [f32; 2], output_uids: &[(String, bool)]) -> ReadNode { + let (path, dependency) = self.resolve_reference(child_value(implementation, "path").unwrap_or("")); + let params = child_element(implementation, "parameters"); + let bridgings: Vec<(String, String)> = child_element(implementation, "outputBridgings") + .into_iter() + .flat_map(|b| children_named(b, "outputBridging")) + .map(|b| (child_value(b, "uid").unwrap_or("").to_string(), child_value(b, "identifier").unwrap_or("output").to_string())) + .collect(); + let instance_params = + || params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))); + + let own_graph = dependency.as_deref().is_none_or(|d| d == SELF_DEPENDENCY).then(|| self.graph_names.get(&path).cloned()).flatten(); + if let Some(sub_graph) = own_graph { + let (id, index, node) = push_node(graph, "graph_instance", pos); + if let Some(node) = node { + node.params.insert("graph".into(), Value::Text(sub_graph)); + for param in instance_params() { + if let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) { + node.params.insert(child_value(param, "name").unwrap_or("").to_string(), to_natural_value(&value)); + } + } + node.base = read_base_params(params); + } + return ReadNode { id, index, inputs: HashMap::new(), outputs: bridgings, open_inputs: true }; + } + + let short_name = path.rsplit('/').next().unwrap_or(&path).to_string(); + let (id, index, node) = push_node(graph, MISSING_NODE, pos); + if let Some(node) = node { + let raw_params = params.map(|parameters| &self.text[parameters.range()]); + fill_placeholder(node, "instance", &short_name, dependency.as_deref().unwrap_or(""), raw_params, output_uids, Some(&bridgings)); + node.params.insert("sbs_path".into(), Value::Text(path)); + } + + ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(output_uids, Some(&bridgings)), open_inputs: true } + } + pub(super) fn set_param(&mut self, node: &mut Node, id: &str, like: &Value, options: usize, param: XmlNode, graph_name: &str) { + let Some(param_value) = child_element(param, "paramValue") else { return }; + + if let Some(value) = sbs_constant(param_value) { + match to_param_value(like, &value, options) { + Some(value) => { + node.params.insert(id.to_string(), value); + } + None => self.warnings.add(format!("`{}`: parameter `{id}` has a value type MaterialCraft can't read yet; kept the default", node.def)), + } + return; + } + + let Some(dynamic) = child_element(param_value, "dynamicValue") else { return }; + match function_graph::read(dynamic) { + Ok(graph) if matches!(like, Value::Function(_)) => { + node.params.insert(id.to_string(), Value::Function(Box::new(graph))); + } + Ok(graph) => { + node.functions.insert(id.to_string(), graph); + } + Err(error) => self.warnings.add(format!("graph `{graph_name}`: {} parameter `{id}`: {error}", node.def)), + } + } + + pub(super) fn read_filter_params(&mut self, node: &mut Node, filter: &FilterMap, params: Option<XmlNode>, graph_name: &str) { + let Some(def) = find(filter.def) else { return }; + + let filter_params: Vec<XmlNode> = + params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))).collect(); + for param in &filter_params { + let param_name = child_value(*param, "name").unwrap_or(""); + let value = child_element(*param, "paramValue").and_then(sbs_constant); + + if let Some(&(_, mc_name)) = filter.params.iter().find(|(sbs, _)| *sbs == param_name) { + let Some(param_def) = def.param(mc_name) else { continue }; + + self.set_param(node, mc_name, ¶m_def.default, param_def.options.len(), *param, graph_name); + continue; + } + + match (filter.sbs, param_name, value) { + ("bitmap", "bitmapresourcepath", Some(SbsValue::Text(url))) | ("svg", "vectorresourcepath", Some(SbsValue::Text(url))) => { + let (path, _) = self.resolve_reference(&url); + match self.resource_names.get(&path) { + Some(name) => { + node.params.insert("resource".into(), Value::Text(name.clone())); + } + None => self.warnings.add(format!("graph `{graph_name}`: Node uses resource `{path}`, which is not in the package")), + } + } + ("grayscaleconversion", "channelsweights", Some(weights)) => { + for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() { + node.params.insert(channel.into(), Value::Float(weights.float(i))); + } + } + _ if HANDLED_PARAMS.contains(&(filter.sbs, param_name)) => {} + _ => self.warnings.add(format!("`{}`: SBS parameter `{param_name}` is not supported yet and was ignored", filter.def)), + } + } + } +} +pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<SbsRead> { + if bytes.len() > MAX_SBS_BYTES { + return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); + } + + let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; + let text = text.trim_start_matches('\u{feff}'); + let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES }; + let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?; + let root = doc.root_element(); + if root.tag_name().name() != "package" { + return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into())); + } + + let mut warnings = Warnings::default(); + let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); + let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); + let package_name = match child_value(root, "identifier").map(str::trim) { + Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), + _ if !file_stem.is_empty() => file_stem.to_string(), + _ => "Untitled package".to_string(), + }; + + let mut reader = + SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 }; + for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { + if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { + reader.dependencies.insert(uid.to_string(), file.to_string()); + } + } + + // Load resources before resolving graph references + let content = child_element(root, "content"); + let mut pkg = Package::new(&package_name); + let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); + if let Some(content) = content { + reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); + } + + // Name every graph first so instances can refer to graphs defined later in the file + let mut names: Vec<String> = Vec::new(); + for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { + let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); + let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); + reader.graph_names.insert(path.clone(), unique.clone()); + names.push(unique); + } + if graph_elements.len() > MAX_GRAPHS { + reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); + } + + for ((_, graph), name) in graph_elements.iter().zip(names) { + let graph = reader.read_graph(*graph, name); + pkg.graphs.push(graph); + } + if pkg.graphs.is_empty() { + reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); + pkg.graphs.push(Graph::new("Graph")); + } + + report_placeholders(&pkg, reader.warnings); + Ok(SbsRead { pkg, warnings: warnings.finish() }) +} +pub fn is_sbs(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); + let mut rest = head.trim_start_matches('\u{feff}'); + + // Skip the XML declaration and comments before the root element + loop { + rest = rest.trim_start(); + let (skip_open, skip_close) = if rest.starts_with("<?") { + ("<?", "?>") + } else if rest.starts_with("<!--") { + ("<!--", "-->") + } else { + break; + }; + + match rest[skip_open.len()..].find(skip_close) { + Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], + None => return false, + } + } + + rest.strip_prefix("<package").is_some_and(|after| after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace())) +} + +pub(super) fn unique_name(taken: &[String], base: &str) -> String { + let free = |name: &str| !taken.iter().any(|t| t == name); + if free(base) { + return base.to_string(); + } + (1..).map(|i| format!("{base}_{i}")).find(|name| free(name)).unwrap_or_else(|| base.to_string()) +} +pub(super) fn push_node<'g>(graph: &'g mut Graph, def: &str, pos: [f32; 2]) -> (NodeId, usize, Option<&'g mut Node>) { + let id = graph.add_node(def, pos); + let index = graph.nodes.len() - 1; + (id, index, graph.nodes.last_mut()) +} +pub(super) fn read_graph_outputs(element: XmlNode) -> HashMap<String, (String, u32)> { + let mut outputs = HashMap::new(); + for output in child_element(element, "graphOutputs").into_iter().flat_map(|o| children_named(o, "graphoutput")) { + let identifier = child_value(output, "identifier").unwrap_or("output").to_string(); + let usage = child_element(output, "usages") + .and_then(|u| child_element(u, "usage")) + .and_then(|u| child_value(u, "name")) + .map_or(usage_index("any"), usage_index); + outputs.insert(child_value(output, "uid").unwrap_or("").to_string(), (identifier, usage)); + } + outputs +} diff --git a/crates/formats/src/sbs/sbs_value.rs b/crates/formats/src/sbs/sbs_value.rs new file mode 100644 index 00000000..98cfb262 --- /dev/null +++ b/crates/formats/src/sbs/sbs_value.rs @@ -0,0 +1,174 @@ +use super::type_code; +use super::xml::{format_float, parse_floats, parse_ints, xml_escape}; +use materialcraft_core::{Value, linear_to_srgb, srgb_to_linear}; +use roxmltree::Node as XmlNode; + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum SbsValue { + Floats(Vec<f32>), + Ints(Vec<i32>), + Bool(bool), + Text(String), +} + +impl SbsValue { + pub(super) fn float(&self, i: usize) -> f32 { + match self { + SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0), + SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0) as f32, + SbsValue::Bool(b) => f32::from(u8::from(*b)), + SbsValue::Text(_) => 0.0, + } + } + pub(super) fn int(&self, i: usize) -> i32 { + match self { + SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0), + SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0).round() as i32, + SbsValue::Bool(b) => i32::from(*b), + SbsValue::Text(_) => 0, + } + } + + pub(super) fn truthy(&self) -> bool { + match self { + SbsValue::Bool(b) => *b, + SbsValue::Text(s) => s == "1" || s.eq_ignore_ascii_case("true"), + _ => self.float(0) != 0.0, + } + } + + pub(super) fn component_count(&self) -> usize { + match self { + SbsValue::Floats(v) => v.len(), + SbsValue::Ints(v) => v.len(), + _ => 1, + } + } +} +pub(super) fn sbs_constant(holder: XmlNode) -> Option<SbsValue> { + let element = holder.children().find(|c| c.is_element())?; + let text = element.attribute("v").unwrap_or(""); + let tag = element.tag_name().name(); + + if tag == "constantValueBool" { + Some(SbsValue::Bool(parse_ints(text).first().is_some_and(|b| *b != 0) || text.trim().eq_ignore_ascii_case("true"))) + } else if tag == "constantValueString" { + Some(SbsValue::Text(text.to_string())) + } else if tag.starts_with("constantValueFloat") { + Some(SbsValue::Floats(parse_floats(text))) + } else if tag.starts_with("constantValueInt") { + Some(SbsValue::Ints(parse_ints(text))) + } else { + None + } +} +pub(super) fn to_param_value(like: &Value, value: &SbsValue, options: usize) -> Option<Value> { + let f = |i| value.float(i); + + Some(match like { + Value::Float(_) => Value::Float(f(0)), + Value::Float2(_) => Value::Float2([f(0), f(1)]), + Value::Float3(_) => Value::Float3([f(0), f(1), f(2)]), + Value::Float4(_) => Value::Float4([f(0), f(1), f(2), f(3)]), + // SBS colors are stored as displayed (sRGB); MaterialCraft's are linear + Value::Color(_) if value.component_count() >= 3 => { + let alpha = if value.component_count() >= 4 { f(3) } else { 1.0 }; + Value::Color([srgb_to_linear(f(0)), srgb_to_linear(f(1)), srgb_to_linear(f(2)), alpha]) + } + Value::Color(_) => { + let gray = srgb_to_linear(f(0)); + Value::Color([gray, gray, gray, 1.0]) + } + Value::Int(_) => Value::Int(value.int(0)), + Value::Int2(_) => Value::Int2([value.int(0), value.int(1)]), + Value::Int3(_) => Value::Int3([value.int(0), value.int(1), value.int(2)]), + Value::Int4(_) => Value::Int4([value.int(0), value.int(1), value.int(2), value.int(3)]), + Value::Bool(_) => Value::Bool(value.truthy()), + Value::Enum(_) => { + let last = options.saturating_sub(1).min(i32::MAX as usize) as i32; + Value::Enum(value.int(0).clamp(0, last) as u32) + } + Value::Text(_) => match value { + SbsValue::Text(s) => Value::Text(s.clone()), + _ => return None, + }, + Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => return None, + }) +} +pub(super) fn to_natural_value(value: &SbsValue) -> Value { + let f = |i| value.float(i); + + match value { + SbsValue::Bool(b) => Value::Bool(*b), + SbsValue::Text(s) => Value::Text(s.clone()), + SbsValue::Ints(v) if v.len() <= 1 => Value::Int(value.int(0)), + SbsValue::Ints(v) if v.len() == 2 => Value::Int2([value.int(0), value.int(1)]), + SbsValue::Ints(v) if v.len() == 3 => Value::Int3([value.int(0), value.int(1), value.int(2)]), + SbsValue::Ints(_) => Value::Int4([value.int(0), value.int(1), value.int(2), value.int(3)]), + SbsValue::Floats(v) => match v.len() { + 0 | 1 => Value::Float(f(0)), + 2 => Value::Float2([f(0), f(1)]), + 3 => Value::Float3([f(0), f(1), f(2)]), + _ => Value::Float4([f(0), f(1), f(2), f(3)]), + }, + } +} +pub(super) fn exposed_default(code: i64, value: Option<&SbsValue>) -> Value { + use type_code::*; + + let value = value.cloned().unwrap_or(SbsValue::Floats(vec![0.0])); + let f = |i| value.float(i); + match code { + BOOL => Value::Bool(value.truthy()), + INT1 => Value::Int(value.int(0)), + INT2 => Value::Int2([value.int(0), value.int(1)]), + INT3 => Value::Int3([value.int(0), value.int(1), value.int(2)]), + INT4 => Value::Int4([value.int(0), value.int(1), value.int(2), value.int(3)]), + FLOAT1 => Value::Float(f(0)), + FLOAT2 => Value::Float2([f(0), f(1)]), + FLOAT3 => Value::Float3([f(0), f(1), f(2)]), + FLOAT4 => Value::Float4([f(0), f(1), f(2), f(3)]), + STRING => match &value { + SbsValue::Text(s) => Value::Text(s.clone()), + _ => Value::Text(String::new()), + }, + _ => to_natural_value(&value), + } +} + +pub(super) fn exposed_type_code(value: &Value) -> i64 { + use type_code::*; + + match value { + Value::Bool(_) => BOOL, + Value::Int(_) | Value::Enum(_) => INT1, + Value::Int2(_) => INT2, + Value::Int3(_) => INT3, + Value::Int4(_) => INT4, + Value::Float(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => FLOAT1, + Value::Float2(_) => FLOAT2, + Value::Float3(_) => FLOAT3, + Value::Float4(_) | Value::Color(_) => FLOAT4, + Value::Text(_) => STRING, + } +} +pub(super) fn constant_xml(value: &Value) -> Option<String> { + let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::<Vec<_>>().join(" "); + let (tag, text) = match value { + Value::Float(x) => ("constantValueFloat1", format_float(*x)), + Value::Float2(x) => ("constantValueFloat2", join(x)), + Value::Float3(x) => ("constantValueFloat3", join(x)), + Value::Float4(x) => ("constantValueFloat4", join(x)), + Value::Color(c) => ("constantValueFloat4", join(&[linear_to_srgb(c[0]), linear_to_srgb(c[1]), linear_to_srgb(c[2]), c[3]])), + Value::Int(i) => ("constantValueInt32", i.to_string()), + Value::Int2(i) => ("constantValueInt2", format!("{} {}", i[0], i[1])), + Value::Int3(i) => ("constantValueInt3", format!("{} {} {}", i[0], i[1], i[2])), + Value::Int4(i) => ("constantValueInt4", format!("{} {} {} {}", i[0], i[1], i[2], i[3])), + Value::Enum(e) => ("constantValueInt32", e.to_string()), + Value::Bool(b) => ("constantValueBool", u8::from(*b).to_string()), + Value::Text(s) => ("constantValueString", s.clone()), + Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => return None, + }; + + Some(format!("<{tag} v=\"{}\"/>", xml_escape(&text))) +} diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs new file mode 100644 index 00000000..c87aeb10 --- /dev/null +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -0,0 +1,378 @@ +use super::base_parameters::base_params_xml; +use super::canvas::write_canvas_items; +use super::constant::FORMAT_VERSION; +use super::constant::{FIRST_UID, NODE_HALF_SIZE, SELF_DEPENDENCY}; +use super::embedded::encode_embedded; +use super::filter_map::filter_by_def; +use super::function_graph; +use super::node_identifiers::NodeIdentifiers; +use super::node_parameter::{param_xml, special_filter_params_xml, text_param}; +use super::output::{output_type, usage_name}; +use super::sbs_value::{constant_xml, exposed_type_code}; +use super::type_code; +use super::xml::{format_float, is_parameters_element, xml_escape}; +use crate::{FormatError, Result}; +use materialcraft_core::{Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports}; +use materialcraft_nodes::find; +use std::collections::{BTreeMap, HashMap}; +use std::fmt::Write as _; + +pub(super) struct SbsWriter { + pub(super) last_uid: u64, + pub(super) external_packages: BTreeMap<String, u64>, +} + +impl SbsWriter { + pub(super) fn next_uid(&mut self) -> u64 { + self.last_uid = self.last_uid.saturating_add(1); + self.last_uid + } + + pub(super) fn external_package_uid(&mut self, file: &str) -> u64 { + if let Some(uid) = self.external_packages.get(file) { + return *uid; + } + + let uid = self.next_uid(); + self.external_packages.insert(file.to_string(), uid); + uid + } + pub(super) fn output_ports(pkg: &Package, graph: &Graph, node: &Node) -> Vec<(String, u32)> { + match node.def.as_str() { + "output" => Vec::new(), + "graph_instance" => { + let sub_graph = match node.params.get("graph") { + Some(Value::Text(name)) => pkg.graph_by_name(name).map(|(_, g)| g), + _ => None, + }; + + let outputs = sub_graph.into_iter().flat_map(|g| g.nodes.iter().filter(|o| o.def == "output")); + outputs.map(|o| (text_param(o, "identifier", "output"), 1)).collect() + } + def if def == MISSING_NODE => missing_ports(node).1.into_iter().map(|(id, gray)| (id, if gray { 2 } else { 1 })).collect(), + "value_processor" | "input_value" | "dot" => { + let code = output_type(graph, node.id, "output"); + vec![("output".into(), code)] + } + def => match find(def) { + Some(def) => def.outputs.iter().map(|o| (o.id.to_string(), output_type(graph, node.id, o.id))).collect(), + None => vec![("output".into(), 1)], + }, + } + } + + pub(super) fn write_graph(&mut self, out: &mut String, pkg: &Package, graph: &Graph, self_uid: u64) -> Result<()> { + let _ = write!(out, "<graph><identifier v=\"{}\"/><uid v=\"{}\"/><graphtype v=\"material\"/>", xml_escape(&graph.name), self.next_uid()); + let attributes = &graph.attributes; + if !(attributes.category.is_empty() && attributes.description.is_empty() && attributes.author.is_empty() && attributes.tags.is_empty()) { + let _ = write!( + out, + "<attributes><category v=\"{}\"/><description v=\"{}\"/><author v=\"{}\"/><tags v=\"{}\"/></attributes>", + xml_escape(&attributes.category), + xml_escape(&attributes.description), + xml_escape(&attributes.author), + xml_escape(&attributes.tags) + ); + } + + let mut node_uids: HashMap<NodeId, u64> = HashMap::new(); + let mut node_outputs: HashMap<NodeId, WrittenOutputs> = HashMap::new(); + for node in &graph.nodes { + node_uids.insert(node.id, self.next_uid()); + let outputs = Self::output_ports(pkg, graph, node).into_iter().map(|(port, kind)| (port, kind, self.next_uid())).collect(); + node_outputs.insert(node.id, outputs); + } + + let input_entries = self.write_graph_inputs(out, graph); + let output_uids = self.write_graph_outputs(out, graph); + + let mut wires_into: HashMap<NodeId, Vec<&Connection>> = HashMap::new(); + for wire in &graph.connections { + wires_into.entry(wire.to).or_default().push(wire); + } + out.push_str("<compNodes>"); + for node in &graph.nodes { + let uid = node_uids.get(&node.id).copied().unwrap_or(0); + let (x, y) = (node.pos[0] + NODE_HALF_SIZE[0], node.pos[1] + NODE_HALF_SIZE[1]); + let _ = write!(out, "<compNode><uid v=\"{uid}\"/><GUILayout><gpos v=\"{} {} 0\"/></GUILayout>", format_float(x), format_float(y)); + + if !node.input_values.is_empty() { + out.push_str("<inputValues>"); + for (identifier, value) in &node.input_values { + let code = *value as u32; + let _ = write!(out, "<compInputValue><identifier v=\"{}\"/><type v=\"{code}\"/></compInputValue>", xml_escape(identifier)); + } + out.push_str("</inputValues>"); + } + + let outputs = node_outputs.get(&node.id).map_or(&[][..], Vec::as_slice); + if !outputs.is_empty() { + out.push_str("<compOutputs>"); + for (_, kind, output_uid) in outputs { + let _ = write!(out, "<compOutput><uid v=\"{output_uid}\"/><comptype v=\"{kind}\"/></compOutput>"); + } + out.push_str("</compOutputs>"); + } + + let filter = filter_by_def(&node.def); + let wires = wires_into.get(&node.id).map_or(&[][..], Vec::as_slice); + if !wires.is_empty() { + out.push_str("<connections>"); + for wire in wires { + let Some(from_uid) = node_uids.get(&wire.from) else { continue }; + let Some((_, _, output_uid)) = node_outputs.get(&wire.from).and_then(|o| o.iter().find(|(port, _, _)| *port == wire.from_port)) else { + continue; + }; + + let identifier = if node.def == "output" { + "inputNodeOutput".to_string() + } else { + let mapped = filter.and_then(|f| f.inputs.iter().find(|(_, port)| *port == wire.to_port)); + mapped + .map(|(sbs, _)| sbs.to_string()) + .or_else(|| super::image_input::write(&node.def, &wire.to_port)) + .unwrap_or_else(|| wire.to_port.clone()) + }; + + let _ = write!( + out, + "<connection><identifier v=\"{}\"/><connRef v=\"{from_uid}\"/><connRefOutput v=\"{output_uid}\"/></connection>", + xml_escape(&identifier) + ); + } + out.push_str("</connections>"); + } + + out.push_str("<compImplementation>"); + let ids = NodeIdentifiers { input_entry: input_entries.get(&node.id).copied(), graph_output: output_uids.get(&node.id).copied(), self_uid }; + self.write_implementation(out, node, outputs, ids)?; + out.push_str("</compImplementation></compNode>"); + } + out.push_str("</compNodes><baseParameters>"); + out.push_str(¶m_xml("randomseed", &Value::Int(graph.seed)).unwrap_or_default()); + out.push_str("</baseParameters>"); + + write_canvas_items(out, graph, self); + let [width, height] = graph.size.map(|s| s.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)); + let _ = write!(out, "<options><option><name v=\"defaultParentSize\"/><value v=\"{width}x{height}\"/></option></options><root><rootOutputs>"); + for uid in graph.nodes.iter().filter_map(|n| output_uids.get(&n.id)) { + let _ = write!(out, "<rootOutput><output v=\"{uid}\"/><format v=\"0\"/><usertag v=\"\"/></rootOutput>"); + } + out.push_str("</rootOutputs></root></graph>"); + Ok(()) + } + pub(super) fn write_graph_inputs(&mut self, out: &mut String, graph: &Graph) -> HashMap<NodeId, u64> { + let mut entries = HashMap::new(); + out.push_str("<paraminputs>"); + + for node in graph.nodes.iter().filter(|n| matches!(n.def.as_str(), "input_color" | "input_grayscale" | "input_value")) { + let uid = self.next_uid(); + entries.insert(node.id, uid); + let fallback = if node.def == "input_value" { Value::Float(0.0) } else { Value::Color([0.5, 0.5, 0.5, 1.0]) }; + let value = node.params.get("default").unwrap_or(&fallback); + let default = constant_xml(value).unwrap_or_default(); + let code = match node.def.as_str() { + "input_value" => exposed_type_code(value), + "input_grayscale" => type_code::GRAY_IMAGE, + _ => type_code::COLOR_IMAGE, + }; + + let _ = write!( + out, + "<paraminput><identifier v=\"{}\"/><uid v=\"{uid}\"/><isConnectable v=\"1\"/><type v=\"{code}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"\"/><options/></defaultWidget></paraminput>", + xml_escape(&text_param(node, "identifier", "input")) + ); + } + + for exposed in &graph.exposed { + let default = constant_xml(graph.inputs.get(&exposed.id).unwrap_or(&exposed.default)).unwrap_or_else(|| "<constantValueFloat1 v=\"0\"/>".into()); + let group = if exposed.group.is_empty() { String::new() } else { format!("<group v=\"{}\"/>", xml_escape(&exposed.group)) }; + let _ = write!( + out, + "<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/><attributes><label v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"slider\"/><options><option><name v=\"min\"/><value v=\"{}\"/></option><option><name v=\"max\"/><value v=\"{}\"/></option></options></defaultWidget>{group}</paraminput>", + xml_escape(&exposed.id), + self.next_uid(), + xml_escape(&exposed.label), + exposed_type_code(&exposed.default), + format_float(exposed.min), + format_float(exposed.max) + ); + } + + out.push_str("</paraminputs>"); + entries + } + pub(super) fn write_graph_outputs(&mut self, out: &mut String, graph: &Graph) -> HashMap<NodeId, u64> { + let mut output_uids = HashMap::new(); + out.push_str("<graphOutputs>"); + + for node in graph.nodes.iter().filter(|n| n.def == "output") { + let uid = self.next_uid(); + output_uids.insert(node.id, uid); + let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0).max(0) as u32; + let code = output_type(graph, node.id, "output"); + let channels = format!("<channels v=\"{code}\"/>"); + let identifier = text_param(node, "identifier", "output"); + let label = if node.label.is_empty() { identifier.clone() } else { node.label.clone() }; + let _ = write!( + out, + "<graphoutput><identifier v=\"{}\"/><uid v=\"{uid}\"/><attributes><label v=\"{}\"/></attributes><usages><usage><components v=\"RGBA\"/><name v=\"{}\"/></usage></usages><group v=\"Material\"/>{channels}</graphoutput>", + xml_escape(&identifier), + xml_escape(&label), + usage_name(usage) + ); + } + + out.push_str("</graphOutputs>"); + output_uids + } + pub(super) fn write_implementation(&mut self, out: &mut String, node: &Node, outputs: &[(String, u32, u64)], ids: NodeIdentifiers) -> Result<()> { + let base = base_params_xml(&node.base); + + match node.def.as_str() { + "output" => { + let _ = write!(out, "<compOutputBridge><output v=\"{}\"/></compOutputBridge>", ids.graph_output.unwrap_or(0)); + } + "input_color" | "input_grayscale" | "input_value" => { + let _ = write!(out, "<compInputBridge><entry v=\"{}\"/><parameters>{base}</parameters></compInputBridge>", ids.input_entry.unwrap_or(0)); + } + "graph_instance" => { + let sub_graph = text_param(node, "graph", ""); + let params: String = node.params.iter().filter(|(k, _)| *k != "graph").filter_map(|(k, v)| param_xml(k, v)).collect(); + let _ = write!( + out, + "<compInstance><path v=\"pkg:///{}?dependency={}\"/><parameters>{base}{params}</parameters>", + xml_escape(&sub_graph), + ids.self_uid + ); + write_bridgings(out, outputs); + out.push_str("</compInstance>"); + } + def if def == MISSING_NODE => { + let name = text_param(node, "sbs_name", &node.label); + let raw_params = match node.params.get("sbs_parameters") { + Some(Value::Text(s)) if is_parameters_element(s) => s.clone(), + _ => "<parameters/>".into(), + }; + + if text_param(node, "sbs_kind", "instance") == "filter" { + let _ = write!(out, "<compFilter><filter v=\"{}\"/>{raw_params}</compFilter>", xml_escape(&name)); + return Ok(()); + } + + let package = text_param(node, "sbs_package", ""); + if package.is_empty() { + return Err(FormatError::Io(format!("missing package reference for `{name}`"))); + } + let dependency = self.external_package_uid(&package); + let path = text_param(node, "sbs_path", &name); + let _ = write!(out, "<compInstance><path v=\"pkg:///{}?dependency={dependency}\"/>{raw_params}", xml_escape(&path)); + write_bridgings(out, outputs); + out.push_str("</compInstance>"); + } + def => match (filter_by_def(def), find(def)) { + (Some(filter), Some(catalog_def)) => { + let _ = write!(out, "<compFilter><filter v=\"{}\"/><parameters>{base}", filter.sbs); + let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default)); + for (sbs_name, mc_name) in filter.params { + let Some(value) = value_of(mc_name) else { continue }; + let binding = + node.bindings.get(*mc_name).map(|identifier| function_graph::binding(identifier, value)).transpose().map_err(FormatError::Io)?; + let function = node.functions.get(*mc_name).or(binding.as_ref()).or_else(|| match value { + Value::Function(graph) => Some(graph.as_ref()), + _ => None, + }); + if let Some(graph) = function { + let function = function_graph::write(graph, self).map_err(FormatError::Io)?; + let _ = write!( + out, + "<parameter><name v=\"{}\"/><relativeTo v=\"0\"/><paramValue>{function}</paramValue></parameter>", + xml_escape(sbs_name) + ); + continue; + } + out.push_str(¶m_xml(sbs_name, value).unwrap_or_default()); + } + out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid)); + out.push_str("</parameters>"); + for parameter in ["curve", "gradient"] { + if let Some(value) = value_of(parameter) { + out.push_str(&super::parameter_array::write(value, self)); + } + } + if let Some(Value::PatternGraph(graph)) = value_of("pattern") { + out.push_str(&super::pattern_graph::write(graph, self).map_err(FormatError::Io)?); + } + out.push_str("</compFilter>"); + } + _ => return Err(FormatError::Io(format!("`{def}` has no native primitive mapping; its SBS graph is required"))), + }, + } + Ok(()) + } +} +pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> { + let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; + let self_uid = writer.next_uid(); + + let mut content = String::from("<content>"); + for graph in &pkg.graphs { + if graph.function.is_some() { + super::standalone_function::write(&mut content, graph, &mut writer)?; + } else { + writer.write_graph(&mut content, pkg, graph, self_uid)?; + } + } + if !pkg.resources.is_empty() { + let _ = write!(content, "<group><uid v=\"{}\"/><identifier v=\"Resources\"/><content>", writer.next_uid()); + for resource in &pkg.resources { + let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); + let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); + let _ = write!( + content, + "<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>", + xml_escape(&resource.name), + writer.next_uid(), + if svg { "svg" } else { "bitmap" }, + xml_escape(ext), + resource.bytes.len(), + encode_embedded(resource.bytes.as_slice())? + ); + } + content.push_str("</content></group>"); + } + content.push_str("</content>"); + + let mut out = String::with_capacity(content.len() + 4096); + let _ = write!( + out, + "<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><identifier v=\"{}\"/><formatVersion v=\"{FORMAT_VERSION}\"/><updaterVersion v=\"{FORMAT_VERSION}\"/><fileUID v=\"0\"/><versionUID v=\"0\"/><dependencies>", + xml_escape(&pkg.name) + ); + let write_dependency = |out: &mut String, file: &str, uid: u64| { + let _ = write!( + out, + "<dependency><filename v=\"{}\"/><uid v=\"{uid}\"/><type v=\"package\"/><fileUID v=\"0\"/><versionUID v=\"0\"/></dependency>", + xml_escape(file) + ); + }; + + write_dependency(&mut out, SELF_DEPENDENCY, self_uid); + for (file, uid) in &writer.external_packages { + write_dependency(&mut out, file, *uid); + } + out.push_str("</dependencies>"); + out.push_str(&content); + + out.push_str("</package>\n"); + Ok(out.into_bytes()) +} +pub(super) type WrittenOutputs = Vec<(String, u32, u64)>; + +pub(super) fn write_bridgings(out: &mut String, outputs: &[(String, u32, u64)]) { + out.push_str("<outputBridgings>"); + for (port, _, uid) in outputs { + let _ = write!(out, "<outputBridging><uid v=\"{uid}\"/><identifier v=\"{}\"/></outputBridging>", xml_escape(port)); + } + out.push_str("</outputBridgings>"); +} diff --git a/crates/formats/src/sbs/standalone_function.rs b/crates/formats/src/sbs/standalone_function.rs new file mode 100644 index 00000000..585253a8 --- /dev/null +++ b/crates/formats/src/sbs/standalone_function.rs @@ -0,0 +1,28 @@ +use super::{canvas::write_canvas_items, function_graph, sbs_writer::SbsWriter, xml::xml_escape}; +use crate::{FormatError, Result}; +use materialcraft_core::Graph; +use std::fmt::Write; + +pub(super) fn write(output: &mut String, graph: &Graph, writer: &mut SbsWriter) -> Result<()> { + let function = graph.function.as_ref().ok_or_else(|| FormatError::Io("missing function graph".into()))?; + let types = materialcraft_nodes::function::node_types(function).map_err(FormatError::Io)?; + let result_type = function.output.and_then(|id| types.get(&id)).copied().unwrap_or(256); + let mut body = function_graph::write(function, writer).map_err(FormatError::Io)?; + body.truncate(body.len().saturating_sub("</dynamicValue>".len())); + write_canvas_items(&mut body, graph, writer); + body.push_str("</dynamicValue>"); + + let _ = write!(output, "<function><identifier v=\"{}\"/><uid v=\"{}\"/>", xml_escape(&graph.name), writer.next_uid()); + let attributes = &graph.attributes; + let _ = write!( + output, + "<attributes><category v=\"{}\"/><description v=\"{}\"/><author v=\"{}\"/><tags v=\"{}\"/></attributes>", + xml_escape(&attributes.category), + xml_escape(&attributes.description), + xml_escape(&attributes.author), + xml_escape(&attributes.tags) + ); + writer.write_graph_inputs(output, graph); + let _ = write!(output, "<type v=\"{result_type}\"/><paramValue>{body}</paramValue></function>"); + Ok(()) +} diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs new file mode 100644 index 00000000..ce058f1b --- /dev/null +++ b/crates/formats/src/sbs/tests.rs @@ -0,0 +1,303 @@ +use super::embedded::{base64_engine, decode_embedded, encode_embedded}; +use super::sbs_reader::{is_sbs, read_sbs}; +use super::sbs_writer::write_sbs; +use base64::Engine as _; +use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports}; + +fn no_linked_files(_: &str) -> Option<Vec<u8>> { + None +} + +fn sample_package() -> Package { + let mut pkg = Package::new("Primitives"); + let mut graph = Graph::new("Wall"); + graph.size = [9, 9]; + + let curve = graph.add_node("curve", [0.0, 0.0]); + let blur = graph.add_node("blur", [150.0, 0.0]); + let uniform = graph.add_node("uniform", [0.0, 150.0]); + let blend = graph.add_node("blend", [300.0, 0.0]); + let output = graph.add_node("output", [450.0, 0.0]); + graph.connect(curve, "output", blur, "input").unwrap(); + graph.connect(blur, "output", blend, "foreground").unwrap(); + graph.connect(uniform, "output", blend, "background").unwrap(); + graph.connect(blend, "output", output, "input").unwrap(); + + let blur_node = graph.node_mut(blur).unwrap(); + blur_node.params.insert("intensity".into(), Value::Float(4.5)); + blur_node.base.size_mode = SizeMode::Absolute; + blur_node.base.size = [8, 8]; + graph.node_mut(uniform).unwrap().params.insert("color".into(), Value::Color([0.25, 0.5, 0.75, 1.0])); + graph.node_mut(blend).unwrap().params.insert("mode".into(), Value::Enum(3)); + let output_node = graph.node_mut(output).unwrap(); + output_node.params.insert("usage".into(), Value::Enum(4)); + output_node.params.insert("identifier".into(), Value::Text("height".into())); + graph.node_mut(curve).unwrap().params.insert("curve".into(), Value::Curve(materialcraft_core::Curve::default())); + graph.frames.push(Frame { + id: 90, + title: "Frame & <title>".into(), + title_visible: false, + description: "note".into(), + rect: [-10.0, -10.0, 300.0, 200.0], + color: [0.1, 0.2, 0.3, 0.4], + }); + 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 png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); + pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); + pkg +} + +#[test] +fn sniffs_sbs() { + assert!(is_sbs(b"<?xml version=\"1.0\"?>\n<package><content/></package>")); + assert!(is_sbs(b"\xef\xbb\xbf<package>")); + assert!(is_sbs(b"<!-- hi --><package >")); + assert!(!is_sbs(b"<packages>")); + assert!(!is_sbs(b"PK\x03\x04zip")); + assert!(!is_sbs(b"<?xml")); + assert!(!is_sbs(b"")); +} + +#[test] +fn structural_round_trip() { + let pkg = sample_package(); + let plain = String::from_utf8(write_sbs(&pkg).unwrap()).unwrap(); + assert!(!plain.contains("materialcraft-package")); + assert!(!plain.contains("materialcraft://")); + let read = read_sbs(plain.as_bytes(), "x.sbs", &no_linked_files).unwrap(); + + let (original, back) = (&pkg.graphs[0], &read.pkg.graphs[0]); + assert_eq!(back.name, "Wall"); + assert_eq!(back.size, [9, 9]); + assert_eq!(back.nodes.len(), original.nodes.len()); + assert_eq!(back.connections.len(), original.connections.len()); + for (a, b) in original.nodes.iter().zip(&back.nodes) { + assert_eq!(a.def, b.def); + assert!((a.pos[0] - b.pos[0]).abs() < 1e-3 && (a.pos[1] - b.pos[1]).abs() < 1e-3); + assert_eq!(a.base, b.base); + } + + assert_eq!(back.nodes[1].params.get("intensity"), Some(&Value::Float(4.5))); + let Some(Value::Color(color)) = back.nodes[2].params.get("color") else { panic!("uniform color") }; + assert!((color[0] - 0.25).abs() < 1e-3 && (color[2] - 0.75).abs() < 1e-3); + assert_eq!(back.nodes[3].params.get("mode"), Some(&Value::Enum(3))); + assert_eq!(back.nodes[4].params.get("usage"), Some(&Value::Enum(4))); + assert_eq!(back.nodes[4].params.get("identifier"), Some(&Value::Text("height".into()))); + assert_eq!(back.frames[0].title, "Frame & <title>"); + assert!(!back.frames[0].title_visible); + assert_eq!(read.pkg.resources[0].bytes, pkg.resources[0].bytes); + + let blend = back.nodes[3].id; + assert_eq!(back.input_of(blend, "foreground").map(|c| c.from), Some(back.nodes[1].id)); + assert_eq!(back.input_of(blend, "background").map(|c| c.from), Some(back.nodes[2].id)); +} + +#[test] +fn native_data_is_the_saved_document() { + let text = String::from_utf8(write_sbs(&sample_package()).unwrap()).unwrap().replace("<identifier v=\"Wall\"/>", "<identifier v=\"Wall2\"/>"); + let read = read_sbs(text.as_bytes(), "x.sbs", &no_linked_files).unwrap(); + + assert_eq!(read.pkg.graphs[0].name, "Wall2"); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); +} + +#[test] +fn missing_nodes_are_placeholders_that_survive_saving() { + let xml = r#"<?xml version="1.0"?><package><identifier v="P"/><dependencies><dependency><filename v="sbs://noise_fancy.sbs"/><uid v="7"/></dependency></dependencies><content><graph><identifier v="G"/> + <compNodes> + <compNode><uid v="1"/><GUILayout><gpos v="0 0 0"/></GUILayout><compOutputs><compOutput><uid v="11"/><comptype v="2"/></compOutput></compOutputs> + <compImplementation><compInstance><path v="pkg:///fancy_noise?dependency=7"/><parameters><parameter><name v="scale"/><paramValue><constantValueFloat1 v="3"/></paramValue></parameter></parameters> + <outputBridgings><outputBridging><uid v="11"/><identifier v="noise"/></outputBridging></outputBridgings></compInstance></compImplementation></compNode> + <compNode><uid v="2"/><GUILayout><gpos v="200 0 0"/></GUILayout><compOutputs><compOutput><uid v="21"/><comptype v="1"/></compOutput></compOutputs> + <connections><connection><identifier v="input1"/><connRef v="1"/><connRefOutput v="11"/></connection></connections> + <compImplementation><compFilter><filter v="blur"/><parameters><parameter><name v="intensity"/><paramValue><constantValueFloat1 v="6"/></paramValue></parameter><parameter><name v="bogus"/><paramValue><constantValueFloat1 v="6"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode> + <compNode><uid v="3"/><GUILayout><gpos v="400 0 0"/></GUILayout><compOutputs><compOutput><uid v="31"/><comptype v="1"/></compOutput></compOutputs> + <connections><connection><identifier v="weird_in"/><connRef v="2"/><connRefOutput v="21"/></connection></connections> + <compImplementation><compFilter><filter v="futurefilter"/><parameters/></compFilter></compImplementation></compNode> + </compNodes></graph></content></package>"#; + let read = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); + let graph = &read.pkg.graphs[0]; + assert_eq!(graph.nodes.len(), 3); + assert_eq!(graph.connections.len(), 2); + + let fancy = &graph.nodes[0]; + assert_eq!(fancy.def, MISSING_NODE); + assert_eq!(fancy.label, "fancy_noise"); + assert_eq!(missing_ports(fancy).1, vec![("noise".to_string(), true)]); + assert_eq!(graph.nodes[1].params.get("intensity"), Some(&Value::Float(6.0))); + assert_eq!(graph.input_of(graph.nodes[1].id, "input").map(|c| c.from_port.as_str()), Some("noise")); + assert_eq!(missing_ports(&graph.nodes[2]).0, vec!["weird_in".to_string()]); + for expected in ["missing node `fancy_noise`", "missing node `futurefilter`", "bogus"] { + assert!(read.warnings.iter().any(|w| w.contains(expected)), "{expected}: {:?}", read.warnings); + } + + // Saved and read back from the SBS data alone, the placeholders are written as they came + let text = String::from_utf8(write_sbs(&read.pkg).unwrap()).unwrap(); + assert!(text.contains("sbs://noise_fancy.sbs")); + assert!(text.contains("pkg:///fancy_noise?dependency=")); + assert!(text.contains("<filter v=\"futurefilter\"/>")); + let back = read_sbs(text.as_bytes(), "p.sbs", &no_linked_files).unwrap(); + let back_graph = &back.pkg.graphs[0]; + assert_eq!(back_graph.nodes[0].def, MISSING_NODE); + assert_eq!(back_graph.nodes[0].params.get("sbs_parameters"), fancy.params.get("sbs_parameters")); + assert_eq!(back_graph.connections.len(), 2); +} + +#[test] +fn wires_keep_the_last_per_input_and_drop_cycles() { + let node = |uid: u32, wires: &str| { + format!( + "<compNode><uid v=\"{uid}\"/><compOutputs><compOutput><uid v=\"{}\"/></compOutput></compOutputs><connections>{wires}</connections><compImplementation><compFilter><filter v=\"blend\"/></compFilter></compImplementation></compNode>", + uid + 100 + ) + }; + + let wire = + |input: &str, from: u32| format!("<connection><identifier v=\"{input}\"/><connRef v=\"{from}\"/><connRefOutput v=\"{}\"/></connection>", from + 100); + let xml = format!( + "<package><content><graph><identifier v=\"G\"/><compNodes>{}{}{}{}</compNodes></graph></content></package>", + node(1, ""), + node(2, &format!("{}{}", wire("source", 1), wire("source", 4))), + node(3, &wire("source", 2)), + node(4, &wire("source", 3)) + ); + let read = read_sbs(xml.as_bytes(), "x.sbs", &no_linked_files).unwrap(); + let graph = &read.pkg.graphs[0]; + + // 2 takes 4 (the last wire), which closes 2 → 3 → 4 → 2, so one wire of that loop is dropped + assert_eq!(graph.connections.len(), 2); + assert!(graph.input_of(graph.nodes[1].id, "foreground").is_none_or(|c| c.from == graph.nodes[3].id)); + assert_eq!(graph.topo_order().len(), 4); + assert!(read.warnings.iter().any(|w| w.contains("cycle")), "{:?}", read.warnings); +} + +#[test] +fn hostile_input_is_an_error_or_a_warning_never_a_panic() { + let cases: &[&str] = &[ + "", + "<package", + "<notpackage/>", + "<!DOCTYPE package [<!ENTITY x \"y\">]><package/>", + "<package><content><graph/></content></package>", + "<package><content><graph><compNodes><compNode/><compNode><uid v=\"1\"/><compImplementation><compInstance/></compImplementation></compNode><compNode><uid v=\"1\"/></compNode></compNodes></graph></content></package>", + "<package><content><graph><options><option><name v=\"defaultParentSize\"/><value v=\"99999x-4\"/></option></options><compNodes><compNode><uid v=\"1\"/><connections><connection><identifier v=\"input1\"/><connRef v=\"1\"/><connRefOutput v=\"9\"/></connection></connections><compImplementation><compFilter><filter v=\"blur\"/><parameters><parameter><name v=\"outputsize\"/><relativeTo v=\"0\"/><paramValue><constantValueInt2 v=\"99999999999 nan\"/></paramValue></parameter><parameter><name v=\"intensity\"/><paramValue><constantValueFloat1 v=\"inf\"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph></content></package>", + "<package><content><resource><identifier v=\"r\"/><source><binembedded><strdata v=\"////\"/></binembedded></source></resource><resource><identifier v=\"s\"/><source><binembedded><strdata v=\"f////w==\"/></binembedded></source></resource><resource><identifier v=\"t\"/><filepath v=\"../../etc/passwd\"/></resource></content></package>", + "<package><content/><!-- materialcraft-package version=1 hash=0 data=AAAA --></package>", + "<package><content><group><content><group><content><graph><identifier v=\"Deep\"/></graph></content></group></content></group><function><identifier v=\"f\"/></function><weird/></content></package>", + ]; + for case in cases { + if let Ok(read) = read_sbs(case.as_bytes(), "x.sbs", &no_linked_files) { + assert!(!read.pkg.graphs.is_empty(), "{case}"); + } + } + assert!(read_sbs(b"\xff\xfe", "x.sbs", &no_linked_files).is_err()); + + let nested = read_sbs(cases[9].as_bytes(), "x.sbs", &no_linked_files).unwrap(); + assert!(nested.pkg.graphs.iter().any(|graph| graph.name == "Deep")); + assert!(nested.pkg.graphs.iter().any(|graph| graph.name == "f" && graph.function.is_some())); + assert!(nested.warnings.iter().any(|warning| warning.contains("missing function body"))); + let clamped = read_sbs(cases[6].as_bytes(), "x.sbs", &no_linked_files).unwrap(); + assert_eq!(clamped.pkg.graphs[0].size, [MAX_SIZE_LOG2, MIN_SIZE_LOG2]); + assert!(clamped.pkg.graphs[0].connections.is_empty(), "a self-wire is a cycle"); +} + +#[test] +fn linked_resources_load_through_the_callback() { + let xml = "<package><content><resource><identifier v=\"img\"/><type v=\"bitmap\"/><format v=\"png\"/><source><externalcopy><filename v=\"p.resources/img.png\"/></externalcopy></source></resource></content></package>"; + + let found = read_sbs(xml.as_bytes(), "p.sbs", &|path| (path == "p.resources/img.png").then(|| vec![1, 2, 3])).unwrap(); + assert_eq!(found.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]); + + let not_found = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); + assert!(not_found.pkg.resources.is_empty()); + assert!(not_found.warnings.iter().any(|w| w.contains("img")), "{:?}", not_found.warnings); +} + +#[test] +fn embedded_data_round_trips_and_checks_its_length() { + let data: Vec<u8> = (0..5000u32).map(|i| (i * 7 % 251) as u8).collect(); + let encoded = encode_embedded(&data).unwrap(); + assert_eq!(decode_embedded(&encoded).unwrap(), data); + + let mut raw = base64_engine().decode(&encoded).unwrap(); + raw[3] ^= 1; + assert!(decode_embedded(&base64_engine().encode(raw)).unwrap_err().contains("declared")); +} + +#[test] +fn native_function_fixture_retains_operation_types_and_ports() { + let xml = r#"<package><content><graph><identifier v="Values"/><compNodes><compNode><uid v="10"/> + <compOutputs><compOutput><uid v="11"/><comptype v="16"/></compOutput></compOutputs> + <compImplementation><compFilter><filter v="valueprocessor"/><parameters><parameter><name v="function"/><paramValue><dynamicValue> + <rootnode v="22"/><paramNodes> + <paramNode><uid v="20"/><function v="const_int1"/><type v="16"/><funcDatas><funcData><name v="const_int1"/><constantValue><constantValueInt32 v="16777217"/></constantValue></funcData></funcDatas></paramNode> + <paramNode><uid v="21"/><function v="const_int1"/><type v="16"/><funcDatas><funcData><name v="const_int1"/><constantValue><constantValueInt32 v="3"/></constantValue></funcData></funcDatas></paramNode> + <paramNode><uid v="22"/><function v="add"/><type v="16"/><connections><connection><identifier v="a"/><connRef v="20"/></connection><connection><identifier v="b"/><connRef v="21"/></connection></connections></paramNode> + </paramNodes> + </dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation> + </compNode></compNodes></graph></content></package>"#; + let read = read_sbs(xml.as_bytes(), "values.sbs", &no_linked_files).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let back = read_sbs(&write_sbs(&read.pkg).unwrap(), "values.sbs", &no_linked_files).unwrap(); + let Value::Function(function) = &back.pkg.graphs[0].nodes[0].params["function"] else { panic!("missing function") }; + assert_eq!(function.nodes[0].value, Some(Value::Int(16_777_217))); + assert_eq!(function.nodes[2].op, "add"); + assert_eq!(function.nodes[2].type_code, 16); + assert_eq!(function.nodes[2].inputs, vec![Some(function.nodes[0].id), Some(function.nodes[1].id)]); +} + +#[test] +fn image_output_types_follow_color_mode_and_blended_inputs() { + let mut package = Package::new("Channels"); + let mut graph = Graph::new("Channels"); + let gray = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(gray).unwrap().params.insert("color_mode".into(), Value::Bool(false)); + let color = graph.add_node("uniform", [0.0; 2]); + let blend = graph.add_node("blend", [0.0; 2]); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(gray, "output", blend, "foreground").unwrap(); + graph.connect(color, "output", blend, "background").unwrap(); + graph.connect(blend, "output", output, "input").unwrap(); + package.graphs.push(graph); + let bytes = write_sbs(&package).unwrap(); + let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap()).unwrap(); + let types: Vec<_> = document.descendants().filter(|node| node.has_tag_name("comptype")).map(|node| node.attribute("v").unwrap()).collect(); + assert_eq!(types, ["2", "1", "1"]); + assert_eq!(document.descendants().find(|node| node.has_tag_name("channels")).unwrap().attribute("v"), Some("1")); +} + +#[test] +fn navigation_pins_round_trip_in_graphs_and_functions() { + let canvas = r#"<GUIObjects> + <GUIObject><type v="PIN"/><GUILayout><gpos v="-128 64 0"/></GUILayout><GUIName v="Start & <review>"/><uid v="50"/></GUIObject> + <GUIObject><type v="PIN"/><GUILayout><gpos v="512 -96 0"/></GUILayout><GUIName v="Finish"/><uid v="51"/></GUIObject> + </GUIObjects>"#; + let items = [ + format!("<graph><identifier v=\"Pins\"/>{canvas}</graph>"), + format!("<function><identifier v=\"Pins\"/><paramValue><dynamicValue><paramNodes/>{canvas}</dynamicValue></paramValue></function>"), + ]; + + for item in items { + let xml = format!("<package><content>{item}</content></package>"); + let imported = read_sbs(xml.as_bytes(), "pins.sbs", &no_linked_files).unwrap(); + assert!(imported.warnings.is_empty(), "{:?}", imported.warnings); + let pins = &imported.pkg.graphs[0].pins; + assert_eq!(pins.len(), 2); + assert_eq!(pins[0].name, "Start & <review>"); + assert_eq!(pins[0].pos, [-128.0, 64.0]); + assert_eq!(pins[1].name, "Finish"); + assert_eq!(pins[1].pos, [512.0, -96.0]); + assert_ne!(pins[0].id, pins[1].id); + + let saved = write_sbs(&imported.pkg).unwrap(); + let native = roxmltree::Document::parse(std::str::from_utf8(&saved).unwrap()).unwrap(); + let pin_count = native.descendants().filter(|element| element.has_tag_name("type") && element.attribute("v") == Some("PIN")).count(); + assert_eq!(pin_count, 2); + + let reopened = read_sbs(&saved, "pins.sbs", &no_linked_files).unwrap(); + assert!(reopened.warnings.is_empty(), "{:?}", reopened.warnings); + assert_eq!(reopened.pkg.graphs[0].pins, *pins); + } +} diff --git a/crates/formats/src/sbs/type_code.rs b/crates/formats/src/sbs/type_code.rs new file mode 100644 index 00000000..8b541431 --- /dev/null +++ b/crates/formats/src/sbs/type_code.rs @@ -0,0 +1,12 @@ +pub const COLOR_IMAGE: i64 = 1; +pub const GRAY_IMAGE: i64 = 2; +pub const BOOL: i64 = 4; +pub const INT1: i64 = 16; +pub const INT2: i64 = 32; +pub const INT3: i64 = 64; +pub const INT4: i64 = 128; +pub const FLOAT1: i64 = 256; +pub const FLOAT2: i64 = 512; +pub const FLOAT3: i64 = 1024; +pub const FLOAT4: i64 = 2048; +pub const STRING: i64 = 16384; diff --git a/crates/formats/src/sbs/warnings.rs b/crates/formats/src/sbs/warnings.rs new file mode 100644 index 00000000..86406acd --- /dev/null +++ b/crates/formats/src/sbs/warnings.rs @@ -0,0 +1,31 @@ +use super::constant::MAX_WARNINGS; +use std::collections::HashMap; + +#[derive(Default)] +pub(super) struct Warnings { + pub(super) lines: Vec<(String, usize)>, + pub(super) line_index: HashMap<String, usize>, +} + +impl Warnings { + pub(super) fn add(&mut self, message: impl Into<String>) { + let message = message.into(); + if let Some(line) = self.line_index.get(&message).and_then(|&i| self.lines.get_mut(i)) { + line.1 += 1; + return; + } + + self.line_index.insert(message.clone(), self.lines.len()); + self.lines.push((message, 1)); + } + + pub(super) fn finish(self) -> Vec<String> { + let total = self.lines.len(); + let mut out: Vec<String> = + self.lines.into_iter().take(MAX_WARNINGS).map(|(line, count)| if count > 1 { format!("{line} (×{count})") } else { line }).collect(); + if total > MAX_WARNINGS { + out.push(format!("…and {} more warnings", total - MAX_WARNINGS)); + } + out + } +} diff --git a/crates/formats/src/sbs/xml.rs b/crates/formats/src/sbs/xml.rs new file mode 100644 index 00000000..73824068 --- /dev/null +++ b/crates/formats/src/sbs/xml.rs @@ -0,0 +1,45 @@ +use roxmltree::Node as XmlNode; + +pub(super) fn parse_floats(text: &str) -> Vec<f32> { + text.split_whitespace().take(16).map(|t| t.parse::<f32>().ok().filter(|v| v.is_finite()).unwrap_or(0.0)).collect() +} +pub(super) fn parse_ints(text: &str) -> Vec<i32> { + let parse = |t: &str| t.parse::<i64>().map(|v| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32).or_else(|_| t.parse::<f64>().map(|v| v as i32)); + text.split_whitespace().take(16).map(|t| parse(t).unwrap_or(0)).collect() +} +pub(super) fn format_float(v: f32) -> String { + if v.is_finite() { format!("{v}") } else { "0".into() } +} + +pub(super) fn child_element<'a, 'input>(node: XmlNode<'a, 'input>, tag: &str) -> Option<XmlNode<'a, 'input>> { + node.children().find(|c| c.is_element() && c.tag_name().name() == tag) +} + +pub(super) fn children_named<'a, 'input: 'a>(node: XmlNode<'a, 'input>, tag: &'a str) -> impl Iterator<Item = XmlNode<'a, 'input>> + 'a { + node.children().filter(move |c| c.is_element() && c.tag_name().name() == tag) +} +pub(super) fn child_value<'a>(node: XmlNode<'a, '_>, tag: &str) -> Option<&'a str> { + child_element(node, tag).and_then(|c| c.attribute("v")) +} +pub(super) fn xml_escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + '\t' => out.push_str(" "), + '\n' => out.push_str(" "), + '\r' => out.push_str(" "), + c if (c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}' => {} + c => out.push(c), + } + } + out +} +pub(super) fn is_parameters_element(xml: &str) -> bool { + let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1_000_000 }; + xml.len() < (16 << 20) && roxmltree::Document::parse_with_options(xml, options).is_ok_and(|d| d.root_element().tag_name().name() == "parameters") +} diff --git a/crates/formats/src/svg.rs b/crates/formats/src/svg.rs new file mode 100644 index 00000000..284272be --- /dev/null +++ b/crates/formats/src/svg.rs @@ -0,0 +1,32 @@ +use crate::{FormatError, Result}; +use materialcraft_image::{Image, Kind, MAX_SIDE, srgb_to_linear}; +use resvg::{tiny_skia, usvg}; + +pub(crate) fn decode(bytes: &[u8]) -> Result<Image> { + if bytes.len() > 16 << 20 { + return Err(FormatError::Image("SVG exceeds the 16 MiB limit".into())); + } + + let mut options = usvg::Options::default(); + options.image_href_resolver.resolve_string = Box::new(|_, _| None); + let tree = usvg::Tree::from_data(bytes, &options).map_err(|error| FormatError::Image(error.to_string()))?; + let size = tree.size().to_int_size(); + let (width, height) = (size.width(), size.height()); + if width > MAX_SIDE || height > MAX_SIDE { + return Err(FormatError::Image(format!("SVG exceeds {MAX_SIDE} pixels"))); + } + + let mut pixels = tiny_skia::Pixmap::new(width, height).ok_or_else(|| FormatError::Image("could not allocate SVG image".into()))?; + resvg::render(&tree, tiny_skia::Transform::identity(), &mut pixels.as_mut()); + Ok(Image::generate(width, height, Kind::Color, |x, y| { + let pixel = pixels.pixel(x, y).map(|pixel| pixel.demultiply()); + pixel.map_or([0.0; 4], |pixel| { + [ + srgb_to_linear(f32::from(pixel.red()) / 255.0), + srgb_to_linear(f32::from(pixel.green()) / 255.0), + srgb_to_linear(f32::from(pixel.blue()) / 255.0), + f32::from(pixel.alpha()) / 255.0, + ] + }) + })) +} diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs new file mode 100644 index 00000000..d415d87b --- /dev/null +++ b/crates/formats/src/tests.rs @@ -0,0 +1,52 @@ +use super::*; +use materialcraft_image::{Image, Kind, srgb_to_linear}; +use std::io::Cursor; + +#[test] +fn export_every_format() { + let img = Image::generate(8, 8, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 7.0, 0.5, 1.0]); + let gray = img.to_gray(); + for (ext, _) in EXPORT_FORMATS { + for depth in [Depth::U8, Depth::U16, Depth::F32] { + for i in [&img, &gray] { + let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); + let back = decode(&b).unwrap_or_else(|e| panic!("{ext} decode: {e}")); + assert_eq!((back.w, back.h), (8, 8)); + } + } + } + let png16 = encode(&gray, "png", Depth::U16, false).unwrap(); + assert!((decode(&png16).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); +} + +#[test] +fn names_are_safe() { + assert_eq!(output_name("$(graph)_$(usage)", "Bricks", "out", "baseColor"), "Bricks_baseColor"); + assert_eq!(safe_file_name("../../etc/passwd"), "passwd"); + assert_eq!(safe_file_name(".."), "resource"); +} + +#[test] +fn oversized_images_are_refused_before_decoding() { + let mut png = Cursor::new(Vec::new()); + ::image::GrayImage::new(8193, 1).write_to(&mut png, ::image::ImageFormat::Png).unwrap(); + let err = decode(png.get_ref()).unwrap_err().to_string(); + assert!(err.contains("8192"), "{err}"); +} + +#[test] +fn tga_still_decodes() { + let mut tga = Cursor::new(Vec::new()); + ::image::RgbaImage::new(2, 2).write_to(&mut tga, ::image::ImageFormat::Tga).unwrap(); + let img = decode(tga.get_ref()).unwrap(); + assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); +} + +#[test] +fn decode_matches_previous_values() { + let mut png = Cursor::new(Vec::new()); + ::image::RgbImage::from_pixel(2, 2, ::image::Rgb([128, 128, 128])).write_to(&mut png, ::image::ImageFormat::Png).unwrap(); + let img = decode(png.get_ref()).unwrap(); + let want = srgb_to_linear(128.0 / 255.0); + assert!((img.get(1, 1, false)[0] - want).abs() < 1e-4); +} diff --git a/crates/nodes/src/atomic.rs b/crates/nodes/src/atomic.rs deleted file mode 100644 index 7a2bcd64..00000000 --- a/crates/nodes/src/atomic.rs +++ /dev/null @@ -1,555 +0,0 @@ -//! The atomic nodes: the built-in operations every graph is made of (blend, blur, levels, -//! curve, HSL, warp, transform, normal, distance, …) plus the graph's own input, output and -//! dot nodes. - -use materialcraft_core::Gradient; -use materialcraft_image::{Image, Kind, luminance}; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::ops::{self, BLEND_MODES}; - -pub const ATOMIC: &str = "Atomic nodes"; -pub const GRAPH_ITEMS: &str = "Graph items"; - -/// Output usages (the material channel an output feeds). -pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"]; - -/// Machine ids of [`USAGES`], used in exports and inspect output. -pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("bitmap", "Bitmap", ATOMIC) - .desc("A bitmap resource of the package, resampled to the node size.") - .atomic() - .generator() - .resource("resource", "Bitmap resource") - .color_out() - .cook(bitmap), - node("blend", "Blend", ATOMIC) - .desc("Blends a foreground over a background with a blending mode, weighted by opacity and an optional mask.") - .atomic() - .any_in("foreground", "Foreground") - .any_in("background", "Background") - .gray_in("mask", "Opacity") - .float("opacity", "Opacity", 1.0, 0.0, 1.0) - .choice("mode", "Blending mode", BLEND_MODES, 0) - .choice("alpha", "Alpha blending", &["Use source alpha", "Ignore alpha"], 0) - .cook(blend), - node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).cook(blur), - node("channels_shuffle", "Channels Shuffle", ATOMIC) - .desc("Builds a color image from any channels of two inputs.") - .atomic() - .any_in("input1", "Input 1") - .any_in("input2", "Input 2") - .choice("red", "Red", CHANNEL_SOURCES, 0) - .choice("green", "Green", CHANNEL_SOURCES, 1) - .choice("blue", "Blue", CHANNEL_SOURCES, 2) - .choice("alpha", "Alpha", CHANNEL_SOURCES, 3) - .color_out() - .cook(channels_shuffle), - node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").cook(curve), - node("directional_blur", "Directional Blur", ATOMIC) - .desc("Blurs along one direction.") - .atomic() - .any_in("input", "Input") - .float("intensity", "Intensity", 10.0, 0.0, 64.0) - .angle("angle", "Angle", 0.0) - .cook(directional_blur), - node("directional_warp", "Directional Warp", ATOMIC) - .desc("Offsets the input along a direction, by an intensity map.") - .atomic() - .any_in("input", "Input") - .gray_in("intensity_input", "Intensity input") - .float("intensity", "Intensity", 10.0, 0.0, 64.0) - .angle("angle", "Warp angle", 0.0) - .cook(directional_warp), - node("distance", "Distance", ATOMIC) - .desc("Grows white areas of a mask into a distance gradient; with a source, spreads its colors outward.") - .atomic() - .gray_in("mask", "Mask") - .any_in("source", "Source") - .float("distance", "Maximum distance", 10.0, 0.0, 256.0) - .boolean("combine", "Combine distance with source", false) - .cook(distance), - node("emboss", "Emboss", ATOMIC) - .desc("Lights the input with the relief of a height map.") - .atomic() - .any_in("input", "Input") - .gray_in("height", "Height") - .float("intensity", "Intensity", 5.0, 0.0, 32.0) - .angle("light_angle", "Light angle", 0.375) - .color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0]) - .color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0]) - .cook(emboss), - node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) - .desc("Maps a grayscale input through the colors of a row of a gradient image.") - .atomic() - .gray_in("input", "Input") - .color_in("gradient", "Gradient") - .float("position", "Position", 0.5, 0.0, 1.0) - .choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0) - .color_out() - .cook(gradient_dynamic), - node("gradient_map", "Gradient Map", ATOMIC) - .desc("Maps grayscale values to colors along a gradient.") - .atomic() - .gray_in("input", "Input") - .gradient("gradient", "Gradient", Gradient::default()) - .choice("mode", "Color mode", &["Color", "Grayscale"], 0) - .cook(gradient_map), - node("grayscale_conversion", "Grayscale Conversion", ATOMIC) - .desc("Weighted sum of the RGBA channels.") - .atomic() - .color_in("input", "Input") - .float("red", "Red weight", 0.333, 0.0, 1.0) - .float("green", "Green weight", 0.333, 0.0, 1.0) - .float("blue", "Blue weight", 0.333, 0.0, 1.0) - .float("alpha", "Alpha weight", 0.0, 0.0, 1.0) - .boolean("flatten_alpha", "Flatten alpha", false) - .gray_out() - .cook(grayscale_conversion), - node("hsl", "HSL", ATOMIC) - .desc("Hue, saturation and lightness adjustments (0.5 = unchanged).") - .atomic() - .color_in("input", "Input") - .float("hue", "Hue", 0.5, 0.0, 1.0) - .float("saturation", "Saturation", 0.5, 0.0, 1.0) - .float("lightness", "Lightness", 0.5, 0.0, 1.0) - .color_out() - .cook(hsl), - node("levels", "Levels", ATOMIC) - .desc("Remaps the input range, midtones and output range.") - .atomic() - .any_in("input", "Input") - .float("in_low", "Level in low", 0.0, 0.0, 1.0) - .float("in_mid", "Level in mid", 0.5, 0.0, 1.0) - .float("in_high", "Level in high", 1.0, 0.0, 1.0) - .float("out_low", "Level out low", 0.0, 0.0, 1.0) - .float("out_high", "Level out high", 1.0, 0.0, 1.0) - .cook(levels), - node("normal", "Normal", ATOMIC) - .desc("Converts a height map to a tangent-space normal map.") - .atomic() - .gray_in("input", "Input") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) - .boolean("height_alpha", "Height in alpha", false) - .color_out() - .cook(normal), - node("pixel_processor", "Pixel Processor", ATOMIC) - .desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).") - .atomic() - .any_in("input0", "Input 0") - .any_in("input1", "Input 1") - .any_in("input2", "Input 2") - .any_in("input3", "Input 3") - .function("function", "Per pixel function", crate::function::default_pixel_function()) - .choice("output", "Output", &["Color", "Grayscale"], 0) - .cook(crate::function::pixel_processor), - node("value_processor", "Value Processor", ATOMIC) - .desc("Computes one value with a function graph and outputs it as a uniform image.") - .atomic() - .any_in("input0", "Input 0") - .function("function", "Function", materialcraft_core::function::FnGraph::constant(materialcraft_core::Value::Float(0.5))) - .cook(crate::function::value_processor), - node("sharpen", "Sharpen", ATOMIC) - .desc("Unsharp mask.") - .atomic() - .any_in("input", "Input") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .cook(sharpen), - node("transformation", "Transformation 2D", ATOMIC) - .desc("Offsets, scales and rotates the input.") - .atomic() - .any_in("input", "Input") - .float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0) - .float2("scale", "Scale", [1.0, 1.0], 0.01, 10.0) - .angle("rotation", "Rotation", 0.0) - .choice("filtering", "Filtering", &["Bilinear", "Nearest"], 0) - .color("matte", "Matte color", [0.0, 0.0, 0.0, 0.0]) - .cook(transformation), - node("uniform", "Uniform Color", ATOMIC) - .desc("A single color or gray value.") - .atomic() - .generator() - .color("color", "Color", [0.5, 0.5, 0.5, 1.0]) - .choice("mode", "Output", &["Color", "Grayscale"], 0) - .cook(uniform), - node("warp", "Warp", ATOMIC) - .desc("Distorts the input along the slopes of a gradient map.") - .atomic() - .any_in("input", "Input") - .gray_in("gradient", "Gradient") - .float("intensity", "Intensity", 1.0, 0.0, 32.0) - .cook(warp), - node("input_color", "Input Color", GRAPH_ITEMS) - .desc("A color image input of the graph.") - .atomic() - .generator() - .text("identifier", "Identifier", "input") - .color("default", "Default color", [0.5, 0.5, 0.5, 1.0]) - .color_out() - .cook(input_color_default), - node("input_grayscale", "Input Grayscale", GRAPH_ITEMS) - .desc("A grayscale image input of the graph.") - .atomic() - .generator() - .text("identifier", "Identifier", "input") - .color("default", "Default value", [0.5, 0.5, 0.5, 1.0]) - .gray_out() - .cook(input_gray_default), - node("output", "Output", GRAPH_ITEMS) - .desc("An output of the graph: a material channel (usage) or any image.") - .atomic() - .any_in("input", "Input") - .text("identifier", "Identifier", "output") - .choice("usage", "Usage", USAGES, 0) - .cook(passthrough), - node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").cook(passthrough), - node("graph_instance", "Graph Instance", GRAPH_ITEMS) - .desc("Another graph of the package, used as a node.") - .atomic() - .text("graph", "Graph", "") - .cook(crate::catalog::no_cook), - ] -} - -const CHANNEL_SOURCES: &[&str] = - &["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"]; - -fn bitmap(ctx: &Ctx) -> CookResult { - let name = ctx.text("resource"); - match (ctx.resource)(name) { - Some(img) => Ok(vec![img.resize(ctx.w, ctx.h, ctx.tile)]), - None if name.is_empty() => Ok(vec![ctx.gen_color(|u, v| { - let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 }; - [c, c, c, 1.0] - })]), - None => Err(format!("no bitmap resource `{name}`")), - } -} - -fn blend(ctx: &Ctx) -> CookResult { - let (fg, bg) = (ctx.sized(0), ctx.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(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 0.0])); - let bg = bg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 1.0])); - let mask = ctx.sized(2).map(|m| m.to_gray()); - let (mode, op) = (ctx.i("mode"), ctx.f("opacity")); - let use_alpha = ctx.i("alpha") == 0 && !fg.is_gray(); - Ok(vec![Image::generate(ctx.w, ctx.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, use_alpha, true) - })]) -} - -fn blur(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let sigma = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0 * 0.5; - Ok(vec![ops::gaussian(&img, sigma, ctx.tile)]) -} - -fn channels_shuffle(ctx: &Ctx) -> CookResult { - let a = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let b = ctx.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let src = [ctx.i("red"), ctx.i("green"), ctx.i("blue"), ctx.i("alpha")]; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - src.map(|s| match s { - 0..=3 => pa[s as usize], - 4..=7 => pb[(s - 4) as usize], - 9 => 1.0, - _ => 0.0, - }) - })]) -} - -fn curve(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let c = ctx.curve("curve"); - // A 1024-entry table: the curve is smooth, so linear lookups are exact enough. - let lut: Vec<f32> = (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) - }; - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) -} - -fn dir_vec(turns: f32) -> (f32, f32) { - let a = turns * std::f32::consts::TAU; - (a.cos(), -a.sin()) -} - -fn directional_blur(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let len = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0; - if len < 0.5 { - return Ok(vec![img]); - } - let (dx, dy) = dir_vec(ctx.f("angle")); - let n = (len.ceil() as i32).clamp(1, 512); - let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let mut acc = [0.0; 4]; - for i in -n..=n { - let t = i as f32 / n as f32 * len * 0.5; - let p = img.sample(u + dx * t * iw, v + dy * t * ih, ctx.tile); - for k in 0..4 { - acc[k] += p[k]; - } - } - acc.map(|a| a / (2 * n + 1) as f32) - })]) -} - -fn directional_warp(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let map = ctx.gray_or(1, 0.0); - let (dx, dy) = dir_vec(ctx.f("angle")); - let k = ctx.f("intensity") / 256.0; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let m = map.sample_gray(u, v, ctx.tile) * k; - img.sample(u + dx * m, v + dy * m, ctx.tile) - })]) -} - -fn distance(ctx: &Ctx) -> CookResult { - let mask = ctx.gray_or(0, 0.0); - let maxd = (ctx.f("distance").max(0.0) * ctx.w as f32 / 256.0).max(1e-3); - let data = mask.data.clone(); - let d2 = ops::distance_sq(ctx.w, ctx.h, |i| data.get(i).copied().unwrap_or(0.0) > 0.5, ctx.tile); - let Some(src) = ctx.sized(1) else { - return Ok(vec![ops::gray_from(ctx.w, ctx.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); - }; - // Spread the source's colors: each pixel takes the color of the nearest mask pixel, found by - // walking down the distance field's gradient. - let dist: Vec<f32> = d2.iter().map(|d| d.sqrt()).collect(); - let combine = ctx.b("combine"); - let (w, h) = (ctx.w as i64, ctx.h as i64); - let field = ops::gray_from(ctx.w, ctx.h, dist); - Ok(vec![Image::generate(ctx.w, ctx.h, src.kind, |x, y| { - let (mut px, mut py) = (x as f32, y as f32); - for _ in 0..64 { - let d = field.get_gray(px.round() as i64, py.round() as i64, ctx.tile); - if d < 0.5 { - break; - } - let (gx, gy) = ops::slope(&field, px.round() as i64, py.round() as i64, ctx.tile); - let g = (gx * gx + gy * gy).sqrt().max(1e-4); - px -= gx / g * d.min(8.0); - py -= gy / g * d.min(8.0); - if !ctx.tile && (px < 0.0 || py < 0.0 || px >= w as f32 || py >= h as f32) { - break; - } - } - let mut c = src.get(px.round() as i64, py.round() as i64, ctx.tile); - let d = field.get_gray(x as i64, y as i64, ctx.tile); - if d > maxd { - c = [0.0, 0.0, 0.0, if src.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]]; - } - c - })]) -} - -fn emboss(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]); - let hmap = ctx.gray_or(1, 0.0); - let (lx, ly) = dir_vec(ctx.f("light_angle")); - let k = ctx.f("intensity") * ctx.w as f32 / 64.0; - let (hi, sh) = (ctx.v4("highlight"), ctx.v4("shadow")); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, ctx.tile); - let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0); - let p = img.get(x as i64, y as i64, false); - let tint = if l >= 0.0 { hi } else { sh }; - let t = l.abs(); - [p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]] - })]) -} - -fn gradient_dynamic(ctx: &Ctx) -> CookResult { - let input = ctx.gray_or(0, 0.0); - let grad = ctx.input(1).map(|g| g.to_color()).unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Color, |u, _| [u, u, u, 1.0])); - let pos = ctx.f("position"); - let vertical = ctx.i("orientation") == 1; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let t = input.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0); - if vertical { grad.sample(pos, t, false) } else { grad.sample(t, pos, false) } - })]) -} - -fn gradient_map(ctx: &Ctx) -> CookResult { - let input = ctx.gray_or(0, 0.0); - let g = ctx.gradient("gradient"); - let lut: Vec<[f32; 4]> = (0..=512).map(|i| g.eval(i as f32 / 512.0)).collect(); - let gray = ctx.i("mode") == 1; - let look = |v: f32| lut.get((v.clamp(0.0, 1.0) * 512.0).round() as usize).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]); - 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 grayscale_conversion(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let w = [ctx.f("red"), ctx.f("green"), ctx.f("blue"), ctx.f("alpha")]; - let flatten = ctx.b("flatten_alpha"); - Ok(vec![img.map(Kind::Gray, |p| { - let mut v = p[0] * w[0] + p[1] * w[1] + p[2] * w[2] + p[3] * w[3]; - if flatten { - v *= p[3]; - } - [v, 0.0, 0.0, 0.0] - })]) -} - -fn hsl(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let (dh, sat, lig) = (ctx.f("hue") - 0.5, ctx.f("saturation"), ctx.f("lightness")); - Ok(vec![img.map(Kind::Color, |p| { - let [h, s, l] = ops::rgb_to_hsl(p); - let s = if sat <= 0.5 { s * sat * 2.0 } else { s + (1.0 - s) * (sat - 0.5) * 2.0 }; - let l = if lig <= 0.5 { l * lig * 2.0 } else { l + (1.0 - l) * (lig - 0.5) * 2.0 }; - let c = ops::hsl_to_rgb(h + dh, s.clamp(0.0, 1.0), l.clamp(0.0, 1.0)); - [c[0], c[1], c[2], p[3]] - })]) -} - -/// The Levels mapping for one value. -pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 { - let span = in_high - in_low; - let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) }; - // NaN (from an input or a hostile parameter) would otherwise spread through the graph. - let t = if t.is_finite() { t } else { 0.0 }; - let mid = in_mid.clamp(0.001, 0.999); - let g = 0.5f32.ln() / mid.ln(); - out_low + t.powf(g) * (out_high - out_low) -} - -fn levels(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let p = [ctx.f("in_low"), ctx.f("in_mid"), ctx.f("in_high"), ctx.f("out_low"), ctx.f("out_high")]; - let f = |v: f32| levels_fn(v, p[0], p[1], p[2], p[3], p[4]); - Ok(vec![img.map(img.kind, |c| [f(c[0]), f(c[1]), f(c[2]), c[3]])]) -} - -/// Tangent-space normal from a height map; `k` scales the slopes. -pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { - Image::generate(h.w, h.h, Kind::Color, |x, y| { - let (dx, dy) = ops::slope(h, x as i64, y as i64, tile); - let (nx, ny, nz) = (-dx * k, dy * k, 1.0); - let l = (nx * nx + ny * ny + nz * nz).sqrt(); - let ny = if directx { -ny } else { ny }; - let a = if alpha_height { h.get_gray(x as i64, y as i64, tile) } else { 1.0 }; - [nx / l * 0.5 + 0.5, ny / l * 0.5 + 0.5, nz / l * 0.5 + 0.5, a] - }) -} - -fn normal(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let k = ctx.f("intensity") * ctx.w as f32 / 32.0; - Ok(vec![height_to_normal(&h, k, ctx.i("format") == 1, ctx.tile, ctx.b("height_alpha"))]) -} - -fn sharpen(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let soft = ops::gaussian(&img, 1.0, ctx.tile); - let k = ctx.f("intensity"); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false)); - [a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]] - })]) -} - -/// Sample `img` through the inverse of offset → rotate → scale about the center. -pub fn transform_sample(img: &Image, u: f32, v: f32, offset: [f32; 2], scale: [f32; 2], rot_turns: f32, nearest: bool, tile: bool) -> Option<[f32; 4]> { - let (s, c) = (rot_turns * std::f32::consts::TAU).sin_cos(); - let (x, y) = (u - 0.5 - offset[0], v - 0.5 - offset[1]); - let (x, y) = (x * c - y * s, x * s + y * c); - let (sx, sy) = (if scale[0].abs() < 1e-4 { 1e-4 } else { scale[0] }, if scale[1].abs() < 1e-4 { 1e-4 } else { scale[1] }); - let (su, sv) = (x / sx + 0.5, y / sy + 0.5); - if !tile && (!(0.0..1.0).contains(&su) || !(0.0..1.0).contains(&sv)) { - return None; - } - Some(if nearest { img.sample_nearest(su, sv, tile) } else { img.sample(su, sv, tile) }) -} - -fn transformation(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let (off, sc, rot) = (ctx.v2("offset"), ctx.v2("scale"), ctx.f("rotation")); - let nearest = ctx.i("filtering") == 1; - let matte = ctx.v4("matte"); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, off, sc, rot, nearest, ctx.tile).unwrap_or(matte))]) -} - -fn uniform(ctx: &Ctx) -> CookResult { - let c = ctx.v4("color"); - Ok(vec![if ctx.i("mode") == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [luminance(c); 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, c) }]) -} - -fn warp(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let grad = ctx.gray_or(1, 0.0); - let k = ctx.f("intensity"); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = ((u * ctx.w as f32) as i64, (v * ctx.h as f32) as i64); - let (dx, dy) = ops::slope(&grad, x, y, ctx.tile); - img.sample(u + dx * k, v + dy * k, ctx.tile) - })]) -} - -fn input_color_default(ctx: &Ctx) -> CookResult { - Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, ctx.v4("default"))]) -} - -fn input_gray_default(ctx: &Ctx) -> CookResult { - Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Gray, [ctx.v4("default")[0]; 4])]) -} - -pub(crate) fn passthrough(ctx: &Ctx) -> CookResult { - Ok(vec![ctx.sized(0).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))]) -} - -/// The kind an output port produces given the node's inputs. -pub fn output_kind(def: &NodeDef, port: usize, inputs: &[Option<Image>]) -> Kind { - 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), - } -} - -#[cfg(test)] -mod levels_tests { - use super::levels_fn; - - #[test] - fn levels_remaps_the_input_range_midtones_and_output_range() { - let close = |a: f32, b: f32| (a - b).abs() < 1e-5; - // Identity by default. - for v in [0.0, 0.25, 0.5, 1.0] { - assert!(close(levels_fn(v, 0.0, 0.5, 1.0, 0.0, 1.0), v)); - } - // The input range stretches and clips. - assert!(close(levels_fn(0.4, 0.2, 0.5, 0.6, 0.0, 1.0), 0.5)); - assert!(close(levels_fn(0.1, 0.2, 0.5, 0.6, 0.0, 1.0), 0.0)); - assert!(close(levels_fn(0.9, 0.2, 0.5, 0.6, 0.0, 1.0), 1.0)); - // Mid is relative to the input range: the value there becomes 0.5. - assert!(close(levels_fn(0.25, 0.0, 0.25, 1.0, 0.0, 1.0), 0.5)); - assert!(close(levels_fn(0.3, 0.2, 0.25, 0.6, 0.0, 1.0), 0.5)); - // The output range, inverted when low > high. - assert!(close(levels_fn(0.5, 0.0, 0.5, 1.0, 0.2, 0.6), 0.4)); - assert!(close(levels_fn(0.0, 0.0, 0.5, 1.0, 1.0, 0.0), 1.0)); - // A collapsed input range is a threshold; NaN never escapes. - assert_eq!(levels_fn(0.49, 0.5, 0.5, 0.5, 0.0, 1.0), 0.0); - assert_eq!(levels_fn(0.5, 0.5, 0.5, 0.5, 0.0, 1.0), 1.0); - assert!(levels_fn(f32::NAN, 0.0, 0.5, 1.0, 0.0, 1.0).is_finite()); - assert!(levels_fn(0.5, f32::NAN, 0.5, f32::NAN, 0.0, 1.0).is_finite()); - } -} diff --git a/crates/nodes/src/atomic/bitmap.rs b/crates/nodes/src/atomic/bitmap.rs new file mode 100644 index 00000000..339feeb4 --- /dev/null +++ b/crates/nodes/src/atomic/bitmap.rs @@ -0,0 +1,27 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; + +pub(super) fn definition() -> NodeDefinition { + node("bitmap", "Bitmap", ATOMIC) + .desc("A bitmap resource of the package, resampled to the node size.") + .atomic() + .generator() + .resource("resource", "Bitmap resource") + .boolean("color_mode", "Color output", true) + .any_out() + .cook(bitmap) +} + +fn bitmap(context: &CookContext) -> CookResult { + let name = context.text("resource"); + let image = match (context.resource)(name) { + 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 }; + [c, c, c, 1.0] + }), + None => return Err(format!("no bitmap resource `{name}`")), + }; + + Ok(vec![if context.b("color_mode") { image.to_color() } else { image.to_gray() }]) +} diff --git a/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs new file mode 100644 index 00000000..51bcfbb0 --- /dev/null +++ b/crates/nodes/src/atomic/blend.rs @@ -0,0 +1,34 @@ +use super::ATOMIC; +use crate::ops; +use crate::ops::BLEND_MODES; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("blend", "Blend", ATOMIC) + .desc("Blends a foreground over a background with a blending mode, weighted by opacity and an optional mask.") + .atomic() + .any_in("foreground", "Foreground") + .any_in("background", "Background") + .gray_in("mask", "Opacity") + .float("opacity", "Opacity", 1.0, 0.0, 1.0) + .choice("mode", "Blending mode", BLEND_MODES, 0) + .boolean("alpha", "Use source alpha", true) + .any_out() + .cook(blend) +} + +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 mask = context.sized(2).map(|m| m.to_gray()); + let (mode, op) = (context.i("mode"), context.f("opacity")); + let use_alpha = context.b("alpha") && !fg.is_gray(); + 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, use_alpha, true) + })]) +} diff --git a/crates/nodes/src/atomic/blur.rs b/crates/nodes/src/atomic/blur.rs new file mode 100644 index 00000000..089e58f0 --- /dev/null +++ b/crates/nodes/src/atomic/blur.rs @@ -0,0 +1,14 @@ +use super::ATOMIC; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::Kind; + +pub(super) fn definition() -> NodeDefinition { + node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).any_out().cook(blur) +} + +fn blur(context: &CookContext) -> CookResult { + let img = context.any_or(0, Kind::Gray, [0.0; 4]); + let sigma = context.f("intensity").max(0.0) * context.w as f32 / 256.0 * 0.5; + Ok(vec![ops::gaussian(&img, sigma, context.tile)]) +} diff --git a/crates/nodes/src/atomic/catalog.rs b/crates/nodes/src/atomic/catalog.rs new file mode 100644 index 00000000..e7c82b38 --- /dev/null +++ b/crates/nodes/src/atomic/catalog.rs @@ -0,0 +1,37 @@ +use super::*; +use crate::NodeDefinition; + +pub(crate) fn defs() -> Vec<NodeDefinition> { + vec![ + bitmap::definition(), + svg::definition(), + text::definition(), + pattern_map::definition(), + blend::definition(), + blur::definition(), + channels_shuffle::definition(), + curve::definition(), + directional_blur::definition(), + directional_warp::definition(), + distance::definition(), + emboss::definition(), + gradient_dynamic::definition(), + gradient_map::definition(), + grayscale_conversion::definition(), + hsl::definition(), + levels::definition(), + normal::definition(), + motion_blur::definition(), + pixel_processor::definition(), + value_processor::definition(), + sharpen::definition(), + transformation::definition(), + uniform::definition(), + warp::definition(), + input_color::definition(), + input_value::definition(), + input_grayscale::definition(), + output::definition(), + dot::definition(), + ] +} diff --git a/crates/nodes/src/atomic/channels_shuffle.rs b/crates/nodes/src/atomic/channels_shuffle.rs new file mode 100644 index 00000000..a87aaca8 --- /dev/null +++ b/crates/nodes/src/atomic/channels_shuffle.rs @@ -0,0 +1,35 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("channels_shuffle", "Channels Shuffle", ATOMIC) + .desc("Builds a color image from any channels of two inputs.") + .atomic() + .any_in("input1", "Input 1") + .any_in("input2", "Input 2") + .choice("red", "Red", CHANNEL_SOURCES, 0) + .choice("green", "Green", CHANNEL_SOURCES, 1) + .choice("blue", "Blue", CHANNEL_SOURCES, 2) + .choice("alpha", "Alpha", CHANNEL_SOURCES, 3) + .color_out() + .cook(channels_shuffle) +} + +fn channels_shuffle(context: &CookContext) -> CookResult { + let a = context.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let b = context.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let src = [context.i("red"), context.i("green"), context.i("blue"), context.i("alpha")]; + Ok(vec![Image::generate(context.w, context.h, Kind::Color, |x, y| { + let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); + src.map(|s| match s { + 0..=3 => pa[s as usize], + 4..=7 => pb[(s - 4) as usize], + 9 => 1.0, + _ => 0.0, + }) + })]) +} + +const CHANNEL_SOURCES: &[&str] = + &["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"]; diff --git a/crates/nodes/src/atomic/curve.rs b/crates/nodes/src/atomic/curve.rs new file mode 100644 index 00000000..da61d433 --- /dev/null +++ b/crates/nodes/src/atomic/curve.rs @@ -0,0 +1,22 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::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<f32> = (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) + }; + Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) +} diff --git a/crates/nodes/src/atomic/direction.rs b/crates/nodes/src/atomic/direction.rs new file mode 100644 index 00000000..3d67131f --- /dev/null +++ b/crates/nodes/src/atomic/direction.rs @@ -0,0 +1,4 @@ +pub(super) fn direction(turns: f32) -> (f32, f32) { + let a = turns * std::f32::consts::TAU; + (a.cos(), -a.sin()) +} diff --git a/crates/nodes/src/atomic/directional_blur.rs b/crates/nodes/src/atomic/directional_blur.rs new file mode 100644 index 00000000..36f75694 --- /dev/null +++ b/crates/nodes/src/atomic/directional_blur.rs @@ -0,0 +1,40 @@ +use super::{ATOMIC, direction}; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("directional_blur", "Directional Blur", ATOMIC) + .desc("Blurs along one direction.") + .atomic() + .any_in("input", "Input") + .float("intensity", "Intensity", 10.0, 0.0, 64.0) + .angle("angle", "Angle", 0.0) + .any_out() + .cook(directional_blur) +} + +fn directional_blur(context: &CookContext) -> CookResult { + blur(context, context.f("angle")) +} + +pub(super) fn blur(context: &CookContext, angle: f32) -> CookResult { + let img = context.any_or(0, Kind::Gray, [0.0; 4]); + let len = context.f("intensity").max(0.0) * context.w as f32 / 256.0; + if len < 0.5 { + return Ok(vec![img]); + } + let (dx, dy) = direction(angle); + let n = (len.ceil() as i32).clamp(1, 512); + let (iw, ih) = (1.0 / context.w as f32, 1.0 / context.h as f32); + Ok(vec![Image::generate_uv(context.w, context.h, img.kind, |u, v| { + let mut acc = [0.0; 4]; + for i in -n..=n { + let t = i as f32 / n as f32 * len * 0.5; + let p = img.sample(u + dx * t * iw, v + dy * t * ih, context.tile); + for k in 0..4 { + acc[k] += p[k]; + } + } + acc.map(|a| a / (2 * n + 1) as f32) + })]) +} diff --git a/crates/nodes/src/atomic/directional_warp.rs b/crates/nodes/src/atomic/directional_warp.rs new file mode 100644 index 00000000..821c481d --- /dev/null +++ b/crates/nodes/src/atomic/directional_warp.rs @@ -0,0 +1,26 @@ +use super::{ATOMIC, direction}; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("directional_warp", "Directional Warp", ATOMIC) + .desc("Offsets the input along a direction, by an intensity map.") + .atomic() + .any_in("input", "Input") + .gray_in("intensity_input", "Intensity input") + .float("intensity", "Intensity", 10.0, 0.0, 64.0) + .angle("angle", "Warp angle", 0.0) + .any_out() + .cook(directional_warp) +} + +fn directional_warp(context: &CookContext) -> CookResult { + let img = 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) + })]) +} diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs new file mode 100644 index 00000000..df9da4a6 --- /dev/null +++ b/crates/nodes/src/atomic/distance.rs @@ -0,0 +1,56 @@ +use super::ATOMIC; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::Image; + +pub(super) fn definition() -> NodeDefinition { + node("distance", "Distance", ATOMIC) + .desc("Grows white areas of a mask into a distance gradient; with a source, spreads its colors outward.") + .atomic() + .gray_in("mask", "Mask input") + .any_in("source", "Source input") + .float("distance", "Maximum distance", 10.0, 0.0, 256.0) + .boolean("combine", "Combine distance with source", false) + .any_out() + .cook(distance) +} + +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(); + let d2 = ops::distance_sq(context.w, context.h, |i| data.get(i).copied().unwrap_or(0.0) > 0.5, context.tile); + let Some(src) = context.sized(1) else { + 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())]); + }; + // Spread the source's colors: each pixel takes the color of the nearest mask pixel, found by walking down the distance field's gradient + let dist: Vec<f32> = d2.iter().map(|d| d.sqrt()).collect(); + let combine = context.b("combine"); + let (w, h) = (context.w as i64, context.h as i64); + let field = ops::gray_from(context.w, context.h, dist); + Ok(vec![Image::generate(context.w, context.h, src.kind, |x, y| { + let (mut px, mut py) = (x as f32, y as f32); + for _ in 0..64 { + let d = field.get_gray(px.round() as i64, py.round() as i64, context.tile); + if d < 0.5 { + break; + } + let (gx, gy) = ops::slope(&field, px.round() as i64, py.round() as i64, context.tile); + let g = (gx * gx + gy * gy).sqrt().max(1e-4); + px -= gx / g * d.min(8.0); + py -= gy / g * d.min(8.0); + if !context.tile && (px < 0.0 || py < 0.0 || px >= w as f32 || py >= h as f32) { + break; + } + } + let mut c = src.get(px.round() as i64, py.round() as i64, context.tile); + let d = field.get_gray(x as i64, y as i64, context.tile); + if d > maxd { + c = [0.0, 0.0, 0.0, if src.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]]; + } + c + })]) +} diff --git a/crates/nodes/src/atomic/dot.rs b/crates/nodes/src/atomic/dot.rs new file mode 100644 index 00000000..73f42930 --- /dev/null +++ b/crates/nodes/src/atomic/dot.rs @@ -0,0 +1,11 @@ +use super::GRAPH_ITEMS; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{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) +} + +pub(crate) fn passthrough(context: &CookContext) -> CookResult { + Ok(vec![context.sized(0).unwrap_or_else(|| Image::filled(context.w, context.h, Kind::Gray, [0.0; 4]))]) +} diff --git a/crates/nodes/src/atomic/emboss.rs b/crates/nodes/src/atomic/emboss.rs new file mode 100644 index 00000000..66492a2e --- /dev/null +++ b/crates/nodes/src/atomic/emboss.rs @@ -0,0 +1,34 @@ +use super::{ATOMIC, direction}; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("emboss", "Emboss", ATOMIC) + .desc("Lights the input with the relief of a height map.") + .atomic() + .any_in("input", "Input") + .gray_in("height", "Intensity input") + .float("intensity", "Intensity", 5.0, 0.0, 32.0) + .angle("light_angle", "Light angle", 0.375) + .color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0]) + .color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0]) + .any_out() + .cook(emboss) +} + +fn emboss(context: &CookContext) -> CookResult { + let img = context.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]); + let hmap = context.gray_or(1, 0.0); + let (lx, ly) = direction(context.f("light_angle")); + let k = context.f("intensity") * context.w as f32 / 64.0; + let (hi, sh) = (context.v4("highlight"), context.v4("shadow")); + Ok(vec![Image::generate(context.w, context.h, img.kind, |x, y| { + let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, context.tile); + let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0); + let p = img.get(x as i64, y as i64, false); + let tint = if l >= 0.0 { hi } else { sh }; + let t = l.abs(); + [p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]] + })]) +} diff --git a/crates/nodes/src/atomic/gradient_dynamic.rs b/crates/nodes/src/atomic/gradient_dynamic.rs new file mode 100644 index 00000000..cd38bdc7 --- /dev/null +++ b/crates/nodes/src/atomic/gradient_dynamic.rs @@ -0,0 +1,26 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) + .desc("Maps a grayscale input through the colors of a row of a gradient image.") + .atomic() + .gray_in("input", "Grayscale input") + .any_in("gradient", "Gradient input") + .float("position", "Position", 0.5, 0.0, 1.0) + .choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0) + .any_out() + .cook(gradient_dynamic) +} + +fn gradient_dynamic(context: &CookContext) -> CookResult { + let input = context.gray_or(0, 0.0); + let gradient = context.input(1).cloned().unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Gray, |position, _| [position; 4])); + let position = context.f("position"); + let vertical = context.i("orientation") == 1; + 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 new file mode 100644 index 00000000..033b3054 --- /dev/null +++ b/crates/nodes/src/atomic/gradient_map.rs @@ -0,0 +1,24 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_core::Gradient; +use materialcraft_image::{Kind, luminance}; + +pub(super) fn definition() -> NodeDefinition { + node("gradient_map", "Gradient Map", ATOMIC) + .desc("Maps grayscale values to colors along a gradient.") + .atomic() + .gray_in("input", "Input") + .gradient("gradient", "Gradient", Gradient::default()) + .boolean("color_mode", "Color output", true) + .any_out() + .cook(gradient_map) +} + +fn gradient_map(context: &CookContext) -> CookResult { + let input = context.gray_or(0, 0.0); + let g = context.gradient("gradient"); + let lut: Vec<[f32; 4]> = (0..=512).map(|i| g.eval(i as f32 / 512.0)).collect(); + let gray = !context.b("color_mode"); + let look = |v: f32| lut.get((v.clamp(0.0, 1.0) * 512.0).round() as usize).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]); + 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])) }]) +} diff --git a/crates/nodes/src/atomic/grayscale_conversion.rs b/crates/nodes/src/atomic/grayscale_conversion.rs new file mode 100644 index 00000000..8f14943c --- /dev/null +++ b/crates/nodes/src/atomic/grayscale_conversion.rs @@ -0,0 +1,32 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::Kind; + +pub(super) fn definition() -> NodeDefinition { + node("grayscale_conversion", "Grayscale Conversion", ATOMIC) + .desc("Weighted sum of the RGBA channels.") + .atomic() + .color_in("input", "Input") + .float("red", "Red weight", 0.333, 0.0, 1.0) + .float("green", "Green weight", 0.333, 0.0, 1.0) + .float("blue", "Blue weight", 0.333, 0.0, 1.0) + .float("alpha", "Alpha weight", 0.0, 0.0, 1.0) + .boolean("flatten_alpha", "Flatten alpha", false) + .float("matte", "Matte level", 0.0, 0.0, 1.0) + .gray_out() + .cook(grayscale_conversion) +} + +fn grayscale_conversion(context: &CookContext) -> CookResult { + let img = context.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let w = [context.f("red"), context.f("green"), context.f("blue"), context.f("alpha")]; + let flatten = context.b("flatten_alpha"); + let matte = context.f("matte"); + Ok(vec![img.map(Kind::Gray, |p| { + let mut v = p[0] * w[0] + p[1] * w[1] + p[2] * w[2] + p[3] * w[3]; + if flatten { + v = v * p[3] + matte * (1.0 - p[3]); + } + [v, 0.0, 0.0, 0.0] + })]) +} diff --git a/crates/nodes/src/atomic/hsl.rs b/crates/nodes/src/atomic/hsl.rs new file mode 100644 index 00000000..f174f2ba --- /dev/null +++ b/crates/nodes/src/atomic/hsl.rs @@ -0,0 +1,28 @@ +use super::ATOMIC; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::Kind; + +pub(super) fn definition() -> NodeDefinition { + node("hsl", "HSL", ATOMIC) + .desc("Hue, saturation and lightness adjustments (0.5 = unchanged).") + .atomic() + .color_in("input", "Input") + .float("hue", "Hue", 0.5, 0.0, 1.0) + .float("saturation", "Saturation", 0.5, 0.0, 1.0) + .float("lightness", "Lightness", 0.5, 0.0, 1.0) + .color_out() + .cook(hsl) +} + +fn hsl(context: &CookContext) -> CookResult { + let img = context.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); + let (dh, sat, lig) = (context.f("hue") - 0.5, context.f("saturation"), context.f("lightness")); + Ok(vec![img.map(Kind::Color, |p| { + let [h, s, l] = ops::rgb_to_hsl(p); + let s = if sat <= 0.5 { s * sat * 2.0 } else { s + (1.0 - s) * (sat - 0.5) * 2.0 }; + let l = if lig <= 0.5 { l * lig * 2.0 } else { l + (1.0 - l) * (lig - 0.5) * 2.0 }; + let c = ops::hsl_to_rgb(h + dh, s.clamp(0.0, 1.0), l.clamp(0.0, 1.0)); + [c[0], c[1], c[2], p[3]] + })]) +} diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs new file mode 100644 index 00000000..6cea4eff --- /dev/null +++ b/crates/nodes/src/atomic/input_color.rs @@ -0,0 +1,18 @@ +use super::GRAPH_ITEMS; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("input_color", "Input Color", GRAPH_ITEMS) + .desc("A color image input of the graph.") + .atomic() + .generator() + .text("identifier", "Identifier", "input") + .color("default", "Default color", [0.5, 0.5, 0.5, 1.0]) + .color_out() + .cook(input_color_default) +} + +fn input_color_default(context: &CookContext) -> CookResult { + Ok(vec![Image::filled(context.w, context.h, Kind::Color, context.v4("default"))]) +} diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs new file mode 100644 index 00000000..ac1f1f15 --- /dev/null +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -0,0 +1,18 @@ +use super::GRAPH_ITEMS; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("input_grayscale", "Input Grayscale", GRAPH_ITEMS) + .desc("A grayscale image input of the graph.") + .atomic() + .generator() + .text("identifier", "Identifier", "input") + .color("default", "Default value", [0.5, 0.5, 0.5, 1.0]) + .gray_out() + .cook(input_gray_default) +} + +fn input_gray_default(context: &CookContext) -> CookResult { + Ok(vec![Image::filled(context.w, context.h, Kind::Gray, [context.v4("default")[0]; 4])]) +} diff --git a/crates/nodes/src/atomic/input_value.rs b/crates/nodes/src/atomic/input_value.rs new file mode 100644 index 00000000..b28aa98a --- /dev/null +++ b/crates/nodes/src/atomic/input_value.rs @@ -0,0 +1,12 @@ +use super::GRAPH_ITEMS; +use crate::{NodeDefinition, PortKind, node}; + +pub(super) fn definition() -> NodeDefinition { + node("input_value", "Input Value", GRAPH_ITEMS) + .desc("A typed value input of the graph.") + .atomic() + .text("identifier", "Identifier", "value") + .float("default", "Default", 0.0, 0.0, 0.0) + .output("output", "Value", PortKind::Value) + .cook(crate::node_definition_builder::no_cook) +} diff --git a/crates/nodes/src/atomic/levels.rs b/crates/nodes/src/atomic/levels.rs new file mode 100644 index 00000000..079f7b46 --- /dev/null +++ b/crates/nodes/src/atomic/levels.rs @@ -0,0 +1,69 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::Kind; + +pub(super) fn definition() -> NodeDefinition { + node("levels", "Levels", ATOMIC) + .desc("Remaps the input range, midtones and output range.") + .atomic() + .any_in("input", "Input") + .float4("in_low", "Level in low", [0.0; 4], 0.0, 1.0) + .float4("in_mid", "Level in mid", [0.5; 4], 0.0, 1.0) + .float4("in_high", "Level in high", [1.0; 4], 0.0, 1.0) + .float4("out_low", "Level out low", [0.0; 4], 0.0, 1.0) + .float4("out_high", "Level out high", [1.0; 4], 0.0, 1.0) + .any_out() + .cook(levels) +} + +fn levels(context: &CookContext) -> CookResult { + let image = context.any_or(0, Kind::Gray, [0.0; 4]); + let low = context.v4("in_low"); + let mid = context.v4("in_mid"); + let high = context.v4("in_high"); + let output_low = context.v4("out_low"); + let output_high = context.v4("out_high"); + + 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])) + })]) +} + +pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 { + let span = in_high - in_low; + let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) }; + // NaN (from an input or a hostile parameter) would otherwise spread through the graph + let t = if t.is_finite() { t } else { 0.0 }; + let mid = in_mid.clamp(0.001, 0.999); + let g = 0.5f32.ln() / mid.ln(); + out_low + t.powf(g) * (out_high - out_low) +} + +#[cfg(test)] +mod levels_tests { + use super::levels_fn; + + #[test] + fn levels_remaps_the_input_range_midtones_and_output_range() { + let close = |a: f32, b: f32| (a - b).abs() < 1e-5; + // Identity by default + for v in [0.0, 0.25, 0.5, 1.0] { + assert!(close(levels_fn(v, 0.0, 0.5, 1.0, 0.0, 1.0), v)); + } + // The input range stretches and clips + assert!(close(levels_fn(0.4, 0.2, 0.5, 0.6, 0.0, 1.0), 0.5)); + assert!(close(levels_fn(0.1, 0.2, 0.5, 0.6, 0.0, 1.0), 0.0)); + assert!(close(levels_fn(0.9, 0.2, 0.5, 0.6, 0.0, 1.0), 1.0)); + // Mid is relative to the input range: the value there becomes 0.5 + assert!(close(levels_fn(0.25, 0.0, 0.25, 1.0, 0.0, 1.0), 0.5)); + assert!(close(levels_fn(0.3, 0.2, 0.25, 0.6, 0.0, 1.0), 0.5)); + // The output range, inverted when low > high + assert!(close(levels_fn(0.5, 0.0, 0.5, 1.0, 0.2, 0.6), 0.4)); + assert!(close(levels_fn(0.0, 0.0, 0.5, 1.0, 1.0, 0.0), 1.0)); + // A collapsed input range is a threshold; NaN never escapes + assert_eq!(levels_fn(0.49, 0.5, 0.5, 0.5, 0.0, 1.0), 0.0); + assert_eq!(levels_fn(0.5, 0.5, 0.5, 0.5, 0.0, 1.0), 1.0); + assert!(levels_fn(f32::NAN, 0.0, 0.5, 1.0, 0.0, 1.0).is_finite()); + assert!(levels_fn(0.5, f32::NAN, 0.5, f32::NAN, 0.0, 1.0).is_finite()); + } +} diff --git a/crates/nodes/src/atomic/mod.rs b/crates/nodes/src/atomic/mod.rs new file mode 100644 index 00000000..7cea5328 --- /dev/null +++ b/crates/nodes/src/atomic/mod.rs @@ -0,0 +1,45 @@ +mod bitmap; +mod blend; +mod blur; +mod channels_shuffle; +mod curve; +mod directional_blur; +mod directional_warp; +mod distance; +mod dot; +mod emboss; +mod gradient_dynamic; +mod gradient_map; +mod grayscale_conversion; +mod hsl; +mod input_color; +mod input_grayscale; +mod input_value; +mod levels; +mod motion_blur; +mod normal; +mod output; +mod pattern_map; +mod pixel_processor; +mod sharpen; +mod svg; +mod text; +mod transformation; +mod uniform; +mod value_processor; +mod warp; + +mod catalog; +mod direction; + +pub(crate) use catalog::defs; +use direction::direction; + +pub const ATOMIC: &str = "Atomic nodes"; +pub const GRAPH_ITEMS: &str = "Graph items"; +pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"]; +pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; + +pub use levels::levels_fn; +pub use normal::height_to_normal; +pub use output::output_kind; diff --git a/crates/nodes/src/atomic/motion_blur.rs b/crates/nodes/src/atomic/motion_blur.rs new file mode 100644 index 00000000..69da3bd0 --- /dev/null +++ b/crates/nodes/src/atomic/motion_blur.rs @@ -0,0 +1,17 @@ +use super::{ATOMIC, directional_blur}; +use crate::{CookContext, CookResult, NodeDefinition, node}; + +pub(super) fn definition() -> NodeDefinition { + node("motion_blur", "Motion Blur", ATOMIC) + .desc("Blurs the input along a motion direction.") + .atomic() + .any_in("input", "Input") + .float("intensity", "Intensity", 10.0, 0.0, 64.0) + .angle("shiftangle", "Angle", 0.0) + .any_out() + .cook(cook) +} + +fn cook(context: &CookContext) -> CookResult { + directional_blur::blur(context, context.f("shiftangle")) +} diff --git a/crates/nodes/src/atomic/normal.rs b/crates/nodes/src/atomic/normal.rs new file mode 100644 index 00000000..6739c214 --- /dev/null +++ b/crates/nodes/src/atomic/normal.rs @@ -0,0 +1,33 @@ +use super::ATOMIC; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("normal", "Normal", ATOMIC) + .desc("Converts a height map to a tangent-space normal map.") + .atomic() + .gray_in("input", "Input") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .boolean("opengl", "OpenGL normals", true) + .boolean("height_alpha", "Height in alpha", false) + .color_out() + .cook(normal) +} + +fn normal(context: &CookContext) -> CookResult { + let h = context.gray_or(0, 0.0); + let k = context.f("intensity") * context.w as f32 / 32.0; + Ok(vec![height_to_normal(&h, k, !context.b("opengl"), context.tile, context.b("height_alpha"))]) +} + +pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { + Image::generate(h.w, h.h, Kind::Color, |x, y| { + let (dx, dy) = ops::slope(h, x as i64, y as i64, tile); + let (nx, ny, nz) = (-dx * k, dy * k, 1.0); + let l = (nx * nx + ny * ny + nz * nz).sqrt(); + let ny = if directx { -ny } else { ny }; + let a = if alpha_height { h.get_gray(x as i64, y as i64, tile) } else { 1.0 }; + [nx / l * 0.5 + 0.5, ny / l * 0.5 + 0.5, nz / l * 0.5 + 0.5, a] + }) +} diff --git a/crates/nodes/src/atomic/output.rs b/crates/nodes/src/atomic/output.rs new file mode 100644 index 00000000..775d8201 --- /dev/null +++ b/crates/nodes/src/atomic/output.rs @@ -0,0 +1,22 @@ +use super::dot::passthrough; +use super::{GRAPH_ITEMS, USAGES}; +use crate::{NodeDefinition, PortKind, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("output", "Output", GRAPH_ITEMS) + .desc("An output of the graph: a material channel (usage) or any image.") + .atomic() + .any_in("input", "Input") + .text("identifier", "Identifier", "output") + .choice("usage", "Usage", USAGES, 0) + .cook(passthrough) +} + +pub fn output_kind(def: &NodeDefinition, port: usize, inputs: &[Option<Image>]) -> Kind { + 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), + } +} diff --git a/crates/nodes/src/atomic/pattern_map.rs b/crates/nodes/src/atomic/pattern_map.rs new file mode 100644 index 00000000..ee338d52 --- /dev/null +++ b/crates/nodes/src/atomic/pattern_map.rs @@ -0,0 +1,18 @@ +use super::ATOMIC; +use crate::{NodeDefinition, node}; +use materialcraft_core::{PatternGraph, PatternNodeKind}; + +pub(super) fn definition() -> NodeDefinition { + node("fx_map", "FX-Map", ATOMIC) + .desc("Places patterns using Quadrant, Switch and Iterate nodes.") + .atomic() + .generator() + .any_in("background", "Background") + .any_in("pattern0", "Input image 0") + .pattern_graph("pattern", "FX-Map graph", PatternGraph::with_root(PatternNodeKind::Quadrant)) + .float("opacity", "Opacity", 1.0, 0.0, 10.0) + .boolean("color_mode", "Color output", false) + .color("background", "Background color", [0.0, 0.0, 0.0, 1.0]) + .any_out() + .cook(crate::pattern::cook) +} diff --git a/crates/nodes/src/atomic/pixel_processor.rs b/crates/nodes/src/atomic/pixel_processor.rs new file mode 100644 index 00000000..07ba8a0a --- /dev/null +++ b/crates/nodes/src/atomic/pixel_processor.rs @@ -0,0 +1,13 @@ +use super::ATOMIC; +use crate::{NodeDefinition, node}; + +pub(super) fn definition() -> NodeDefinition { + node("pixel_processor", "Pixel Processor", ATOMIC) + .desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).") + .atomic() + .any_in("input0", "Input image 0") + .function("function", "Per pixel function", crate::function::default_pixel_function()) + .boolean("color_mode", "Color output", true) + .any_out() + .cook(crate::function::pixel_processor) +} diff --git a/crates/nodes/src/atomic/sharpen.rs b/crates/nodes/src/atomic/sharpen.rs new file mode 100644 index 00000000..ef2bd464 --- /dev/null +++ b/crates/nodes/src/atomic/sharpen.rs @@ -0,0 +1,24 @@ +use super::ATOMIC; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("sharpen", "Sharpen", ATOMIC) + .desc("Unsharp mask.") + .atomic() + .any_in("input", "Input") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .any_out() + .cook(sharpen) +} + +fn sharpen(context: &CookContext) -> CookResult { + let img = context.any_or(0, Kind::Gray, [0.0; 4]); + let soft = ops::gaussian(&img, 1.0, context.tile); + let k = context.f("intensity"); + Ok(vec![Image::generate(context.w, context.h, img.kind, |x, y| { + let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false)); + [a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]] + })]) +} diff --git a/crates/nodes/src/atomic/svg.rs b/crates/nodes/src/atomic/svg.rs new file mode 100644 index 00000000..7ae5e182 --- /dev/null +++ b/crates/nodes/src/atomic/svg.rs @@ -0,0 +1,26 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node, raster::composite}; + +pub(super) fn definition() -> NodeDefinition { + node("svg", "SVG", ATOMIC) + .desc("Renders an SVG resource from the package.") + .atomic() + .generator() + .any_in("background", "Background") + .resource("resource", "SVG resource") + .boolean("color_mode", "Color output", true) + .color("background", "Background color", [0.0; 4]) + .any_out() + .cook(svg) +} + +fn svg(context: &CookContext) -> CookResult { + let name = context.text("resource"); + let foreground = if name.is_empty() { + None + } else { + Some((context.resource)(name).ok_or_else(|| format!("SVG resource `{name}` could not be decoded"))?.resize(context.w, context.h, false)) + }; + + Ok(vec![composite(context, |x, y| foreground.as_ref().map_or([0.0; 4], |image| image.get(i64::from(x), i64::from(y), false)))]) +} diff --git a/crates/nodes/src/text.rs b/crates/nodes/src/atomic/text.rs similarity index 51% rename from crates/nodes/src/text.rs rename to crates/nodes/src/atomic/text.rs index c0903e4c..e9140558 100644 --- a/crates/nodes/src/text.rs +++ b/crates/nodes/src/atomic/text.rs @@ -1,15 +1,10 @@ -//! Atomic › Text: renders a string with MaterialCraft's own single-stroke vector font, drawn as -//! anti-aliased capsules. The font is original data defined below. - -use std::f32::consts::TAU; +//! Original single-stroke font rendered as anti-aliased capsules use crate::atomic::ATOMIC; -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::svg::{Capsules, Seg, composite}; +use crate::raster::{CapsuleRaster, CapsuleSegment, composite}; +use crate::{CookContext, CookResult, NodeDefinition, node}; -/// The font: each glyph is strokes separated by spaces, each stroke a polyline of `xy` digit -/// pairs on a grid 4 wide where y = 0 is the cap height, 2 the x-height, 6 the baseline and 8 -/// the descender. A single pair is a dot. Original design for MaterialCraft. +/// The font: each glyph is strokes separated by spaces, each stroke a polyline of `xy` digit pairs on a grid 4 wide where y = 0 is the cap height, 2 the x-height, 6 the baseline and 8 the descender const GLYPHS: &[(char, &str)] = &[ ('A', "062046 1333"), ('B', "06003041423303 3344453606"), @@ -99,88 +94,90 @@ const GLYPHS: &[(char, &str)] = &[ (' ', ""), ]; -/// A character's strokes; unknown characters show as `?`. +/// A character's strokes; unknown characters show as `?` fn glyph(c: char) -> &'static str { let find = |c: char| GLYPHS.iter().find(|(g, _)| *g == c).map(|(_, s)| *s); find(c).or_else(|| find('?')).unwrap_or("") } -/// The strokes of `s` as polylines in grid units. +/// The strokes of `s` as polylines in grid units fn strokes(s: &str) -> impl Iterator<Item = Vec<[f32; 2]>> + '_ { s.split(' ') .filter(|t| !t.is_empty()) .map(|t| t.as_bytes().chunks_exact(2).map(|p| [p[0].saturating_sub(b'0') as f32, p[1].saturating_sub(b'0') as f32]).collect()) } -/// Longest text drawn (an allocation cap). +/// Longest text drawn (an allocation cap) const MAX_CHARS: usize = 10_000; -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("text", "Text", ATOMIC) - .desc("Draws text with a built-in single-stroke font (A–Z, a–z, 0–9, punctuation). \\n starts a new line.") - .atomic() - .generator() - .text("text", "Text", "MaterialCraft") - .float("size", "Size", 0.09, 0.0, 1.0) - .float2("position", "Position", [0.5, 0.5], 0.0, 1.0) - .choice("alignment", "Alignment", &["Left", "Center", "Right"], 1) - .color("color", "Color", [1.0, 1.0, 1.0, 1.0]) - .float("weight", "Stroke weight", 0.7, 0.05, 3.0) - .float("letter_spacing", "Letter spacing", 1.0, 0.0, 5.0) - .float("line_spacing", "Line spacing", 1.0, 0.0, 5.0) - .angle("rotation", "Rotation", 0.0) - .boolean("tiling", "Tiling (wrap at edges)", true) - .color_out() - .cook(text), - ] +pub(super) fn definition() -> NodeDefinition { + node("text", "Text", ATOMIC) + .desc("Draws text with a built-in single-stroke font (A–Z, a–z, 0–9, punctuation). \\n starts a new line.") + .atomic() + .generator() + .any_in("background", "Background") + .boolean("color_mode", "Color output", false) + .color("background", "Background color", [0.0, 0.0, 0.0, 1.0]) + .text("text", "Text", "MaterialCraft") + .text("fontdata", "Font reference", "") + .float("fontsize", "Font size", 0.09, 0.0, 1.0) + .float2("position", "Position", [0.0; 2], -1.0, 1.0) + .float4("matrix", "Transform matrix", [1.0, 0.0, 0.0, 1.0], -10.0, 10.0) + .choice("alignment", "Alignment", &["Left", "Center", "Right"], 1) + .any_out() + .cook(text) } -/// The capsule segments of `txt` in pixel space. -fn layout(ctx: &Ctx, txt: &str) -> Vec<Seg> { - let unit = ctx.f("size").max(0.0) * ctx.h as f32 / 8.0; - let (adv, line_h) = (4.0 + 2.0 * ctx.f("letter_spacing"), 10.0 * ctx.f("line_spacing")); - let (align, pos) = (ctx.i("alignment"), ctx.v2("position")); - let (s, c) = (ctx.f("rotation") * TAU).sin_cos(); - let anchor = [pos[0] * ctx.w as f32, pos[1] * ctx.h as f32]; - let lines: Vec<&str> = txt.split('\n').collect(); - // The block is centered vertically on the anchor (cap height of the first line to baseline of the last). - let top = -((lines.len().max(1) - 1) as f32 * line_h + 6.0) * 0.5; - let mut segs = Vec::new(); - for (li, line) in lines.iter().enumerate() { +/// The capsule segments of `text` in pixel space +fn layout(context: &CookContext, text: &str) -> Vec<CapsuleSegment> { + let unit = context.f("fontsize").max(0.0) * context.h as f32 / 8.0; + let (advance, line_height) = (6.0, 10.0); + let (alignment, position) = (context.i("alignment"), context.v2("position")); + let matrix = context.v4("matrix"); + let anchor = [(0.5 + position[0]) * context.w as f32, (0.5 + position[1]) * context.h as f32]; + let lines: Vec<&str> = text.split('\n').collect(); + // The block is centered vertically on the anchor (cap height of the first line to baseline of the last) + let top = -((lines.len().max(1) - 1) as f32 * line_height + 6.0) * 0.5; + let mut segments = Vec::new(); + for (line_index, line) in lines.iter().enumerate() { let n = line.chars().count() as f32; - let width = if n > 0.0 { (n - 1.0) * adv + 4.0 } else { 0.0 }; - let x0 = match align { + let width = if n > 0.0 { (n - 1.0) * advance + 4.0 } else { 0.0 }; + let x0 = match alignment { 0 => 0.0, 1 => -width * 0.5, _ => -width, }; - let y0 = top + li as f32 * line_h; - for (ci, ch) in line.chars().enumerate() { - let gx = x0 + ci as f32 * adv; - for stroke in strokes(glyph(ch)) { - let px: Vec<[f32; 2]> = stroke + + let y0 = top + line_index as f32 * line_height; + for (character_index, character) in line.chars().enumerate() { + let glyph_x = x0 + character_index as f32 * advance; + for stroke in strokes(glyph(character)) { + let points: Vec<[f32; 2]> = stroke .iter() .map(|p| { - let (x, y) = ((gx + p[0]) * unit, (y0 + p[1]) * unit); - [anchor[0] + x * c + y * s, anchor[1] - x * s + y * c] + let (x, y) = ((glyph_x + p[0]) * unit, (y0 + p[1]) * unit); + [anchor[0] + x * matrix[0] + y * matrix[1], anchor[1] + x * matrix[2] + y * matrix[3]] }) .collect(); - match px.as_slice() { - [a] => segs.push(Seg { a: *a, b: *a, wt: 1.0 }), - _ => segs.extend(px.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 })), + match points.as_slice() { + [a] => segments.push(CapsuleSegment { start: *a, end: *a, weight: 1.0 }), + _ => segments.extend(points.windows(2).map(|w| CapsuleSegment { start: w[0], end: w[1], weight: 1.0 })), } } } } - segs + segments } -fn text(ctx: &Ctx) -> CookResult { - let txt: String = ctx.text("text").replace("\\n", "\n").chars().take(MAX_CHARS).collect(); - let r = ctx.f("weight").max(0.0) * ctx.f("size").max(0.0) * ctx.h as f32 / 16.0; - let caps = Capsules::new(layout(ctx, &txt), r, ctx.w, ctx.h, ctx.b("tiling")); - Ok(vec![composite(ctx.w, ctx.h, ctx.v4("color"), |x, y| caps.coverage(x as f32 + 0.5, y as f32 + 0.5), [0.0; 4], |_, _| 0.0)]) +fn text(context: &CookContext) -> CookResult { + if !context.text("fontdata").is_empty() { + return Err("external fonts are not supported yet; clear Font reference to use the built-in stroke font".into()); + } + + let text: String = context.text("text").replace("\\n", "\n").chars().take(MAX_CHARS).collect(); + let radius = 0.7 * context.f("fontsize").max(0.0) * context.h as f32 / 16.0; + let raster = CapsuleRaster::new(layout(context, &text), radius, context.w, context.h, context.tile); + Ok(vec![composite(context, |x, y| [1.0, 1.0, 1.0, raster.coverage(x as f32 + 0.5, y as f32 + 0.5)])]) } #[cfg(test)] @@ -188,7 +185,7 @@ mod tests { use std::collections::BTreeMap; use super::*; - use crate::catalog::{find, resolve_params}; + use crate::{find, resolve_params}; #[test] fn font_data_is_well_formed() { @@ -209,11 +206,11 @@ mod tests { let p = resolve_params(def, &BTreeMap::new()); let no_res = |_: &str| None; let vars = BTreeMap::new(); - let ctx = Ctx { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; - let img = &text(&ctx).unwrap()[0]; - let lit = img.data.chunks(4).filter(|p| p[3] > 0.5).count(); + let context = CookContext { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; + let img = &text(&context).unwrap()[0]; + let lit = img.data.iter().filter(|value| **value > 0.5).count(); assert!(lit > 300, "{lit} pixels"); - // Centered: nothing in the top and bottom quarters. - assert!((0..256).all(|x| img.get(x, 20, false)[3] == 0.0 && img.get(x, 236, false)[3] == 0.0)); + // Centered: nothing in the top and bottom quarters + assert!((0..256).all(|x| img.get(x, 20, false)[0] == 0.0 && img.get(x, 236, false)[0] == 0.0)); } } diff --git a/crates/nodes/src/atomic/transformation.rs b/crates/nodes/src/atomic/transformation.rs new file mode 100644 index 00000000..695ab306 --- /dev/null +++ b/crates/nodes/src/atomic/transformation.rs @@ -0,0 +1,42 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("transformation", "Transformation 2D", ATOMIC) + .desc("Transforms the input with an offset and a 2 by 2 matrix.") + .atomic() + .any_in("input", "Input") + .float2("offset", "Offset", [0.0; 2], -1.0, 1.0) + .float4("matrix", "Transform matrix", [1.0, 0.0, 0.0, 1.0], -10.0, 10.0) + .choice("filtering", "Filtering", &["Bilinear", "Nearest"], 0) + .color("matte", "Matte color", [0.0; 4]) + .any_out() + .cook(transformation) +} + +fn transformation(context: &CookContext) -> CookResult { + let input = context.any_or(0, Kind::Gray, [0.0; 4]); + let offset = context.v2("offset"); + let matrix = context.v4("matrix"); + let determinant = matrix[0] * matrix[3] - matrix[1] * matrix[2]; + if !determinant.is_finite() || determinant.abs() < 1e-8 { + return Err("transform matrix is singular".into()); + } + + let nearest = context.i("filtering") == 1; + let matte = context.v4("matte"); + Ok(vec![Image::generate_uv(context.w, context.h, input.kind, |u, v| { + let x = u - 0.5 - offset[0]; + let y = v - 0.5 - offset[1]; + let source_u = (matrix[3] * x - matrix[1] * y) / determinant + 0.5; + let source_v = (-matrix[2] * x + matrix[0] * y) / determinant + 0.5; + if !context.tile && (!(0.0..1.0).contains(&source_u) || !(0.0..1.0).contains(&source_v)) { + matte + } else if nearest { + input.sample_nearest(source_u, source_v, context.tile) + } else { + input.sample(source_u, source_v, context.tile) + } + })]) +} diff --git a/crates/nodes/src/atomic/uniform.rs b/crates/nodes/src/atomic/uniform.rs new file mode 100644 index 00000000..36f230e0 --- /dev/null +++ b/crates/nodes/src/atomic/uniform.rs @@ -0,0 +1,23 @@ +use super::ATOMIC; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind, luminance}; + +pub(super) fn definition() -> NodeDefinition { + node("uniform", "Uniform Color", ATOMIC) + .desc("A single color or gray value.") + .atomic() + .generator() + .color("color", "Color", [0.5, 0.5, 0.5, 1.0]) + .boolean("color_mode", "Color output", true) + .any_out() + .cook(uniform) +} + +fn uniform(context: &CookContext) -> CookResult { + let c = context.v4("color"); + Ok(vec![if !context.b("color_mode") { + Image::filled(context.w, context.h, Kind::Gray, [luminance(c); 4]) + } else { + Image::filled(context.w, context.h, Kind::Color, c) + }]) +} diff --git a/crates/nodes/src/atomic/value_processor.rs b/crates/nodes/src/atomic/value_processor.rs new file mode 100644 index 00000000..554a5bc0 --- /dev/null +++ b/crates/nodes/src/atomic/value_processor.rs @@ -0,0 +1,12 @@ +use super::ATOMIC; +use crate::{NodeDefinition, node}; + +pub(super) fn definition() -> NodeDefinition { + node("value_processor", "Value Processor", ATOMIC) + .desc("Computes a typed value with a function graph.") + .atomic() + .any_in("input0", "Input image 0") + .function("function", "Function", materialcraft_core::FunctionGraph::constant(materialcraft_core::Value::Float(0.5))) + .output("output", "Value", crate::PortKind::Value) + .cook(crate::node_definition_builder::no_cook) +} diff --git a/crates/nodes/src/atomic/warp.rs b/crates/nodes/src/atomic/warp.rs new file mode 100644 index 00000000..bbd1f36f --- /dev/null +++ b/crates/nodes/src/atomic/warp.rs @@ -0,0 +1,26 @@ +use super::ATOMIC; +use crate::ops; +use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_image::{Image, Kind}; + +pub(super) fn definition() -> NodeDefinition { + node("warp", "Warp", ATOMIC) + .desc("Distorts the input along the slopes of a gradient map.") + .atomic() + .any_in("input", "Input") + .gray_in("gradient", "Gradient input") + .float("intensity", "Intensity", 1.0, 0.0, 32.0) + .any_out() + .cook(warp) +} + +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 (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) + })]) +} diff --git a/crates/nodes/src/catalog.rs b/crates/nodes/src/catalog.rs index 719c98e1..1faa93cc 100644 --- a/crates/nodes/src/catalog.rs +++ b/crates/nodes/src/catalog.rs @@ -1,346 +1,17 @@ -//! Node definitions: ports, parameters and the cook function of every node in the library, -//! built once into a static registry ([`catalog`]). - -use std::collections::BTreeMap; +use crate::NodeDefinition; use std::sync::OnceLock; -use materialcraft_core::function::FnGraph; -use materialcraft_core::{Curve, Gradient, Value}; -use materialcraft_image::{Image, Kind}; - -/// What a port carries. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PortKind { - Gray, - Color, - /// Either; outputs of this kind follow the main input. - Any, +/// Every node definition, in library order +pub fn catalog() -> &'static [NodeDefinition] { + static CAT: OnceLock<Vec<NodeDefinition>> = OnceLock::new(); + CAT.get_or_init(crate::atomic::defs) } -#[derive(Clone, Debug)] -pub struct PortDef { - pub id: &'static str, - pub label: &'static str, - pub kind: PortKind, -} - -/// The editor widget and range of a parameter. -#[derive(Clone, Debug)] -pub struct ParamDef { - pub id: &'static str, - pub label: &'static str, - pub default: Value, - pub min: f32, - pub max: f32, - /// Labels of an enum parameter. - pub options: &'static [&'static str], - /// Section heading in the Properties panel ("" = none). - pub group: &'static str, - /// An angle in turns (shown in degrees). - pub angle: bool, - /// The name of a package resource (bitmap / SVG). - pub resource: bool, -} - -/// Where a cook runs: output size, seed, tiling, inputs and resolved parameters. -pub struct Ctx<'a> { - pub w: u32, - pub h: u32, - pub seed: u32, - pub tile: bool, - /// By input port order; `None` = not connected. - pub inputs: &'a [Option<Image>], - pub params: &'a BTreeMap<String, Value>, - /// The package's bitmap resources, decoded on demand. - pub resource: &'a (dyn Fn(&str) -> Option<Image> + Sync), - /// Exposed graph inputs (for `get_*` nodes in function graphs). - pub vars: &'a BTreeMap<String, Value>, -} - -impl Ctx<'_> { - pub fn value(&self, id: &str) -> Option<&Value> { - self.params.get(id) - } - - pub fn f(&self, id: &str) -> f32 { - self.value(id).and_then(Value::as_f32).filter(|v| v.is_finite()).unwrap_or(0.0) - } - - pub fn i(&self, id: &str) -> i32 { - self.value(id).and_then(Value::as_i32).unwrap_or(0) - } - - pub fn b(&self, id: &str) -> bool { - self.value(id).and_then(Value::as_bool).unwrap_or(false) - } - - pub fn v4(&self, id: &str) -> [f32; 4] { - self.value(id).and_then(Value::as_vec4).unwrap_or([0.0; 4]) - } - - pub fn v2(&self, id: &str) -> [f32; 2] { - let v = self.v4(id); - [v[0], v[1]] - } - - pub fn text(&self, id: &str) -> &str { - match self.value(id) { - Some(Value::Text(s)) => s, - _ => "", - } - } - - pub fn curve(&self, id: &str) -> Curve { - match self.value(id) { - Some(Value::Curve(c)) => c.clone(), - _ => Curve::default(), - } - } - - pub fn gradient(&self, id: &str) -> Gradient { - match self.value(id) { - Some(Value::Gradient(g)) => g.clone(), - _ => Gradient::default(), - } - } - - pub fn function(&self, id: &str) -> Option<&FnGraph> { - match self.value(id) { - Some(Value::Function(g)) => Some(g.as_ref()), - _ => None, - } - } - - /// Input `i` if connected. - pub fn input(&self, i: usize) -> Option<&Image> { - self.inputs.get(i).and_then(Option::as_ref) - } - - /// Input `i` resampled to the output size (`None` if not connected). - pub fn sized(&self, i: usize) -> Option<Image> { - self.input(i).map(|img| img.resize(self.w, self.h, self.tile)) - } - - /// Input `i` at the output size as gray, or a constant gray `v` when unconnected. - pub fn gray_or(&self, i: usize, v: f32) -> Image { - self.sized(i).map(|img| img.to_gray()).unwrap_or_else(|| Image::filled(self.w, self.h, Kind::Gray, [v; 4])) - } - - /// Input `i` at the output size (kind kept), or constant `v` of `kind` when unconnected. - pub fn any_or(&self, i: usize, kind: Kind, v: [f32; 4]) -> Image { - self.sized(i).unwrap_or_else(|| Image::filled(self.w, self.h, kind, v)) - } - - /// 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) - } - - /// A gray image from `f(u, v)` at the output size. - pub fn gen_gray(&self, f: impl Fn(f32, f32) -> f32 + Sync) -> Image { - Image::generate_uv(self.w, self.h, Kind::Gray, |u, v| [f(u, v), 0.0, 0.0, 0.0]) - } - - pub fn gen_color(&self, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { - Image::generate_uv(self.w, self.h, Kind::Color, f) - } -} - -pub type CookResult = Result<Vec<Image>, String>; -pub type Cook = fn(&Ctx) -> CookResult; - -/// A node in the library. -#[derive(Clone, Debug)] -pub struct NodeDef { - pub id: &'static str, - pub label: &'static str, - /// Library path, e.g. `Filters/Blurs`, `Texture generators/Noises`, `Atomic nodes`. - pub category: &'static str, - pub description: &'static str, - pub inputs: Vec<PortDef>, - pub outputs: Vec<PortDef>, - pub params: Vec<ParamDef>, - /// A generator takes its size from the graph, not from an input. - pub generator: bool, - /// One of the engine's built-in ("atomic") nodes (shown with a grey header). - pub atomic: bool, - pub cook: Cook, -} - -impl NodeDef { - pub fn param(&self, id: &str) -> Option<&ParamDef> { - self.params.iter().find(|p| p.id == id) - } - - pub fn input_index(&self, id: &str) -> Option<usize> { - self.inputs.iter().position(|p| p.id == id) - } - - pub fn output_index(&self, id: &str) -> Option<usize> { - self.outputs.iter().position(|p| p.id == id) - } - - /// The last path element of the category ("Blurs"). - pub fn group(&self) -> &'static str { - self.category.rsplit('/').next().unwrap_or(self.category) - } -} - -pub(crate) fn no_cook(_: &Ctx) -> CookResult { - Err("this node is cooked by the graph evaluator".into()) -} - -/// Builder for [`NodeDef`]s. -pub(crate) struct B(NodeDef); - -pub(crate) fn node(id: &'static str, label: &'static str, category: &'static str) -> B { - B(NodeDef { - id, - label, - category, - description: "", - inputs: Vec::new(), - outputs: Vec::new(), - params: Vec::new(), - generator: false, - atomic: false, - cook: no_cook, - }) -} - -impl B { - pub fn desc(mut self, d: &'static str) -> B { - self.0.description = d; - self - } - pub fn atomic(mut self) -> B { - self.0.atomic = true; - self - } - pub fn generator(mut self) -> B { - self.0.generator = true; - self - } - pub fn input(mut self, id: &'static str, label: &'static str, kind: PortKind) -> B { - self.0.inputs.push(PortDef { id, label, kind }); - self - } - pub fn gray_in(self, id: &'static str, label: &'static str) -> B { - self.input(id, label, PortKind::Gray) - } - pub fn color_in(self, id: &'static str, label: &'static str) -> B { - self.input(id, label, PortKind::Color) - } - pub fn any_in(self, id: &'static str, label: &'static str) -> B { - self.input(id, label, PortKind::Any) - } - pub fn output(mut self, id: &'static str, label: &'static str, kind: PortKind) -> B { - self.0.outputs.push(PortDef { id, label, kind }); - self - } - pub fn gray_out(self) -> B { - self.output("output", "Output", PortKind::Gray) - } - pub fn color_out(self) -> B { - self.output("output", "Output", PortKind::Color) - } - pub fn any_out(self) -> B { - self.output("output", "Output", PortKind::Any) - } - fn push(mut self, id: &'static str, label: &'static str, default: Value, min: f32, max: f32) -> B { - self.0.params.push(ParamDef { id, label, default, min, max, options: &[], group: "", angle: false, resource: false }); - self - } - fn last(&mut self) -> Option<&mut ParamDef> { - self.0.params.last_mut() - } - pub fn float(self, id: &'static str, label: &'static str, d: f32, min: f32, max: f32) -> B { - self.push(id, label, Value::Float(d), min, max) - } - pub fn angle(mut self, id: &'static str, label: &'static str, d: f32) -> B { - self = self.push(id, label, Value::Float(d), -1.0, 1.0); - if let Some(p) = self.last() { - p.angle = true; - } - self - } - pub fn int(self, id: &'static str, label: &'static str, d: i32, min: i32, max: i32) -> B { - self.push(id, label, Value::Int(d), min as f32, max as f32) - } - pub fn float2(self, id: &'static str, label: &'static str, d: [f32; 2], min: f32, max: f32) -> B { - self.push(id, label, Value::Float2(d), min, max) - } - pub fn boolean(self, id: &'static str, label: &'static str, d: bool) -> B { - self.push(id, label, Value::Bool(d), 0.0, 1.0) - } - pub fn color(self, id: &'static str, label: &'static str, d: [f32; 4]) -> B { - self.push(id, label, Value::Color(d), 0.0, 1.0) - } - pub fn choice(mut self, id: &'static str, label: &'static str, options: &'static [&'static str], d: u32) -> B { - self = self.push(id, label, Value::Enum(d), 0.0, options.len().saturating_sub(1) as f32); - if let Some(p) = self.last() { - p.options = options; - } - self - } - pub fn text(self, id: &'static str, label: &'static str, d: &str) -> B { - self.push(id, label, Value::Text(d.into()), 0.0, 0.0) - } - pub fn resource(mut self, id: &'static str, label: &'static str) -> B { - self = self.push(id, label, Value::Text(String::new()), 0.0, 0.0); - if let Some(p) = self.last() { - p.resource = true; - } - self - } - pub fn curve(self, id: &'static str, label: &'static str) -> B { - self.push(id, label, Value::Curve(Curve::default()), 0.0, 1.0) - } - pub fn gradient(self, id: &'static str, label: &'static str, g: Gradient) -> B { - self.push(id, label, Value::Gradient(g), 0.0, 1.0) - } - pub fn function(self, id: &'static str, label: &'static str, g: FnGraph) -> B { - self.push(id, label, Value::Function(Box::new(g)), 0.0, 0.0) - } - pub fn cook(mut self, f: Cook) -> NodeDef { - if self.0.outputs.is_empty() { - self = self.any_out(); - } - self.0.cook = f; - self.0 - } -} - -/// Every node definition, in library order. -pub fn catalog() -> &'static [NodeDef] { - static CAT: OnceLock<Vec<NodeDef>> = OnceLock::new(); - CAT.get_or_init(|| { - let mut v = Vec::new(); - v.extend(crate::atomic::defs()); - v.extend(crate::fx_map::defs()); - v.extend(crate::svg::defs()); - v.extend(crate::text::defs()); - v.extend(crate::generators::defs()); - v.extend(crate::noises_more::defs()); - v.extend(crate::noise3d::defs()); - v.extend(crate::patterns::defs()); - v.extend(crate::patterns_more::defs()); - v.extend(crate::filters::defs()); - v.extend(crate::filters_more::defs()); - v.extend(crate::filters_extra::defs()); - v.extend(crate::flood_fill::defs()); - v.extend(crate::material::defs()); - v.extend(crate::material_more::defs()); - v.extend(crate::weathering::defs()); - v - }) -} - -pub fn find(id: &str) -> Option<&'static NodeDef> { +pub fn find(id: &str) -> Option<&'static NodeDefinition> { catalog().iter().find(|d| d.id == id) } -/// The library's category tree, in display order: (path, ids). +/// The library's category tree, in display order: (path, ids) pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> { let mut out: Vec<(&'static str, Vec<&'static str>)> = Vec::new(); for d in catalog() { @@ -351,71 +22,3 @@ pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> { } out } - -/// How many slider spans the hard limit extends past each end of a parameter's range. -const HARD_SPAN: f32 = 16.0; - -/// Clamp `v` to `[lo, hi]`; a non-finite `v` becomes `fallback`. -fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 { - if v.is_finite() { v.clamp(lo, hi) } else { fallback } -} - -/// Clamp numeric parameters to hard limits: the declared slider range widened by -/// `HARD_SPAN` spans on each side (the editor lets values past the slider through, so the -/// slider range itself is not a limit). Non-finite values become the default. Keeps cooks -/// bounded whatever a file, binding, function or command supplies. -pub fn clamp_params(def: &NodeDef, params: &mut BTreeMap<String, Value>) { - for p in &def.params { - let Some(v) = params.get_mut(p.id) else { continue }; - if let Value::Enum(i) = v { - if !p.options.is_empty() { - *i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX)); - } - continue; - } - if let Value::Color(c) = v { - for x in c { - *x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0); - } - continue; - } - if p.min >= p.max { - continue; - } - let span = p.max - p.min; - let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span); - // The default's component `i`, or 0 when the default is a different variant. - let fallback = |i: usize| match &p.default { - Value::Float(d) => [*d].get(i).copied(), - Value::Float2(d) => d.get(i).copied(), - Value::Float3(d) => d.get(i).copied(), - Value::Float4(d) => d.get(i).copied(), - _ => None, - }; - let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0)); - let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32; - match v { - Value::Float(x) => clamp_at(x, 0), - Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Int(x) => clamp_int(x), - Value::Int2(a) => a.iter_mut().for_each(clamp_int), - _ => {} - } - } -} - -/// Parameter values for a node: catalog defaults overlaid with `overrides`. -pub fn resolve_params(def: &NodeDef, overrides: &BTreeMap<String, Value>) -> BTreeMap<String, Value> { - let mut m: BTreeMap<String, Value> = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect(); - for (k, v) in overrides { - // Keep only known parameters whose type matches (a hand-edited file may have anything). - if let Some(d) = m.get(k) - && d.type_name() == v.type_name() - { - m.insert(k.clone(), v.clone()); - } - } - m -} diff --git a/crates/nodes/src/cook_context.rs b/crates/nodes/src/cook_context.rs new file mode 100644 index 00000000..bef04af8 --- /dev/null +++ b/crates/nodes/src/cook_context.rs @@ -0,0 +1,107 @@ +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 +pub struct CookContext<'a> { + pub w: u32, + pub h: u32, + pub seed: u32, + pub tile: bool, + /// By input port order; `None` = not connected + pub inputs: &'a [Option<Image>], + pub params: &'a BTreeMap<String, Value>, + /// The package's bitmap resources, decoded on demand + pub resource: &'a (dyn Fn(&str) -> Option<Image> + Sync), + /// Exposed graph inputs (for `get_*` nodes in function graphs) + pub vars: &'a BTreeMap<String, Value>, +} + +impl CookContext<'_> { + pub fn value(&self, id: &str) -> Option<&Value> { + self.params.get(id) + } + + pub fn f(&self, id: &str) -> f32 { + self.value(id).and_then(Value::as_f32).filter(|v| v.is_finite()).unwrap_or(0.0) + } + + pub fn i(&self, id: &str) -> i32 { + self.value(id).and_then(Value::as_i32).unwrap_or(0) + } + + pub fn b(&self, id: &str) -> bool { + self.value(id).and_then(Value::as_bool).unwrap_or(false) + } + + pub fn v4(&self, id: &str) -> [f32; 4] { + self.value(id).and_then(Value::as_vec4).unwrap_or([0.0; 4]) + } + + pub fn v2(&self, id: &str) -> [f32; 2] { + let v = self.v4(id); + [v[0], v[1]] + } + + pub fn text(&self, id: &str) -> &str { + match self.value(id) { + Some(Value::Text(s)) => s, + _ => "", + } + } + + pub fn curve(&self, id: &str) -> Curve { + match self.value(id) { + Some(Value::Curve(c)) => c.clone(), + _ => Curve::default(), + } + } + + pub fn gradient(&self, id: &str) -> Gradient { + match self.value(id) { + Some(Value::Gradient(g)) => g.clone(), + _ => Gradient::default(), + } + } + + pub fn function(&self, id: &str) -> Option<&FunctionGraph> { + match self.value(id) { + Some(Value::Function(g)) => Some(g.as_ref()), + _ => None, + } + } + + /// Input `i` if connected + pub fn input(&self, i: usize) -> Option<&Image> { + self.inputs.get(i).and_then(Option::as_ref) + } + + /// Input `i` resampled to the output size (`None` if not connected) + pub fn sized(&self, i: usize) -> Option<Image> { + self.input(i).map(|img| img.resize(self.w, self.h, self.tile)) + } + + /// Input `i` at the output size as gray, or a constant gray `v` when unconnected + pub fn gray_or(&self, i: usize, v: f32) -> Image { + self.sized(i).map(|img| img.to_gray()).unwrap_or_else(|| Image::filled(self.w, self.h, Kind::Gray, [v; 4])) + } + + /// Input `i` at the output size (kind kept), or constant `v` of `kind` when unconnected + pub fn any_or(&self, i: usize, kind: Kind, v: [f32; 4]) -> Image { + self.sized(i).unwrap_or_else(|| Image::filled(self.w, self.h, kind, v)) + } + + /// 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) + } + + /// A gray image from `f(u, v)` at the output size + pub fn gen_gray(&self, f: impl Fn(f32, f32) -> f32 + Sync) -> Image { + Image::generate_uv(self.w, self.h, Kind::Gray, |u, v| [f(u, v), 0.0, 0.0, 0.0]) + } + + pub fn gen_color(&self, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { + Image::generate_uv(self.w, self.h, Kind::Color, f) + } +} diff --git a/crates/nodes/src/filters.rs b/crates/nodes/src/filters.rs deleted file mode 100644 index 702383b5..00000000 --- a/crates/nodes/src/filters.rs +++ /dev/null @@ -1,961 +0,0 @@ -//! Filters: adjustments, blending, blurs, channels, effects, normal map tools, tiling and -//! transforms. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind, luminance}; - -use crate::atomic::{height_to_normal, levels_fn, transform_sample}; -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::ops; - -const ADJ: &str = "Filters/Adjustments"; -const BLENDING: &str = "Filters/Blending"; -const BLURS: &str = "Filters/Blurs"; -const CHANNELS: &str = "Filters/Channels"; -const EFFECTS: &str = "Filters/Effects"; -const NORMAL: &str = "Filters/Normal map"; -const TILING: &str = "Filters/Tiling"; -const TRANSFORMS: &str = "Filters/Transforms"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - // ---- Adjustments - node("auto_levels", "Auto Levels", ADJ).desc("Stretches the input to the full 0..1 range.").any_in("input", "Input").cook(auto_levels), - node("clamp", "Clamp", ADJ) - .desc("Clamps values between a minimum and a maximum.") - .any_in("input", "Input") - .float("min", "Min", 0.0, 0.0, 1.0) - .float("max", "Max", 1.0, 0.0, 1.0) - .cook(clamp), - node("color_to_mask", "Color to Mask", ADJ) - .desc("White where the input is close to a key color.") - .color_in("input", "Input") - .color("color", "Key color", [1.0, 0.0, 0.0, 1.0]) - .float("range", "Range", 0.2, 0.0, 1.0) - .float("softness", "Softness", 0.1, 0.0, 1.0) - .gray_out() - .cook(color_to_mask), - node("contrast_luminosity", "Contrast/Luminosity", ADJ) - .desc("Contrast and brightness (0 = unchanged).") - .any_in("input", "Input") - .float("contrast", "Contrast", 0.0, -1.0, 1.0) - .float("luminosity", "Luminosity", 0.0, -1.0, 1.0) - .cook(contrast_luminosity), - node("exposure", "Exposure", ADJ).desc("Exposure in stops.").any_in("input", "Input").float("stops", "Exposure (EV)", 0.0, -10.0, 10.0).cook(exposure), - node("gamma", "Gamma", ADJ).desc("Raises values to a power.").any_in("input", "Input").float("gamma", "Gamma", 1.0, 0.01, 10.0).cook(gamma), - node("histogram_range", "Histogram Range", ADJ) - .desc("Compresses values into a range around a position.") - .gray_in("input", "Input") - .float("range", "Range", 0.5, 0.0, 1.0) - .float("position", "Position", 0.5, 0.0, 1.0) - .gray_out() - .cook(histogram_range), - node("histogram_scan", "Histogram Scan", ADJ) - .desc("Thresholds the input at a position with adjustable contrast.") - .gray_in("input", "Input") - .float("position", "Position", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .boolean("invert", "Invert position", false) - .gray_out() - .cook(histogram_scan), - node("histogram_shift", "Histogram Shift", ADJ) - .desc("Shifts values with wrap-around.") - .gray_in("input", "Input") - .float("position", "Position", 0.5, 0.0, 1.0) - .gray_out() - .cook(histogram_shift), - node("invert", "Invert", ADJ).desc("1 minus the input (alpha kept).").any_in("input", "Input").boolean("alpha", "Invert alpha", false).cook(invert), - node("posterize", "Posterize", ADJ) - .desc("Quantizes values to a number of steps.") - .any_in("input", "Input") - .int("steps", "Steps", 4, 2, 256) - .cook(posterize), - node("replace_color", "Replace Color", ADJ) - .desc("Shifts colors near a source color towards a target color.") - .color_in("input", "Input") - .color("source", "Source color", [1.0, 0.0, 0.0, 1.0]) - .color("target", "Target color", [0.0, 0.0, 1.0, 1.0]) - .float("range", "Range", 0.3, 0.0, 1.0) - .color_out() - .cook(replace_color), - node("threshold", "Threshold", ADJ) - .desc("White above the threshold, black below.") - .gray_in("input", "Input") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .gray_out() - .cook(threshold), - node("colorize", "Colorize", ADJ) - .desc("Tints a grayscale image between two colors.") - .gray_in("input", "Input") - .color("dark", "Dark color", [0.05, 0.03, 0.02, 1.0]) - .color("light", "Light color", [0.9, 0.75, 0.5, 1.0]) - .color_out() - .cook(colorize), - node("channel_mixer", "Channel Mixer", ADJ) - .desc("Each output channel as a weighted sum of the input channels.") - .color_in("input", "Input") - .float2("red_rg", "Red from R, G", [1.0, 0.0], -2.0, 2.0) - .float("red_b", "Red from B", 0.0, -2.0, 2.0) - .float2("green_rg", "Green from R, G", [0.0, 1.0], -2.0, 2.0) - .float("green_b", "Green from B", 0.0, -2.0, 2.0) - .float2("blue_rg", "Blue from R, G", [0.0, 0.0], -2.0, 2.0) - .float("blue_b", "Blue from B", 1.0, -2.0, 2.0) - .color_out() - .cook(channel_mixer), - // ---- Blending - node("height_blend", "Height Blend", BLENDING) - .desc("Blends two height maps by which is higher, with a soft contrast; also outputs the mask.") - .gray_in("top", "Height top") - .gray_in("bottom", "Height bottom") - .gray_in("mask", "Mask") - .float("offset", "Height offset", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.9, 0.0, 1.0) - .output("height", "Height", PortKind::Gray) - .output("blend_mask", "Blend mask", PortKind::Gray) - .cook(height_blend), - node("alpha_merge", "Alpha Merge", BLENDING) - .desc("Puts a grayscale image in a color image's alpha.") - .color_in("input", "Color") - .gray_in("alpha", "Alpha") - .color_out() - .cook(alpha_merge), - node("rgba_merge", "RGBA Merge", CHANNELS) - .desc("Builds a color image from four grayscale channels.") - .gray_in("r", "R") - .gray_in("g", "G") - .gray_in("b", "B") - .gray_in("a", "A") - .color_out() - .cook(rgba_merge), - node("rgba_split", "RGBA Split", CHANNELS) - .desc("Splits a color image into four grayscale channels.") - .color_in("input", "RGBA") - .output("r", "R", PortKind::Gray) - .output("g", "G", PortKind::Gray) - .output("b", "B", PortKind::Gray) - .output("a", "A", PortKind::Gray) - .cook(rgba_split), - node("switch", "Switch", BLENDING) - .desc("Outputs input A or input B.") - .any_in("a", "Input A") - .any_in("b", "Input B") - .boolean("use_b", "Use input B", false) - .cook(switch), - // ---- Blurs - node("anisotropic_blur", "Anisotropic Blur", BLURS) - .desc("A Gaussian blur stronger along one direction.") - .any_in("input", "Input") - .float("intensity", "Intensity", 4.0, 0.0, 32.0) - .float("anisotropy", "Anisotropy", 0.5, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .cook(anisotropic_blur), - node("non_uniform_blur", "Non Uniform Blur", BLURS) - .desc("Blurs more where the blur map is white.") - .any_in("input", "Input") - .gray_in("blur_map", "Blur map") - .float("intensity", "Intensity", 4.0, 0.0, 32.0) - .cook(non_uniform_blur), - node("radial_blur", "Radial Blur", BLURS) - .desc("Zoom blur from a center.") - .any_in("input", "Input") - .float("intensity", "Intensity", 0.2, 0.0, 1.0) - .float2("center", "Center", [0.5, 0.5], 0.0, 1.0) - .cook(radial_blur), - node("slope_blur", "Slope Blur", BLURS) - .desc("Smears the input along the slopes of a map, like flowing material.") - .any_in("input", "Input") - .gray_in("slope", "Slope") - .float("intensity", "Intensity", 8.0, -64.0, 64.0) - .int("samples", "Samples", 8, 1, 32) - .choice("mode", "Mode", &["Blur", "Min", "Max"], 0) - .cook(slope_blur), - // ---- Effects - node("ambient_occlusion", "Ambient Occlusion", EFFECTS) - .desc("Darkens creases of a height map.") - .gray_in("height", "Height") - .float("spread", "Spreading", 0.15, 0.0, 1.0) - .float("intensity", "Height depth", 0.5, 0.0, 1.0) - .gray_out() - .cook(ambient_occlusion), - node("bevel", "Bevel", EFFECTS) - .desc("Rounds the edges of a mask into a height ramp.") - .gray_in("input", "Mask") - .float("distance", "Distance", 0.05, -1.0, 1.0) - .float("smoothing", "Smoothing", 0.0, 0.0, 1.0) - .gray_out() - .cook(bevel), - node("curvature", "Curvature", EFFECTS) - .desc("Convexity (white) and concavity (black) of a normal map.") - .color_in("normal", "Normal") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .gray_out() - .cook(curvature), - node("dilation", "Dilation", EFFECTS) - .desc("Grows bright areas (maximum filter).") - .any_in("input", "Input") - .int("radius", "Radius", 2, 0, 64) - .cook(dilation), - node("erosion", "Erosion", EFFECTS) - .desc("Shrinks bright areas (minimum filter).") - .any_in("input", "Input") - .int("radius", "Radius", 2, 0, 64) - .cook(erosion), - node("edge_detect", "Edge Detect", EFFECTS) - .desc("White along the edges of a mask.") - .gray_in("input", "Input") - .float("width", "Edge width", 2.0, 0.0, 32.0) - .float("roundness", "Edge roundness", 0.5, 0.0, 1.0) - .gray_out() - .cook(edge_detect), - node("glow", "Glow", EFFECTS) - .desc("A soft glow around bright areas.") - .any_in("input", "Input") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .float("size", "Size", 8.0, 0.0, 64.0) - .float("amount", "Amount", 0.5, 0.0, 2.0) - .cook(glow), - node("highpass", "Highpass", EFFECTS) - .desc("Keeps the fine detail, centered on gray.") - .any_in("input", "Input") - .float("radius", "Radius", 6.0, 0.0, 64.0) - .cook(highpass), - node("mosaic", "Mosaic", EFFECTS).desc("Pixelates into blocks.").any_in("input", "Input").int("cells", "Cells", 16, 1, 512).cook(mosaic), - node("swirl", "Swirl", EFFECTS) - .desc("Twists the image around its center.") - .any_in("input", "Input") - .float("amount", "Amount", 0.5, -4.0, 4.0) - .float("radius", "Radius", 0.5, 0.0, 1.0) - .cook(swirl), - node("vignette", "Vignette", EFFECTS) - .desc("Darkens towards the borders.") - .any_in("input", "Input") - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.5, 0.0, 1.0) - .cook(vignette), - node("quantize", "Quantize Grayscale", EFFECTS) - .desc("Snaps gray values to steps with soft transitions.") - .gray_in("input", "Input") - .int("steps", "Steps", 4, 2, 64) - .float("smoothness", "Smoothness", 0.1, 0.0, 1.0) - .gray_out() - .cook(quantize), - // ---- Normal map - node("height_to_normal", "Height to Normal", NORMAL) - .desc("Same as Normal: a normal map from a height map.") - .gray_in("input", "Height") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) - .color_out() - .cook(height_normal), - node("normal_blend", "Normal Blend", NORMAL) - .desc("Combines two normal maps (reoriented normal mapping).") - .color_in("base", "Normal base") - .color_in("detail", "Normal detail") - .gray_in("mask", "Mask") - .float("opacity", "Opacity", 1.0, 0.0, 1.0) - .color_out() - .cook(normal_blend), - node("normal_invert", "Normal Invert", NORMAL) - .desc("Flips the green (and optionally red) channel: OpenGL / DirectX.") - .color_in("input", "Normal") - .boolean("red", "Invert red", false) - .boolean("green", "Invert green", true) - .color_out() - .cook(normal_invert), - node("normal_normalize", "Normal Normalize", NORMAL) - .desc("Rescales normals to unit length.") - .color_in("input", "Normal") - .color_out() - .cook(normal_normalize), - node("normal_intensity", "Normal Intensity", NORMAL) - .desc("Strengthens or flattens a normal map.") - .color_in("input", "Normal") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .color_out() - .cook(normal_intensity), - node("normal_to_height", "Normal to Height", NORMAL) - .desc("Reconstructs a height map from a normal map.") - .color_in("input", "Normal") - .float("intensity", "Height scale", 1.0, 0.0, 10.0) - .gray_out() - .cook(normal_to_height), - // ---- Tiling - node("make_it_tile", "Make It Tile", TILING) - .desc("Cross-fades the borders so a photo tiles.") - .any_in("input", "Input") - .float("blend", "Blend width", 0.25, 0.0, 0.5) - .cook(make_it_tile), - node("safe_transform", "Safe Transform", TILING) - .desc("Tiling-safe transform: whole-number tiling, offsets and 90° rotations.") - .any_in("input", "Input") - .int("tile", "Tile", 1, 1, 64) - .float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0) - .choice("rotation", "Rotation", &["0°", "90°", "180°", "270°"], 0) - .boolean("flip", "Flip", false) - .cook(safe_transform), - // ---- Transforms - node("mirror", "Mirror", TRANSFORMS) - .desc("Mirrors one half of the image onto the other.") - .any_in("input", "Input") - .choice("axis", "Mirror type", &["Horizontal", "Vertical", "Corner"], 0) - .boolean("flip", "Flip side", false) - .cook(mirror), - node("kaleidoscope", "Kaleidoscope", TRANSFORMS) - .desc("Repeats a wedge of the image around the center.") - .any_in("input", "Input") - .int("segments", "Segments", 6, 2, 64) - .angle("angle", "Angle", 0.0) - .cook(kaleidoscope), - node("cartesian_to_polar", "Cartesian to Polar", TRANSFORMS) - .desc("Wraps the image around the center.") - .any_in("input", "Input") - .cook(cartesian_to_polar), - node("polar_to_cartesian", "Polar to Cartesian", TRANSFORMS) - .desc("Unwraps a circular image into bands.") - .any_in("input", "Input") - .cook(polar_to_cartesian), - node("skew", "Skew", TRANSFORMS) - .desc("Shears the image.") - .any_in("input", "Input") - .float("amount", "Amount", 0.25, -2.0, 2.0) - .boolean("vertical", "Vertical", false) - .cook(skew), - ] -} - -fn src(ctx: &Ctx) -> Image { - ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0]) -} - -fn per_value(ctx: &Ctx, f: impl Fn(f32) -> f32 + Sync) -> CookResult { - let img = src(ctx); - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) -} - -fn auto_levels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (lo, hi) = img.range(); - let span = (hi - lo).max(1e-6); - per_value(ctx, |v| (v - lo) / span) -} - -fn clamp(ctx: &Ctx) -> CookResult { - let (a, b) = (ctx.f("min"), ctx.f("max")); - per_value(ctx, |v| v.max(a).min(b.max(a))) -} - -fn color_to_mask(ctx: &Ctx) -> CookResult { - let img = src(ctx).to_color(); - let (k, r, s) = (ctx.v4("color"), ctx.f("range"), ctx.f("softness").max(1e-4)); - Ok(vec![img.map(Kind::Gray, |p| { - let d = ((p[0] - k[0]).powi(2) + (p[1] - k[1]).powi(2) + (p[2] - k[2]).powi(2)).sqrt(); - [(1.0 - (d - r) / s).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn contrast_luminosity(ctx: &Ctx) -> CookResult { - let (c, l) = (ctx.f("contrast"), ctx.f("luminosity")); - let k = if c >= 0.0 { 1.0 / (1.0 - c * 0.99) } else { 1.0 + c }; - per_value(ctx, |v| ((v - 0.5) * k + 0.5 + l).clamp(0.0, 1.0)) -} - -fn exposure(ctx: &Ctx) -> CookResult { - // Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite. - let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0)); - per_value(ctx, |v| v * k) -} - -fn gamma(ctx: &Ctx) -> CookResult { - let g = ctx.f("gamma").max(0.01); - per_value(ctx, |v| v.max(0.0).powf(1.0 / g)) -} - -fn histogram_range(ctx: &Ctx) -> CookResult { - let (r, p) = (ctx.f("range"), ctx.f("position")); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |c| [(p + (c[0] - 0.5) * r).clamp(0.0, 1.0), 0.0, 0.0, 0.0])]) -} - -/// The Histogram Scan mapping. -pub fn histogram_scan_fn(v: f32, position: f32, contrast: f32) -> f32 { - let width = (1.0 - contrast).max(0.001); - let lo = position * (1.0 + width) - width; - levels_fn(v, lo, 0.5, lo + width, 0.0, 1.0) -} - -fn histogram_scan(ctx: &Ctx) -> CookResult { - let p = if ctx.b("invert") { 1.0 - ctx.f("position") } else { ctx.f("position") }; - let c = ctx.f("contrast"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |v| [histogram_scan_fn(v[0], 1.0 - p, c), 0.0, 0.0, 0.0])]) -} - -fn histogram_shift(ctx: &Ctx) -> CookResult { - let p = ctx.f("position"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |v| [(v[0] + p).rem_euclid(1.0), 0.0, 0.0, 0.0])]) -} - -fn invert(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let a = ctx.b("alpha"); - Ok(vec![img.map(img.kind, |p| [1.0 - p[0], 1.0 - p[1], 1.0 - p[2], if a { 1.0 - p[3] } else { p[3] }])]) -} - -fn posterize(ctx: &Ctx) -> CookResult { - let n = (ctx.i("steps").max(2) - 1) as f32; - per_value(ctx, |v| (v * n).round() / n) -} - -fn replace_color(ctx: &Ctx) -> CookResult { - let img = src(ctx).to_color(); - let (s, t, r) = (ctx.v4("source"), ctx.v4("target"), ctx.f("range").max(1e-4)); - Ok(vec![img.map(Kind::Color, |p| { - let d = ((p[0] - s[0]).powi(2) + (p[1] - s[1]).powi(2) + (p[2] - s[2]).powi(2)).sqrt(); - let w = (1.0 - d / r).clamp(0.0, 1.0); - [p[0] + (t[0] - s[0]) * w, p[1] + (t[1] - s[1]) * w, p[2] + (t[2] - s[2]) * w, p[3]] - })]) -} - -fn threshold(ctx: &Ctx) -> CookResult { - let t = ctx.f("threshold"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |v| [if v[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])]) -} - -fn colorize(ctx: &Ctx) -> CookResult { - let (a, b) = (ctx.v4("dark"), ctx.v4("light")); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Color, |v| { - let t = v[0]; - [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, 1.0] - })]) -} - -fn channel_mixer(ctx: &Ctx) -> CookResult { - let img = src(ctx).to_color(); - let (r, g, b) = (ctx.v2("red_rg"), ctx.v2("green_rg"), ctx.v2("blue_rg")); - let (rb, gb, bb) = (ctx.f("red_b"), ctx.f("green_b"), ctx.f("blue_b")); - Ok(vec![ - img.map(Kind::Color, |p| [r[0] * p[0] + r[1] * p[1] + rb * p[2], g[0] * p[0] + g[1] * p[1] + gb * p[2], b[0] * p[0] + b[1] * p[1] + bb * p[2], p[3]]), - ]) -} - -fn height_blend(ctx: &Ctx) -> CookResult { - let (top, bot) = (ctx.gray_or(0, 0.0), ctx.gray_or(1, 0.0)); - let mask = ctx.sized(2).map(|m| m.to_gray()); - let (off, c) = (ctx.f("offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999)); - let soft = (1.0 - c) * 0.5 + 1e-4; - let n = (ctx.w * ctx.h) as usize; - let mut h = vec![0.0; n]; - let mut m = vec![0.0; n]; - for i in 0..n { - let (t, b) = (top.data[i] + off, bot.data[i]); - let mut k = ((t - b) / soft * 0.5 + 0.5).clamp(0.0, 1.0); - if let Some(mm) = &mask { - k *= mm.data[i]; - } - h[i] = b + (t - b) * k; - m[i] = k; - } - Ok(vec![ops::gray_from(ctx.w, ctx.h, h), ops::gray_from(ctx.w, ctx.h, m)]) -} - -fn alpha_merge(ctx: &Ctx) -> CookResult { - let c = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let a = ctx.gray_or(1, 1.0); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let p = c.get(x as i64, y as i64, false); - [p[0], p[1], p[2], a.get_gray(x as i64, y as i64, false)] - })]) -} - -fn rgba_merge(ctx: &Ctx) -> CookResult { - let ch: Vec<Image> = (0..4).map(|i| ctx.gray_or(i, if i == 3 { 1.0 } else { 0.0 })).collect(); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let i = (y * ctx.w + x) as usize; - [ch[0].data[i], ch[1].data[i], ch[2].data[i], ch[3].data[i]] - })]) -} - -fn rgba_split(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - Ok((0..4).map(|k| img.map(Kind::Gray, |p| [p[k], 0.0, 0.0, 0.0])).collect()) -} - -fn switch(ctx: &Ctx) -> CookResult { - let i = usize::from(ctx.b("use_b")); - Ok(vec![ctx.sized(i).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))]) -} - -fn anisotropic_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let s = ctx.f("intensity") * ctx.w as f32 / 512.0; - let an = ctx.f("anisotropy"); - let a = ctx.f("angle") * TAU; - // Blur in a rotated frame: rotate, blur x/y separately, rotate back. - let (sx, sy) = (s, s * (1.0 - an)); - if a.abs() < 1e-4 { - return Ok(vec![blur_xy(&img, sx, sy, ctx.tile)]); - } - let rotated = - Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, [0.0, 0.0], [1.0, 1.0], a / TAU, false, true).unwrap_or([0.0; 4])); - let b = blur_xy(&rotated, sx, sy, true); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))]) -} - -/// Most extra horizontal passes `blur_xy` runs: a cost bound, whatever sigma it is given. -const MAX_BLUR_PASSES: i64 = 64; -/// Widest horizontal kernel half-width `blur_xy` builds: a cost bound on the kernel allocation. -const MAX_KERNEL_RADIUS: i64 = 512; - -fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { - if !sx.is_finite() || !sy.is_finite() { - return img.clone(); - } - // Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so - // blur fully with the smaller sigma and add the extra along x by repeated small passes. - let base = ops::gaussian(img, sy, tile); - let extra = (sx * sx - sy * sy).max(0.0).sqrt(); - if extra < 0.1 { - return base; - } - let n = ((extra / 2.0).ceil().max(1.0) as i64).min(MAX_BLUR_PASSES); - let step = extra / (n as f32).sqrt(); - let mut out = base; - for _ in 0..n { - let src = out.clone(); - let r = ((step * 2.0).ceil() as i64).clamp(1, MAX_KERNEL_RADIUS); - let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect(); - let sum: f32 = k.iter().sum(); - out = Image::generate(src.w, src.h, src.kind, |x, y| { - let mut acc = [0.0; 4]; - for (j, kv) in k.iter().enumerate() { - let p = src.get(x as i64 + j as i64 - r, y as i64, tile); - for c in 0..4 { - acc[c] += p[c] * kv / sum; - } - } - acc - }); - } - out -} - -fn non_uniform_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let map = ctx.gray_or(1, 1.0); - let s = ctx.f("intensity") * ctx.w as f32 / 512.0; - // Four blur levels, blended by the map. - let levels: Vec<Image> = (0..4).map(|i| ops::gaussian(&img, s * i as f32 / 3.0, ctx.tile)).collect(); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let t = map.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0) * 3.0; - let i = (t.floor() as usize).min(2); - let f = t - i as f32; - let (a, b) = (levels[i].get(x as i64, y as i64, false), levels[i + 1].get(x as i64, y as i64, false)); - [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f] - })]) -} - -fn radial_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (k, c) = (ctx.f("intensity"), ctx.v2("center")); - let n = 24; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let mut acc = [0.0; 4]; - for i in 0..n { - let t = 1.0 - k * i as f32 / n as f32; - let p = img.sample(c[0] + (u - c[0]) * t, c[1] + (v - c[1]) * t, ctx.tile); - for j in 0..4 { - acc[j] += p[j] / n as f32; - } - } - acc - })]) -} - -fn slope_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let slope = ops::gaussian(&ctx.gray_or(1, 0.5), 1.0, ctx.tile); - let k = ctx.f("intensity") / 256.0; - let n = ctx.i("samples").clamp(1, 64); - let mode = ctx.i("mode"); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (mut pu, mut pv) = (u, v); - let mut acc = img.sample(u, v, ctx.tile); - let mut cnt = 1.0; - for _ in 0..n { - let (x, y) = ((pu * ctx.w as f32) as i64, (pv * ctx.h as f32) as i64); - let (dx, dy) = ops::slope(&slope, x, y, ctx.tile); - let l = (dx * dx + dy * dy).sqrt().max(1e-6); - pu -= dx / l * k / n as f32 * 4.0; - pv -= dy / l * k / n as f32 * 4.0; - let p = img.sample(pu, pv, ctx.tile); - for j in 0..4 { - acc[j] = match mode { - 1 => acc[j].min(p[j]), - 2 => acc[j].max(p[j]), - _ => acc[j] + p[j], - }; - } - cnt += 1.0; - } - if mode == 0 { acc.map(|a| a / cnt) } else { acc } - })]) -} - -fn ambient_occlusion(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let spread = ctx.f("spread").max(0.001) * ctx.w as f32 * 0.25; - let depth = ctx.f("intensity"); - let wide = ops::gaussian(&h, spread, ctx.tile); - let mid = ops::gaussian(&h, spread * 0.35, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let i = (y * ctx.w + x) as usize; - let occ = ((wide.data[i] - h.data[i]).max(0.0) * 0.6 + (mid.data[i] - h.data[i]).max(0.0) * 0.4) * depth * 6.0; - [(1.0 - occ).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn bevel(ctx: &Ctx) -> CookResult { - let m = ctx.gray_or(0, 0.0); - let d = ctx.f("distance"); - let dist_px = (d.abs() * ctx.w as f32).max(1e-3); - let data = m.data.clone(); - let outside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile); - let inside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile); - let v: Vec<f32> = (0..outside.len()) - .map(|i| { - if d >= 0.0 { - // Inner bevel: ramp up from the edge inward. - if data[i] > 0.5 { (inside[i].sqrt() / dist_px).min(1.0) } else { 0.0 } - } else if data[i] > 0.5 { - 1.0 - } else { - (1.0 - outside[i].sqrt() / dist_px).max(0.0) - } - }) - .collect(); - let img = ops::gray_from(ctx.w, ctx.h, v); - let s = ctx.f("smoothing") * ctx.w as f32 / 128.0; - Ok(vec![ops::gaussian(&img.map(Kind::Gray, |p| [(p[0] * std::f32::consts::FRAC_PI_2).sin(), 0.0, 0.0, 0.0]), s, ctx.tile)]) -} - -fn curvature(ctx: &Ctx) -> CookResult { - let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color(); - let k = ctx.f("intensity") * 2.0; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let (x, y) = (x as i64, y as i64); - let dx = n.get(x + 1, y, ctx.tile)[0] - n.get(x - 1, y, ctx.tile)[0]; - let dy = n.get(x, y + 1, ctx.tile)[1] - n.get(x, y - 1, ctx.tile)[1]; - [(0.5 + (dx - dy) * k).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn morph(ctx: &Ctx, max: bool) -> CookResult { - let img = src(ctx); - let r = ctx.i("radius").clamp(0, 64) as i64; - if r == 0 { - return Ok(vec![img]); - } - // Separable square window: rows then columns. - let pass = |src: &Image, horizontal: bool| { - Image::generate(src.w, src.h, src.kind, |x, y| { - let mut acc = src.get(x as i64, y as i64, ctx.tile); - for o in -r..=r { - let p = if horizontal { src.get(x as i64 + o, y as i64, ctx.tile) } else { src.get(x as i64, y as i64 + o, ctx.tile) }; - for k in 0..4 { - acc[k] = if max { acc[k].max(p[k]) } else { acc[k].min(p[k]) }; - } - } - acc - }) - }; - Ok(vec![pass(&pass(&img, true), false)]) -} - -fn dilation(ctx: &Ctx) -> CookResult { - morph(ctx, true) -} - -fn erosion(ctx: &Ctx) -> CookResult { - morph(ctx, false) -} - -fn edge_detect(ctx: &Ctx) -> CookResult { - let m = ctx.gray_or(0, 0.0); - let w = (ctx.f("width") * ctx.w as f32 / 256.0).max(0.5); - let data = m.data.clone(); - let a = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile); - let b = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile); - let round = ctx.f("roundness"); - let v: Vec<f32> = a - .iter() - .zip(&b) - .map(|(a, b)| { - let d = a.sqrt().max(b.sqrt()); - let t = (1.0 - d / w).max(0.0); - // A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2. - t.powf((1.0 - round * 0.8).max(0.01)) - }) - .collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn glow(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (t, amt) = (ctx.f("threshold"), ctx.f("amount")); - let bright = img.map(img.kind, |p| { - let l = luminance(p); - let k = if l > t { 1.0 } else { 0.0 }; - [p[0] * k, p[1] * k, p[2] * k, p[3]] - }); - let b = ops::gaussian(&bright, ctx.f("size") * ctx.w as f32 / 256.0, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (p, g) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - [p[0] + g[0] * amt, p[1] + g[1] * amt, p[2] + g[2] * amt, p[3]] - })]) -} - -fn highpass(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let b = ops::gaussian(&img, ctx.f("radius") * ctx.w as f32 / 256.0, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (p, q) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - [p[0] - q[0] + 0.5, p[1] - q[1] + 0.5, p[2] - q[2] + 0.5, p[3]] - })]) -} - -fn mosaic(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let n = ctx.i("cells").max(1) as f32; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| img.sample(((u * n).floor() + 0.5) / n, ((v * n).floor() + 0.5) / n, ctx.tile))]) -} - -fn swirl(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (amt, rad) = (ctx.f("amount") * TAU, ctx.f("radius").max(1e-3)); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = (u - 0.5, v - 0.5); - let r = (x * x + y * y).sqrt(); - let t = (1.0 - r / rad).max(0.0); - let a = amt * t * t; - let (s, c) = a.sin_cos(); - img.sample(x * c - y * s + 0.5, x * s + y * c + 0.5, ctx.tile) - })]) -} - -fn vignette(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (amt, soft) = (ctx.f("amount"), ctx.f("softness").max(0.01)); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let p = img.sample_nearest(u, v, false); - let r = ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() * std::f32::consts::SQRT_2; - let k = 1.0 - amt * ((r - (1.0 - soft)) / soft).clamp(0.0, 1.0); - [p[0] * k, p[1] * k, p[2] * k, p[3]] - })]) -} - -fn quantize(ctx: &Ctx) -> CookResult { - let n = (ctx.i("steps").max(2) - 1) as f32; - let s = ctx.f("smoothness").clamp(0.0, 1.0) * 0.5; - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |p| { - let x = p[0] * n; - let f = x.fract(); - let t = if s > 0.0 { ((f - 0.5 + s) / (2.0 * s)).clamp(0.0, 1.0) } else { (f >= 0.5) as i32 as f32 }; - [(x.floor() + t * t * (3.0 - 2.0 * t)) / n, 0.0, 0.0, 0.0] - })]) -} - -fn height_normal(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - Ok(vec![height_to_normal(&h, ctx.f("intensity") * ctx.w as f32 / 32.0, ctx.i("format") == 1, ctx.tile, false)]) -} - -fn unpack(p: [f32; 4]) -> [f32; 3] { - [p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0] -} - -fn pack(n: [f32; 3], a: f32) -> [f32; 4] { - let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6); - [n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a] -} - -fn flat_normal(ctx: &Ctx, i: usize) -> Image { - ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color() -} - -fn normal_blend(ctx: &Ctx) -> CookResult { - let (base, det) = (flat_normal(ctx, 0), flat_normal(ctx, 1)); - let mask = ctx.sized(2).map(|m| m.to_gray()); - let op = ctx.f("opacity"); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (x, y) = (x as i64, y as i64); - let k = op * mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); - let b = unpack(base.get(x, y, false)); - let mut d = unpack(det.get(x, y, false)); - d = [d[0] * k, d[1] * k, 1.0 + (d[2] - 1.0) * k]; - // Reoriented normal mapping (Barré-Brisebois & Hill). - let t = [b[0], b[1], b[2] + 1.0]; - let u = [-d[0], -d[1], d[2]]; - let dot = t[0] * u[0] + t[1] * u[1] + t[2] * u[2]; - let r = [t[0] * dot / t[2] - u[0], t[1] * dot / t[2] - u[1], t[2] * dot / t[2] - u[2]]; - pack(r, 1.0) - })]) -} - -fn normal_invert(ctx: &Ctx) -> CookResult { - let n = flat_normal(ctx, 0); - let (r, g) = (ctx.b("red"), ctx.b("green")); - Ok(vec![n.map(Kind::Color, |p| [if r { 1.0 - p[0] } else { p[0] }, if g { 1.0 - p[1] } else { p[1] }, p[2], p[3]])]) -} - -fn normal_normalize(ctx: &Ctx) -> CookResult { - let n = flat_normal(ctx, 0); - Ok(vec![n.map(Kind::Color, |p| pack(unpack(p), p[3]))]) -} - -fn normal_intensity(ctx: &Ctx) -> CookResult { - let n = flat_normal(ctx, 0); - let k = ctx.f("intensity"); - Ok(vec![n.map(Kind::Color, |p| { - let v = unpack(p); - pack([v[0] * k, v[1] * k, v[2].max(1e-3)], p[3]) - })]) -} - -fn normal_to_height(ctx: &Ctx) -> CookResult { - // Integrate the slopes at several scales (a multigrid-style Poisson solve: coarse levels set - // the broad shape, finer ones the detail). - let n = flat_normal(ctx, 0); - let (w, h) = (ctx.w, ctx.h); - let gx = n.map(Kind::Gray, |p| { - let v = unpack(p); - [-v[0] / v[2].max(0.1), 0.0, 0.0, 0.0] - }); - let gy = n.map(Kind::Gray, |p| { - let v = unpack(p); - [v[1] / v[2].max(0.1), 0.0, 0.0, 0.0] - }); - let mut height = Image::filled(8.min(w), 8.min(h), Kind::Gray, [0.0; 4]); - let mut size = 8u32; - loop { - let (sw, sh) = (size.min(w), size.min(h)); - let (gxs, gys) = (gx.resize(sw, sh, true), gy.resize(sw, sh, true)); - let scale = w as f32 / sw as f32; - let mut cur = height.resize(sw, sh, true); - for _ in 0..40 { - let prev = cur.clone(); - cur = Image::generate(sw, sh, Kind::Gray, |x, y| { - let (x, y) = (x as i64, y as i64); - let nb = prev.get(x - 1, y, true)[0] + prev.get(x + 1, y, true)[0] + prev.get(x, y - 1, true)[0] + prev.get(x, y + 1, true)[0]; - // Divergence of the gradient field (pixels of this level). - let div = (gxs.get(x + 1, y, true)[0] - gxs.get(x - 1, y, true)[0] + gys.get(x, y + 1, true)[0] - gys.get(x, y - 1, true)[0]) * 0.5 / scale; - [(nb - div) * 0.25, 0.0, 0.0, 0.0] - }); - } - height = cur; - if sw >= w && sh >= h { - break; - } - size *= 2; - } - let (lo, hi) = height.range(); - let k = ctx.f("intensity"); - let span = (hi - lo).max(1e-6); - Ok(vec![height.map(Kind::Gray, |p| [(((p[0] - lo) / span - 0.5) * k + 0.5).clamp(0.0, 1.0), 0.0, 0.0, 0.0])]) -} - -fn make_it_tile(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let b = ctx.f("blend").clamp(0.01, 0.5); - // Blend the image with a half-offset copy near the borders. - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let p = img.sample(u, v, true); - let q = img.sample(u + 0.5, v + 0.5, true); - let edge = (u.min(1.0 - u)).min(v.min(1.0 - v)); - let t = (edge / b).clamp(0.0, 1.0); - let t = t * t * (3.0 - 2.0 * t); - [q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t, q[2] + (p[2] - q[2]) * t, q[3] + (p[3] - q[3]) * t] - })]) -} - -fn safe_transform(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let n = ctx.i("tile").max(1) as f32; - let off = ctx.v2("offset"); - let (rot, flip) = (ctx.i("rotation"), ctx.b("flip")); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (mut x, mut y) = ((u * n - off[0]).rem_euclid(1.0), (v * n - off[1]).rem_euclid(1.0)); - for _ in 0..rot.rem_euclid(4) { - (x, y) = (y, 1.0 - x); - } - if flip { - x = 1.0 - x; - } - img.sample(x, y, true) - })]) -} - -fn mirror(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (axis, flip) = (ctx.i("axis"), ctx.b("flip")); - let m = |t: f32| { - if flip { - if t < 0.5 { 1.0 - t } else { t } - } else if t > 0.5 { - 1.0 - t - } else { - t - } - }; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| match axis { - 1 => img.sample(u, m(v), ctx.tile), - 2 => img.sample(m(u), m(v), ctx.tile), - _ => img.sample(m(u), v, ctx.tile), - })]) -} - -fn kaleidoscope(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let seg = TAU / ctx.i("segments").clamp(2, 64) as f32; - let a0 = ctx.f("angle") * TAU; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = (u - 0.5, v - 0.5); - let r = (x * x + y * y).sqrt(); - let mut a = (y.atan2(x) - a0).rem_euclid(seg); - if a > seg * 0.5 { - a = seg - a; - } - let a = a + a0; - img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile) - })]) -} - -fn cartesian_to_polar(ctx: &Ctx) -> CookResult { - let img = src(ctx); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = (u - 0.5, v - 0.5); - let r = (x * x + y * y).sqrt() * 2.0; - let a = (y.atan2(x) / TAU).rem_euclid(1.0); - img.sample(a, r, true) - })]) -} - -fn polar_to_cartesian(ctx: &Ctx) -> CookResult { - let img = src(ctx); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (a, r) = (u * TAU, v * 0.5); - img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile) - })]) -} - -fn skew(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (k, vert) = (ctx.f("amount"), ctx.b("vertical")); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - if vert { img.sample(u, v + (u - 0.5) * k, ctx.tile) } else { img.sample(u + (v - 0.5) * k, v, ctx.tile) } - })]) -} diff --git a/crates/nodes/src/filters_extra.rs b/crates/nodes/src/filters_extra.rs deleted file mode 100644 index 4d1de25c..00000000 --- a/crates/nodes/src/filters_extra.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! More filters: random per-tile transforms, horizon-based ambient occlusion, a 5×5 Sobel normal -//! map, value band selection, palette quantization and block-averaged pixelation. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind, luminance}; -use rayon::prelude::*; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::filters_more::pack; -use crate::noise::rand2; -use crate::noises_more::smoothstep; - -const ADJ: &str = "Filters/Adjustments"; -const EFFECTS: &str = "Filters/Effects"; -const NORMAL: &str = "Filters/Normal map"; -const TILING: &str = "Filters/Tiling"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("tile_random", "Tile Random", TILING) - .desc("Cuts the image into a grid and shows a randomly offset, flipped and rotated window of the input in each tile (breaks up repetition).") - .any_in("input", "Input") - .int("x_amount", "X amount", 4, 1, 256) - .int("y_amount", "Y amount", 4, 1, 256) - .float("offset_random", "Offset random", 1.0, 0.0, 1.0) - .boolean("rotate", "Random 90° rotation", true) - .boolean("flip", "Random flip", true) - .float("luminance_random", "Luminance random", 0.0, 0.0, 1.0) - .cook(tile_random), - node("ambient_occlusion_fast", "Ambient Occlusion (Fast)", EFFECTS) - .desc("Horizon-based ambient occlusion of a height map: how much of the sky each pixel sees within the radius.") - .gray_in("height", "Height") - .float("radius", "Radius", 12.0, 1.0, 128.0) - .float("height_depth", "Height depth", 0.3, 0.0, 1.0) - .float("intensity", "Intensity", 1.0, 0.0, 2.0) - .gray_out() - .cook(ambient_occlusion_fast), - node("normal_from_height_hq", "Normal from Height HQ", NORMAL) - .desc("A smooth normal map from a height map with 5×5 Sobel slopes.") - .gray_in("input", "Height") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) - .color_out() - .cook(normal_from_height_hq), - node("histogram_select", "Histogram Select", ADJ) - .desc("White where values lie in a band around the position, fading out with the contrast.") - .gray_in("input", "Input") - .float("position", "Position", 0.5, 0.0, 1.0) - .float("range", "Range", 0.25, 0.0, 1.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(histogram_select), - node("quantize_color", "Quantize Color", ADJ) - .desc("Reduces the image to a palette of its most representative colors (k-means), with optional ordered dithering.") - .color_in("input", "Input") - .int("colors", "Colors", 8, 2, 64) - .float("dither", "Dither", 0.0, 0.0, 1.0) - .color_out() - .cook(quantize_color), - node("pixelate_color", "Pixelate Color", EFFECTS) - .desc("Averages the image over blocks (separate X and Y counts).") - .any_in("input", "Input") - .int("x_cells", "X cells", 32, 1, 1024) - .int("y_cells", "Y cells", 32, 1, 1024) - .cook(pixelate_color), - ] -} - -fn tile_random(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let (nx, ny) = (ctx.i("x_amount").clamp(1, 256) as f32, ctx.i("y_amount").clamp(1, 256) as f32); - let (off, rot, flip, lr, s) = (ctx.f("offset_random"), ctx.b("rotate"), ctx.b("flip"), ctx.f("luminance_random"), ctx.seed); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (cx, cy) = ((u * nx).floor(), (v * ny).floor()); - let (ci, cj) = ((cx as i32).rem_euclid(nx as i32), (cy as i32).rem_euclid(ny as i32)); - let r = |k: u32| rand2(ci, cj, s ^ k.wrapping_mul(0x2545_f491)); - // Offset from the tile center in uv, flipped and turned by quarter turns. - let (mut a, mut b) = ((u * nx - cx - 0.5) / nx, (v * ny - cy - 0.5) / ny); - if flip && r(1) < 0.5 { - a = -a; - } - if rot { - for _ in 0..(r(2) * 4.0) as i32 { - (a, b) = (-b, a); - } - } - let su = (cx + 0.5) / nx + a + (r(3) - 0.5) * off; - let sv = (cy + 0.5) / ny + b + (r(4) - 0.5) * off; - let p = img.sample(su, sv, true); - let k = 1.0 - lr * r(5); - [p[0] * k, p[1] * k, p[2] * k, p[3]] - })]) -} - -fn ambient_occlusion_fast(ctx: &Ctx) -> CookResult { - const DIRS: usize = 8; - const STEPS: usize = 6; - let h = ctx.gray_or(0, 0.0); - let scale = ctx.w as f32 / 256.0; - let rad = (ctx.f("radius") * scale).clamp(1.0, 1024.0); - let hs = ctx.f("height_depth") * 64.0 * scale; - let k = ctx.f("intensity"); - // Integer offsets along each direction, denser near the pixel, and their true distances. - let taps: Vec<(i64, i64, f32)> = (0..DIRS) - .flat_map(|d| { - let (sn, cs) = ((d as f32 + 0.5) / DIRS as f32 * TAU).sin_cos(); - (1..=STEPS).map(move |s| { - let dist = rad * (s as f32 / STEPS as f32).powf(1.5); - let (ox, oy) = ((cs * dist).round(), (sn * dist).round()); - (ox as i64, oy as i64, (ox * ox + oy * oy).sqrt().max(1.0)) - }) - }) - .collect(); - let tile = ctx.tile; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let (x, y) = (x as i64, y as i64); - let h0 = h.get_gray(x, y, tile); - let occ: f32 = taps - .chunks(STEPS) - .map(|dir| { - // Tangent of the highest horizon in this direction, as the sine of its angle. - let m = dir.iter().fold(0.0f32, |m, &(ox, oy, d)| m.max((h.get_gray(x + ox, y + oy, tile) - h0) * hs / d)); - m / (1.0 + m * m).sqrt() - }) - .sum(); - [(1.0 - k * occ / DIRS as f32).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn normal_from_height_hq(ctx: &Ctx) -> CookResult { - const SMOOTH: [f32; 5] = [1.0, 4.0, 6.0, 4.0, 1.0]; - const DERIV: [f32; 5] = [-1.0, -2.0, 0.0, 2.0, 1.0]; - let h = ctx.gray_or(0, 0.0); - // The kernels sum to 128 × the slope of a linear ramp. - let k = ctx.f("intensity") * ctx.w as f32 / 32.0 / 128.0; - let dx_fmt = ctx.i("format") == 1; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (mut gx, mut gy) = (0.0, 0.0); - for j in 0..5 { - for i in 0..5 { - let v = h.get_gray(x as i64 + i as i64 - 2, y as i64 + j as i64 - 2, ctx.tile); - gx += SMOOTH[j] * DERIV[i] * v; - gy += DERIV[j] * SMOOTH[i] * v; - } - } - let ny = gy * k; - pack([-gx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0) - })]) -} - -fn histogram_select(ctx: &Ctx) -> CookResult { - let (pos, half) = (ctx.f("position"), ctx.f("range") * 0.5); - let soft = (1.0 - ctx.f("contrast").clamp(0.0, 1.0)) * 0.25 + 1e-3; - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |p| [1.0 - smoothstep(half, half + soft, (p[0] - pos).abs()), 0.0, 0.0, 0.0])]) -} - -/// Index of the color in `pal` nearest to `c`. -fn nearest(pal: &[[f32; 3]], c: [f32; 3]) -> usize { - let d = |p: &[f32; 3]| (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2); - pal.iter().enumerate().min_by(|a, b| d(a.1).total_cmp(&d(b.1))).map_or(0, |(i, _)| i) -} - -fn quantize_color(ctx: &Ctx) -> CookResult { - const BAYER: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0]; - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let k = ctx.i("colors").clamp(2, 64) as usize; - let rgb = |p: &[f32]| [p[0], p[1], p[2]]; - // Lloyd's k-means on up to ~4096 samples, seeded at luminance quantiles. - let step = (img.data.len() / 4 / 4096).max(1); - let mut samples: Vec<[f32; 3]> = img.data.chunks_exact(4).step_by(step).map(rgb).collect(); - samples.sort_by(|a, b| luminance([a[0], a[1], a[2], 1.0]).total_cmp(&luminance([b[0], b[1], b[2], 1.0]))); - let mut pal: Vec<[f32; 3]> = (0..k).filter_map(|j| samples.get(((j as f32 + 0.5) / k as f32 * samples.len() as f32) as usize).copied()).collect(); - for _ in 0..8 { - let mut acc = vec![[0.0f32; 4]; pal.len()]; - for s in &samples { - if let Some(a) = acc.get_mut(nearest(&pal, *s)) { - *a = [a[0] + s[0], a[1] + s[1], a[2] + s[2], a[3] + 1.0]; - } - } - for (p, a) in pal.iter_mut().zip(&acc) { - if a[3] > 0.0 { - *p = [a[0] / a[3], a[1] / a[3], a[2] / a[3]]; - } - } - } - let spread = ctx.f("dither") / (k as f32).cbrt(); - Ok(vec![Image::generate(img.w, img.h, Kind::Color, |x, y| { - let p = img.get(x as i64, y as i64, false); - let d = ((BAYER[(y as usize % 4) * 4 + x as usize % 4] + 0.5) / 16.0 - 0.5) * spread; - let c = pal.get(nearest(&pal, [p[0] + d, p[1] + d, p[2] + d])).copied().unwrap_or([p[0], p[1], p[2]]); - [c[0], c[1], c[2], p[3]] - })]) -} - -fn pixelate_color(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]); - let (w, h) = (img.w as usize, img.h as usize); - let (nx, ny) = (ctx.i("x_cells").clamp(1, 1024) as usize, ctx.i("y_cells").clamp(1, 1024) as usize); - // Block `b` of `n` over `len` pixels covers `b·len/n .. (b+1)·len/n` (at least one pixel). - let range = |n: usize, len: usize, b: usize| (b * len / n, ((b + 1) * len / n).max(b * len / n + 1).min(len)); - let block = |n: usize, len: usize, p: usize| (((p + 1) * n).saturating_sub(1) / len).min(n - 1); - let means: Vec<[f32; 4]> = (0..nx * ny) - .into_par_iter() - .map(|bi| { - let ((x0, x1), (y0, y1)) = (range(nx, w, bi % nx), range(ny, h, bi / nx)); - let mut s = [0.0f32; 4]; - for y in y0..y1 { - for x in x0..x1 { - let p = img.get(x as i64, y as i64, false); - s = std::array::from_fn(|c| s[c] + p[c]); - } - } - let n = ((x1 - x0) * (y1 - y0)).max(1) as f32; - s.map(|v| v / n) - }) - .collect(); - Ok(vec![Image::generate(img.w, img.h, img.kind, |x, y| { - means.get(block(ny, h, y as usize) * nx + block(nx, w, x as usize)).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]) - })]) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn nearest_and_block_math() { - assert_eq!(nearest(&[[0.0; 3], [1.0; 3]], [0.7; 3]), 1); - // Pixelate: a 2-cell split of a black/white image averages each half exactly. - let img = Image::gray(8, 2, |x, _| if x < 4 { 0.0 } else { 1.0 }); - let def = crate::catalog::find("pixelate_color").unwrap(); - let mut p = crate::catalog::resolve_params(def, &Default::default()); - p.insert("x_cells".into(), materialcraft_core::Value::Int(2)); - p.insert("y_cells".into(), materialcraft_core::Value::Int(1)); - let no_res = |_: &str| None; - let vars = Default::default(); - let inputs = [Some(img)]; - let ctx = Ctx { w: 8, h: 2, seed: 0, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars }; - let out = &pixelate_color(&ctx).unwrap()[0]; - assert_eq!((out.get(3, 1, false)[0], out.get(4, 0, false)[0]), (0.0, 1.0)); - } -} diff --git a/crates/nodes/src/filters_more.rs b/crates/nodes/src/filters_more.rs deleted file mode 100644 index 68c39415..00000000 --- a/crates/nodes/src/filters_more.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! More filters: tone remaps and per-channel adjustments, two-input math, median and unsharp -//! mask, Sobel edges, glows and shadows from masks, curvature from height, and normal map tools. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::flood_fill::region_rand; -use crate::noise::fbm; -use crate::noises_more::smoothstep; -use crate::ops; - -const ADJ: &str = "Filters/Adjustments"; -const BLENDING: &str = "Filters/Blending"; -const BLURS: &str = "Filters/Blurs"; -const EFFECTS: &str = "Filters/Effects"; -const NORMAL: &str = "Filters/Normal map"; - -/// A tangent-space normal from a normal map pixel (0..1 → -1..1). -#[inline] -pub(crate) fn unpack(p: [f32; 4]) -> [f32; 3] { - [p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0] -} - -/// A normalized normal back to a normal map pixel. -#[inline] -pub(crate) fn pack(n: [f32; 3], a: f32) -> [f32; 4] { - let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6); - [n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a] -} - -/// The pixel offset of `dist` (pixels at 256) along `angle` (turns, y down). -fn offset(ctx: &Ctx, angle: f32, dist: f32) -> (i64, i64) { - let (s, c) = (angle * TAU).sin_cos(); - let d = dist * ctx.w as f32 / 256.0; - ((c * d).round() as i64, (-s * d).round() as i64) -} - -fn px(ctx: &Ctx, v: f32) -> f32 { - v * ctx.w as f32 / 256.0 -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let two = |id, label, desc| node(id, label, BLENDING).desc(desc).any_in("input_a", "A").any_in("input_b", "B"); - let mask_in = |id, label, cat| node(id, label, cat).gray_in("input", "Mask"); - vec![ - // ---- Adjustments - node("remap", "Remap", ADJ) - .desc("Maps the input range linearly onto the output range.") - .any_in("input", "Input") - .float("in_min", "Input min", 0.0, 0.0, 1.0) - .float("in_max", "Input max", 1.0, 0.0, 1.0) - .float("out_min", "Output min", 0.0, 0.0, 1.0) - .float("out_max", "Output max", 1.0, 0.0, 1.0) - .boolean("clamp", "Clamp", true) - .cook(remap), - node("smoothstep", "Smoothstep", ADJ) - .desc("A smooth S-shaped step from the low edge (black) to the high edge (white).") - .any_in("input", "Input") - .float("low", "Low edge", 0.25, 0.0, 1.0) - .float("high", "High edge", 0.75, 0.0, 1.0) - .cook(smoothstep_node), - node("s_curve", "S-Curve Contrast", ADJ) - .desc("Raises contrast around a pivot with a smooth S curve (keeps black and white).") - .any_in("input", "Input") - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("pivot", "Pivot", 0.5, 0.01, 0.99) - .cook(s_curve), - node("channel_levels", "Channel Levels", ADJ) - .desc("Levels with a separate input range per channel.") - .any_in("input", "Input") - .color("low", "Input low", [0.0, 0.0, 0.0, 0.0]) - .color("high", "Input high", [1.0, 1.0, 1.0, 1.0]) - .float("gamma", "Gamma", 1.0, 0.1, 4.0) - .cook(channel_levels), - node("auto_levels_channels", "Auto Levels per Channel", ADJ) - .desc("Stretches each color channel separately to the full 0..1 range.") - .any_in("input", "Input") - .cook(auto_levels_channels), - node("invert_channels", "Invert Channels", ADJ) - .desc("Inverts the chosen channels.") - .any_in("input", "Input") - .boolean("red", "Red", true) - .boolean("green", "Green", true) - .boolean("blue", "Blue", true) - .boolean("alpha", "Alpha", false) - .cook(invert_channels), - node("clamp_channels", "Clamp Channels", ADJ) - .desc("Clamps each channel between its own minimum and maximum.") - .any_in("input", "Input") - .color("min", "Min", [0.0, 0.0, 0.0, 0.0]) - .color("max", "Max", [1.0, 1.0, 1.0, 1.0]) - .cook(clamp_channels), - node("color_variation", "Color Variation", ADJ) - .desc("Random hue, saturation and value shifts: per region when a flood fill index map is connected, else from soft noise.") - .color_in("input", "Input") - .color_in("index", "Index map (optional)") - .float("hue", "Hue random", 0.03, 0.0, 0.5) - .float("saturation", "Saturation random", 0.15, 0.0, 1.0) - .float("value", "Value random", 0.2, 0.0, 1.0) - .float("scale", "Noise scale", 4.0, 1.0, 64.0) - .color_out() - .cook(color_variation), - // ---- Blending - node("lerp", "Lerp", BLENDING) - .desc("Linear interpolation from A to B by a mask (or a constant position without one).") - .any_in("input_a", "A") - .any_in("input_b", "B") - .gray_in("mask", "Mask") - .float("position", "Position (no mask)", 0.5, 0.0, 1.0) - .cook(lerp), - two("minimum", "Minimum", "The darker of A and B, per channel.").cook(minimum), - two("maximum", "Maximum", "The brighter of A and B, per channel.").cook(maximum), - two("multiply", "Multiply", "A times B.").cook(multiply), - two("difference", "Difference", "The absolute difference of A and B.").cook(difference), - two("add", "Add", "A plus B.").boolean("clamp", "Clamp", true).cook(add), - two("subtract", "Subtract", "A minus B.").boolean("clamp", "Clamp", true).cook(subtract), - // ---- Blurs - node("median", "Median", BLURS) - .desc("Median of each neighbourhood: removes specks while keeping edges.") - .any_in("input", "Input") - .choice("size", "Size", &["3 × 3", "5 × 5"], 0) - .cook(median), - node("unsharp_mask", "Unsharp Mask", BLURS) - .desc("Sharpens by adding back the difference from a blurred copy.") - .any_in("input", "Input") - .float("radius", "Radius", 2.0, 0.0, 32.0) - .float("amount", "Amount", 1.0, 0.0, 5.0) - .float("threshold", "Threshold", 0.0, 0.0, 1.0) - .cook(unsharp_mask), - // ---- Effects - node("sobel", "Sobel Edges", EFFECTS) - .desc("Edge strength from the Sobel operator.") - .gray_in("input", "Input") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .gray_out() - .cook(sobel), - mask_in("outer_glow", "Outer Glow", EFFECTS) - .desc("A glow fading outward from a mask (by exact distance).") - .float("size", "Size", 16.0, 0.0, 256.0) - .float("intensity", "Intensity", 1.0, 0.0, 1.0) - .float("falloff", "Falloff", 2.0, 0.25, 8.0) - .gray_out() - .cook(outer_glow), - mask_in("inner_shadow", "Inner Shadow", EFFECTS) - .desc("Darkens the inside of a mask along the edges facing the light.") - .angle("angle", "Light angle", -0.125) - .float("distance", "Distance", 6.0, 0.0, 64.0) - .float("size", "Size", 8.0, 0.0, 128.0) - .float("opacity", "Opacity", 0.75, 0.0, 1.0) - .gray_out() - .cook(inner_shadow), - mask_in("drop_shadow", "Drop Shadow", EFFECTS) - .desc("An offset, blurred shadow under a mask.") - .angle("angle", "Angle", -0.125) - .float("distance", "Distance", 8.0, 0.0, 128.0) - .float("size", "Blur", 4.0, 0.0, 64.0) - .float("opacity", "Opacity", 0.75, 0.0, 1.0) - .output("output", "Output", PortKind::Gray) - .output("shadow", "Shadow", PortKind::Gray) - .cook(drop_shadow), - node("height_curvature", "Curvature from Height", EFFECTS) - .desc("Convex areas above 0.5, concave below, from a height map.") - .gray_in("input", "Height") - .float("radius", "Radius", 2.0, 0.25, 32.0) - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .gray_out() - .cook(height_curvature), - mask_in("outline", "Outline", EFFECTS) - .desc("A line of constant width around the edges of a mask.") - .float("width", "Width", 4.0, 0.0, 64.0) - .choice("position", "Position", &["Outside", "Center", "Inside"], 1) - .gray_out() - .cook(outline), - // ---- Normal map - node("normal_combine", "Normal Combine", NORMAL) - .desc("Combines a detail normal map over a base one (whiteout blending).") - .color_in("base", "Base normal") - .color_in("detail", "Detail normal") - .float("intensity", "Detail intensity", 1.0, 0.0, 4.0) - .color_out() - .cook(normal_combine), - node("normal_rotate", "Normal Rotate", NORMAL) - .desc("Rotates the directions of a normal map (for rotated textures).") - .color_in("input", "Normal") - .angle("angle", "Angle", 0.0) - .color_out() - .cook(normal_rotate), - node("normal_sobel", "Normal Sobel", NORMAL) - .desc("A normal map from a height map with Sobel slopes (smoother than plain differences).") - .gray_in("input", "Height") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Format", &["OpenGL", "DirectX"], 0) - .color_out() - .cook(normal_sobel), - ] -} - -fn src(ctx: &Ctx) -> Image { - ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0]) -} - -/// Map R, G and B (gray: the value) with `f(value, channel)`; alpha kept. -fn per_channel(ctx: &Ctx, f: impl Fn(f32, usize) -> f32 + Sync) -> CookResult { - let img = src(ctx); - Ok(vec![img.map(img.kind, |p| [f(p[0], 0), f(p[1], 1), f(p[2], 2), p[3]])]) -} - -fn remap(ctx: &Ctx) -> CookResult { - let (a, b, c, d, cl) = (ctx.f("in_min"), ctx.f("in_max"), ctx.f("out_min"), ctx.f("out_max"), ctx.b("clamp")); - let span = if (b - a).abs() < 1e-6 { 1e-6 } else { b - a }; - per_channel(ctx, |v, _| { - let t = (v - a) / span; - c + (d - c) * if cl { t.clamp(0.0, 1.0) } else { t } - }) -} - -fn smoothstep_node(ctx: &Ctx) -> CookResult { - let (lo, hi) = (ctx.f("low"), ctx.f("high")); - per_channel(ctx, |v, _| smoothstep(lo, hi.max(lo + 1e-4), v)) -} - -fn s_curve(ctx: &Ctx) -> CookResult { - // A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1). - let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99)); - per_channel(ctx, |v, _| { - let v = v.clamp(0.0, 1.0); - if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) } - }) -} - -fn channel_levels(ctx: &Ctx) -> CookResult { - let (lo, hi, g) = (ctx.v4("low"), ctx.v4("high"), 1.0 / ctx.f("gamma").max(0.01)); - per_channel(ctx, |v, c| { - let span = (hi[c] - lo[c]).abs().max(1e-6).copysign(hi[c] - lo[c]); - ((v - lo[c]) / span).clamp(0.0, 1.0).powf(g) - }) -} - -fn auto_levels_channels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let c = img.channels(); - let mut lo = [f32::INFINITY; 3]; - let mut hi = [f32::NEG_INFINITY; 3]; - for p in img.data.chunks(c) { - for k in 0..c.min(3) { - lo[k] = lo[k].min(p[k]); - hi[k] = hi[k].max(p[k]); - } - } - per_channel(ctx, |v, k| { - let k = if c == 1 { 0 } else { k }; - let span = hi[k] - lo[k]; - if span.is_finite() && span > 1e-6 { (v - lo[k]) / span } else { v } - }) -} - -fn invert_channels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let flags = [ctx.b("red"), ctx.b("green"), ctx.b("blue"), ctx.b("alpha")]; - Ok(vec![img.map(img.kind, |p| std::array::from_fn(|k| if flags[k] { 1.0 - p[k] } else { p[k] }))]) -} - -fn clamp_channels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (lo, hi) = (ctx.v4("min"), ctx.v4("max")); - Ok(vec![img.map(img.kind, |p| std::array::from_fn(|k| p[k].max(lo[k]).min(hi[k].max(lo[k]))))]) -} - -fn color_variation(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let index = ctx.input(1); - let (hr, sr, vr, sc, s, tile) = (ctx.f("hue"), ctx.f("saturation"), ctx.f("value"), ctx.f("scale").max(1.0).round(), ctx.seed, ctx.tile); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Color, |u, v| { - let p = img.sample_nearest(u, v, false); - // Three random shifts in -1..1: per flood fill region, or from noise. - let r: [f32; 3] = match index.map(|i| i.sample_nearest(u, v, tile)) { - Some(q) if q[3] > 0.5 => std::array::from_fn(|k| region_rand(q[2], 10 + k as u32, s) * 2.0 - 1.0), - Some(_) => [0.0; 3], - None => std::array::from_fn(|k| (fbm(u, v, sc, 3, 0.5, s.wrapping_add(k as u32 * 101)) - 0.5) * 4.0), - }; - let hsl = ops::rgb_to_hsl(p); - let c = ops::hsl_to_rgb(hsl[0] + hr * r[0], (hsl[1] * (1.0 + sr * r[1])).clamp(0.0, 1.0), (hsl[2] * (1.0 + vr * r[2])).max(0.0)); - [c[0], c[1], c[2], p[3]] - })]) -} - -fn lerp(ctx: &Ctx) -> CookResult { - let kind = ctx.main_kind(Kind::Gray); - let (a, b) = (ctx.any_or(0, kind, [0.0, 0.0, 0.0, 1.0]).to_kind(kind), ctx.any_or(1, kind, [1.0; 4]).to_kind(kind)); - let m = ctx.gray_or(2, ctx.f("position")); - Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| { - let (x, y) = (x as i64, y as i64); - let (p, q, t) = (a.get(x, y, false), b.get(x, y, false), m.get_gray(x, y, false)); - std::array::from_fn(|k| p[k] + (q[k] - p[k]) * t) - })]) -} - -/// Per-channel `f(a, b)` of two inputs (in the kind of the first connected one); B defaults to -/// `b_default`; alpha from A. -fn binary(ctx: &Ctx, b_default: f32, f: impl Fn(f32, f32) -> f32 + Sync) -> CookResult { - let kind = ctx.main_kind(Kind::Gray); - let a = ctx.any_or(0, kind, [0.0, 0.0, 0.0, 1.0]).to_kind(kind); - let b = ctx.any_or(1, kind, [b_default, b_default, b_default, 1.0]).to_kind(kind); - Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| { - let (p, q) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - [f(p[0], q[0]), f(p[1], q[1]), f(p[2], q[2]), p[3]] - })]) -} - -fn minimum(ctx: &Ctx) -> CookResult { - binary(ctx, 1.0, f32::min) -} - -fn maximum(ctx: &Ctx) -> CookResult { - binary(ctx, 0.0, f32::max) -} - -fn multiply(ctx: &Ctx) -> CookResult { - binary(ctx, 1.0, |a, b| a * b) -} - -fn difference(ctx: &Ctx) -> CookResult { - binary(ctx, 0.0, |a, b| (a - b).abs()) -} - -fn add(ctx: &Ctx) -> CookResult { - let cl = ctx.b("clamp"); - binary(ctx, 0.0, |a, b| if cl { (a + b).clamp(0.0, 1.0) } else { a + b }) -} - -fn subtract(ctx: &Ctx) -> CookResult { - let cl = ctx.b("clamp"); - binary(ctx, 0.0, |a, b| if cl { (a - b).clamp(0.0, 1.0) } else { a - b }) -} - -fn median(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let r: i64 = if ctx.i("size") == 1 { 2 } else { 1 }; - let c = img.channels(); - let tile = ctx.tile; - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let mut buf = [[0.0f32; 25]; 4]; - let mut n = 0; - for dy in -r..=r { - for dx in -r..=r { - let p = img.get(x as i64 + dx, y as i64 + dy, tile); - for (k, b) in buf.iter_mut().enumerate() { - b[n] = p[k]; - } - n += 1; - } - } - let mut out = [0.0; 4]; - for (k, b) in buf.iter_mut().enumerate().take(c) { - let s = &mut b[..n]; - let (_, m, _) = s.select_nth_unstable_by(n / 2, f32::total_cmp); - out[k] = *m; - } - out - })]) -} - -fn unsharp_mask(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let blurred = ops::gaussian(&img, px(ctx, ctx.f("radius")), ctx.tile); - let (amt, th) = (ctx.f("amount"), ctx.f("threshold")); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (p, q) = (img.get(x as i64, y as i64, false), blurred.get(x as i64, y as i64, false)); - let f = |a: f32, b: f32| if (a - b).abs() > th { a + (a - b) * amt } else { a }; - [f(p[0], q[0]), f(p[1], q[1]), f(p[2], q[2]), p[3]] - })]) -} - -/// Sobel slopes (dx, dy) of a gray image, in value units per pixel. -fn sobel_slope(img: &Image, x: i64, y: i64, tile: bool) -> (f32, f32) { - let g = |dx: i64, dy: i64| img.get_gray(x + dx, y + dy, tile); - let gx = g(1, -1) + 2.0 * g(1, 0) + g(1, 1) - g(-1, -1) - 2.0 * g(-1, 0) - g(-1, 1); - let gy = g(-1, 1) + 2.0 * g(0, 1) + g(1, 1) - g(-1, -1) - 2.0 * g(0, -1) - g(1, -1); - (gx / 8.0, gy / 8.0) -} - -fn sobel(ctx: &Ctx) -> CookResult { - let img = ctx.gray_or(0, 0.0); - let k = ctx.f("intensity") * 2.0; - Ok(vec![Image::gray(ctx.w, ctx.h, |x, y| { - let (dx, dy) = sobel_slope(&img, x as i64, y as i64, ctx.tile); - ((dx * dx + dy * dy).sqrt() * k).min(1.0) - })]) -} - -/// The mask input (inside where above 0.5). -fn mask(ctx: &Ctx) -> Image { - ctx.gray_or(0, 0.0) -} - -fn outer_glow(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let d2 = ops::distance_sq(ctx.w, ctx.h, |i| m.data.get(i).is_some_and(|v| *v > 0.5), ctx.tile); - let (size, amt, fall) = (px(ctx, ctx.f("size")).max(1e-3), ctx.f("intensity"), ctx.f("falloff").max(0.01)); - let v = d2.iter().zip(m.data.iter()).map(|(d, mv)| mv.max((1.0 - d.sqrt() / size).max(0.0).powf(fall) * amt)).collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn inner_shadow(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let (ox, oy) = offset(ctx, ctx.f("angle"), ctx.f("distance")); - let (w, tile) = (ctx.w as usize, ctx.tile); - // Distance to the nearest pixel outside the mask shifted toward the shadow. - let d2 = ops::distance_sq(ctx.w, ctx.h, |i| m.get_gray((i % w) as i64 - ox, (i / w) as i64 - oy, tile) <= 0.5, tile); - let (size, op) = (px(ctx, ctx.f("size")).max(1e-3), ctx.f("opacity")); - let v = d2.iter().zip(m.data.iter()).map(|(d, mv)| mv * (1.0 - op * (1.0 - d.sqrt() / size).clamp(0.0, 1.0))).collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn drop_shadow(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let (ox, oy) = offset(ctx, ctx.f("angle"), ctx.f("distance")); - let shifted = Image::gray(ctx.w, ctx.h, |x, y| m.get_gray(x as i64 - ox, y as i64 - oy, ctx.tile)); - let op = ctx.f("opacity"); - let shadow = ops::gaussian(&shifted, px(ctx, ctx.f("size")), ctx.tile).map(Kind::Gray, |p| [p[0] * op, 0.0, 0.0, 0.0]); - let out = Image::gray(ctx.w, ctx.h, |x, y| m.get_gray(x as i64, y as i64, false).max(shadow.get_gray(x as i64, y as i64, false))); - Ok(vec![out, shadow]) -} - -fn height_curvature(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let r = px(ctx, ctx.f("radius")); - // Difference of Gaussians: a band-limited Laplacian that ignores pixel noise. - let (fine, wide) = (ops::gaussian(&h, r * 0.5, ctx.tile), ops::gaussian(&h, r * 2.0, ctx.tile)); - let k = ctx.f("intensity") * 8.0; - let v = fine.data.iter().zip(wide.data.iter()).map(|(a, b)| (0.5 + (a - b) * k).clamp(0.0, 1.0)).collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn outline(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let inside = |i: usize| m.data.get(i).is_some_and(|v| *v > 0.5); - let to_in = ops::distance_sq(ctx.w, ctx.h, inside, ctx.tile); - let to_out = ops::distance_sq(ctx.w, ctx.h, |i| !inside(i), ctx.tile); - let w = px(ctx, ctx.f("width")); - let (lo, hi) = match ctx.i("position") { - 0 => (0.0, w), - 2 => (-w, 0.0), - _ => (-w * 0.5, w * 0.5), - }; - // Signed distance to the edge (positive outside), half a pixel off each side of it. - let v = (0..to_in.len()) - .map(|i| { - let sd = if inside(i) { 0.5 - to_out[i].sqrt() } else { to_in[i].sqrt() - 0.5 }; - (sd - lo + 0.5).clamp(0.0, 1.0) * (hi - sd + 0.5).clamp(0.0, 1.0) - }) - .collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn flat(ctx: &Ctx, i: usize) -> Image { - ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color() -} - -fn normal_combine(ctx: &Ctx) -> CookResult { - let (base, det) = (flat(ctx, 0), flat(ctx, 1)); - let k = ctx.f("intensity"); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (b, d) = (unpack(base.get(x as i64, y as i64, false)), unpack(det.get(x as i64, y as i64, false))); - // Whiteout blending: add the slopes, multiply the heights. - pack([b[0] + d[0] * k, b[1] + d[1] * k, b[2] * (1.0 + (d[2] - 1.0) * k.min(1.0)).max(1e-3)], 1.0) - })]) -} - -fn normal_rotate(ctx: &Ctx) -> CookResult { - let n = flat(ctx, 0); - let (s, c) = (ctx.f("angle") * TAU).sin_cos(); - Ok(vec![n.map(Kind::Color, |p| { - let v = unpack(p); - pack([v[0] * c - v[1] * s, v[0] * s + v[1] * c, v[2]], p[3]) - })]) -} - -fn normal_sobel(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let k = ctx.f("intensity") * ctx.w as f32 / 32.0; - let dx_fmt = ctx.i("format") == 1; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (dx, dy) = sobel_slope(&h, x as i64, y as i64, ctx.tile); - let ny = dy * k; - pack([-dx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0) - })]) -} diff --git a/crates/nodes/src/flood_fill.rs b/crates/nodes/src/flood_fill.rs deleted file mode 100644 index ccc7c658..00000000 --- a/crates/nodes/src/flood_fill.rs +++ /dev/null @@ -1,306 +0,0 @@ -//! Filters › Flood fill: labels the connected white regions of a tile mask and turns each region -//! into per-region data (random values, colors, gradients, sizes, positions). -//! -//! The index map that [`flood_fill`] writes holds, per region pixel: R, G = the region's -//! bounding-box center (UV), B = a random id, A = 1. Gaps are all zero. Downstream nodes re-label -//! the index map (pixels of one region share the same RGB), so they recover the exact bounding -//! box, and a pixel's place inside it, at any size. Labeling wraps across the image edges when -//! the graph tiles, so a tile crossing an edge is one region. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::noise::{hash3, rand1}; - -const FLOOD: &str = "Filters/Flood fill"; -const NONE: u32 = u32::MAX; - -/// Connected regions of an image. -pub struct Regions { - /// Region index per pixel (`u32::MAX` = background). - pub label: Vec<u32>, - /// Unwrapped pixel coordinates (a region crossing an edge continues past it). - pub pos: Vec<[i32; 2]>, - /// Per region: min x, min y, max x, max y (unwrapped, inclusive). - pub bbox: Vec<[i32; 4]>, -} - -/// Label the 4-connected regions of pixels where `inside` holds and neighbours are `same`. -pub fn label(w: u32, h: u32, tile: bool, inside: impl Fn(usize) -> bool, same: impl Fn(usize, usize) -> bool) -> Regions { - let (wi, hi) = (w as i32, h as i32); - let n = w as usize * h as usize; - let mut label = vec![NONE; n]; - let mut pos = vec![[0i32; 2]; n]; - let mut bbox = Vec::new(); - let mut queue: Vec<usize> = Vec::new(); - for start in 0..n { - if label[start] != NONE || !inside(start) { - continue; - } - let id = bbox.len() as u32; - let s = [(start % w as usize) as i32, (start / w as usize) as i32]; - label[start] = id; - pos[start] = s; - let mut b = [s[0], s[1], s[0], s[1]]; - queue.clear(); - queue.push(start); - let mut head = 0; - while let Some(&i) = queue.get(head) { - head += 1; - let p = pos[i]; - for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { - let q = [p[0] + dx, p[1] + dy]; - let (x, y) = if tile { - (q[0].rem_euclid(wi), q[1].rem_euclid(hi)) - } else if (0..wi).contains(&q[0]) && (0..hi).contains(&q[1]) { - (q[0], q[1]) - } else { - continue; - }; - let j = (y * wi + x) as usize; - if label[j] != NONE || !inside(j) || !same(i, j) { - continue; - } - label[j] = id; - pos[j] = q; - b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])]; - queue.push(j); - } - } - bbox.push(b); - } - Regions { label, pos, bbox } -} - -/// What a downstream node knows about the region under a pixel. -pub struct RegionPx { - /// The region's random id (0..1). - pub id: f32, - /// Bounding-box center (UV, wrapped into 0..1). - pub center: [f32; 2], - /// Bounding-box size (UV). - pub size: [f32; 2], - /// The pixel's place inside the bounding box (0..1). - pub local: [f32; 2], -} - -/// Bounding-box center and size (UV) of a region. -fn bbox_uv(b: [i32; 4], w: u32, h: u32) -> ([f32; 2], [f32; 2]) { - let (wf, hf) = (w as f32, h as f32); - let (ex, ey) = ((b[2] - b[0] + 1) as f32, (b[3] - b[1] + 1) as f32); - let center = [((b[0] + b[2] + 1) as f32 * 0.5 / wf).rem_euclid(1.0), ((b[1] + b[3] + 1) as f32 * 0.5 / hf).rem_euclid(1.0)]; - (center, [(ex / wf).min(1.0), (ey / hf).min(1.0)]) -} - -/// A uniform random value per region (and per `k`), from the region's id and the node's seed. -pub fn region_rand(id: f32, k: u32, seed: u32) -> f32 { - rand1(id.to_bits() ^ k.wrapping_mul(0x9e37_79b9), seed) -} - -/// The index map input at the output size (nearest sampling keeps region values exact). -fn index_input(ctx: &Ctx, i: usize) -> Image { - match ctx.input(i) { - Some(img) => Image::generate_uv(ctx.w, ctx.h, Kind::Color, |u, v| img.sample_nearest(u, v, false)), - None => Image::filled(ctx.w, ctx.h, Kind::Color, [0.0; 4]), - } -} - -/// Run `f` for every region pixel of index map input `i`; background pixels get `bg`. -pub fn per_region(ctx: &Ctx, i: usize, kind: Kind, bg: [f32; 4], f: impl Fn(&RegionPx, f32, f32) -> [f32; 4] + Sync) -> Image { - let idx = index_input(ctx, i).to_color(); - let d = idx.data.as_slice(); - let px = |i: usize| d.get(i * 4..i * 4 + 4).unwrap_or(&[0.0; 4]); - let regions = label(ctx.w, ctx.h, ctx.tile, |i| px(i)[3] > 0.5, |a, b| px(a)[..3] == px(b)[..3]); - let (w, h) = (ctx.w, ctx.h); - Image::generate(w, h, kind, |x, y| { - let i = (y * w + x) as usize; - let Some(b) = regions.label.get(i).and_then(|l| regions.bbox.get(*l as usize)) else { - return bg; - }; - let (center, size) = bbox_uv(*b, w, h); - let p = regions.pos[i]; - let local = [(p[0] - b[0]) as f32 + 0.5, (p[1] - b[1]) as f32 + 0.5]; - let local = [local[0] / (b[2] - b[0] + 1) as f32, local[1] / (b[3] - b[1] + 1) as f32]; - let r = RegionPx { id: px(i)[2], center, size, local }; - f(&r, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32) - }) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let index_in = |id, label| node(id, label, FLOOD).color_in("input", "Index map"); - vec![ - node("flood_fill", "Flood Fill", FLOOD) - .desc("Finds every connected white region of a tile mask (regions crossing the edges are one) and writes an index map: R, G = region center, B = random id, A = 1.") - .gray_in("input", "Mask") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .output("output", "Index map", PortKind::Color) - .cook(flood_fill), - index_in("flood_fill_to_random_grayscale", "Flood Fill to Random Grayscale") - .desc("A random gray per region.") - .float("min", "Min", 0.0, 0.0, 1.0) - .float("max", "Max", 1.0, 0.0, 1.0) - .gray_out() - .cook(to_random_gray), - index_in("flood_fill_to_random_color", "Flood Fill to Random Color") - .desc("A random color per region.") - .float("saturation", "Saturation", 0.7, 0.0, 1.0) - .float("lightness", "Lightness", 0.5, 0.0, 1.0) - .float("lightness_random", "Lightness random", 0.3, 0.0, 1.0) - .color_out() - .cook(to_random_color), - index_in("flood_fill_to_gradient", "Flood Fill to Gradient") - .desc("A linear gradient across each region's bounding box.") - .angle("angle", "Angle", 0.0) - .float("angle_random", "Angle random", 0.0, 0.0, 1.0) - .float("slope_random", "Slope random", 0.0, 0.0, 1.0) - .gray_out() - .cook(to_gradient), - index_in("flood_fill_to_bbox_size", "Flood Fill to BBox Size") - .desc("Each region's bounding-box size.") - .choice("mode", "Size", &["Width", "Height", "Max", "Min", "Area"], 2) - .gray_out() - .cook(to_bbox_size), - index_in("flood_fill_to_position", "Flood Fill to Position") - .desc("Each region's center position (R = X, G = Y).") - .color_out() - .cook(to_position), - index_in("flood_fill_to_grayscale", "Flood Fill to Grayscale") - .desc("Each region takes the value of the input at its center.") - .gray_in("source", "Source") - .gray_out() - .cook(to_grayscale), - index_in("flood_fill_to_color", "Flood Fill to Color") - .desc("Each region takes the color of the input at its center.") - .color_in("source", "Source") - .color_out() - .cook(to_color), - ] -} - -fn flood_fill(ctx: &Ctx) -> CookResult { - let t = ctx.f("threshold"); - let m = ctx.gray_or(0, 0.0); - let d = m.data.as_slice(); - let regions = label(ctx.w, ctx.h, ctx.tile, |i| d.get(i).is_some_and(|v| *v > t), |_, _| true); - let (w, h, s) = (ctx.w, ctx.h, ctx.seed); - let info: Vec<[f32; 4]> = regions - .bbox - .iter() - .map(|b| { - let (c, size) = bbox_uv(*b, w, h); - // Stable per region: from its center and size, not its scan order. - let k = hash3((c[0] * 65536.0) as i32, (c[1] * 65536.0) as i32, s ^ (((size[0] * 4096.0) as u32) << 12) ^ ((size[1] * 4096.0) as u32)); - [c[0], c[1], ((k >> 8) as f32 / (1u32 << 24) as f32).max(1e-4), 1.0] - }) - .collect(); - Ok(vec![Image::generate(w, h, Kind::Color, |x, y| { - regions.label.get((y * w + x) as usize).and_then(|l| info.get(*l as usize)).copied().unwrap_or([0.0; 4]) - })]) -} - -fn to_random_gray(ctx: &Ctx) -> CookResult { - let (lo, hi, s) = (ctx.f("min"), ctx.f("max"), ctx.seed); - Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| [lo + (hi - lo) * region_rand(r.id, 0, s), 0.0, 0.0, 0.0])]) -} - -fn to_random_color(ctx: &Ctx) -> CookResult { - let (sat, l, lr, s) = (ctx.f("saturation"), ctx.f("lightness"), ctx.f("lightness_random"), ctx.seed); - Ok(vec![per_region(ctx, 0, Kind::Color, [0.0, 0.0, 0.0, 1.0], |r, _, _| { - let light = (l + (region_rand(r.id, 2, s) - 0.5) * lr).clamp(0.0, 1.0); - let c = crate::ops::hsl_to_rgb(region_rand(r.id, 1, s), sat, light); - [c[0], c[1], c[2], 1.0] - })]) -} - -fn to_gradient(ctx: &Ctx) -> CookResult { - let (a, ar, sr, s) = (ctx.f("angle"), ctx.f("angle_random"), ctx.f("slope_random"), ctx.seed); - Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| { - let (sn, cs) = ((a + (region_rand(r.id, 3, s) - 0.5) * ar) * TAU).sin_cos(); - // Projection onto the direction, normalized so the gradient spans 0..1 over the box. - let (x, y) = (r.local[0] - 0.5, r.local[1] - 0.5); - let t = 0.5 + (x * cs + y * sn) / (cs.abs() + sn.abs()).max(1e-6); - let slope = 1.0 - sr * region_rand(r.id, 4, s); - [(t * slope).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn to_bbox_size(ctx: &Ctx) -> CookResult { - let mode = ctx.i("mode"); - Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| { - let [w, h] = r.size; - let v = match mode { - 0 => w, - 1 => h, - 3 => w.min(h), - 4 => w * h, - _ => w.max(h), - }; - [v, 0.0, 0.0, 0.0] - })]) -} - -fn to_position(ctx: &Ctx) -> CookResult { - Ok(vec![per_region(ctx, 0, Kind::Color, [0.0, 0.0, 0.0, 1.0], |r, _, _| [r.center[0], r.center[1], 0.0, 1.0])]) -} - -fn sample_at_center(ctx: &Ctx, kind: Kind) -> Image { - let src = ctx.input(1).map(|i| i.to_kind(kind)); - let tile = ctx.tile; - per_region(ctx, 0, kind, [0.0, 0.0, 0.0, 1.0], |r, _, _| src.as_ref().map_or([1.0; 4], |img| img.sample(r.center[0], r.center[1], tile))) -} - -fn to_grayscale(ctx: &Ctx) -> CookResult { - Ok(vec![sample_at_center(ctx, Kind::Gray)]) -} - -fn to_color(ctx: &Ctx) -> CookResult { - Ok(vec![sample_at_center(ctx, Kind::Color)]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use super::*; - use crate::{find, resolve_params}; - - fn cook(id: &str, inputs: &[Option<Image>], w: u32) -> Vec<Image> { - let def = find(id).unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w, h: w, seed: 3, tile: true, inputs, params: ¶ms, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap() - } - - #[test] - fn separate_squares_differ_and_edge_square_wraps() { - // Square A at 2..6, square B at 10..14, square C straddling the right edge (x 14..16 and 0..1) - // in rows 10..13. - let mask = Image::gray(16, 16, |x, y| { - let a = (2..6).contains(&x) && (2..6).contains(&y); - let b = (9..13).contains(&x) && (2..6).contains(&y); - let c = !(1..14).contains(&x) && (10..13).contains(&y); - (a || b || c) as i32 as f32 - }); - let idx = &cook("flood_fill", &[Some(mask)], 16)[0]; - let (a, b) = (idx.get(3, 3, false), idx.get(10, 3, false)); - assert_eq!(a[3], 1.0); - assert_ne!(a[2], b[2], "separate squares get different ids"); - assert_eq!(idx.get(0, 0, false), [0.0; 4], "gaps stay empty"); - let (l, r) = (idx.get(0, 11, false), idx.get(15, 11, false)); - assert_eq!(l, r, "a square across the edge is one region"); - // Pixels 14, 15 and 0 (wrapped to 16): the box middle is 15.5 px. - assert!((l[0] - 15.5 / 16.0).abs() < 1e-5, "{l:?}"); - let gray = &cook("flood_fill_to_random_grayscale", &[Some(idx.clone())], 16)[0]; - assert_eq!(gray.get(0, 11, false), gray.get(15, 11, false)); - assert_ne!(gray.get(3, 3, false), gray.get(10, 3, false)); - let size = &cook("flood_fill_to_bbox_size", &[Some(idx.clone())], 16)[0]; - assert!((size.get(15, 11, false)[0] - 3.0 / 16.0).abs() < 1e-5); - let grad = &cook("flood_fill_to_gradient", &[Some(idx.clone())], 16)[0]; - assert!(grad.get(2, 3, false)[0] < grad.get(5, 3, false)[0]); - assert!(grad.get(14, 11, false)[0] < grad.get(0, 11, false)[0], "the gradient continues across the edge"); - } -} diff --git a/crates/nodes/src/function.rs b/crates/nodes/src/function.rs deleted file mode 100644 index 55888c15..00000000 --- a/crates/nodes/src/function.rs +++ /dev/null @@ -1,395 +0,0 @@ -//! Function graph evaluation: a [`FnGraph`] is compiled once into a flat instruction list -//! (dependency order from the output node), then run per pixel with a small register file. All -//! values are 4-wide; scalars are broadcast to every lane, so component-wise ops need no type -//! checks. The pixel processor samples its inputs at any position; the value processor runs once. - -use std::collections::BTreeMap; - -use materialcraft_core::Value; -use materialcraft_core::function::FnGraph; -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx}; -use crate::noise; - -/// Function node operations: (id, label, input count, library category). -pub const FN_OPS: &[(&str, &str, usize, &str)] = &[ - ("const_float", "Float", 0, "Constant"), - ("const_float2", "Float2", 0, "Constant"), - ("const_float3", "Float3", 0, "Constant"), - ("const_float4", "Float4", 0, "Constant"), - ("const_int", "Integer", 0, "Constant"), - ("const_bool", "Boolean", 0, "Constant"), - ("get_pos", "$pos", 0, "Variables"), - ("get_size", "$size", 0, "Variables"), - ("get_var", "Get variable", 0, "Variables"), - ("sample_gray", "Sample Gray", 1, "Samplers"), - ("sample_color", "Sample Color", 1, "Samplers"), - ("vec2", "Vector Float2", 2, "Vector"), - ("vec3", "Vector Float3", 3, "Vector"), - ("vec4", "Vector Float4", 4, "Vector"), - ("swizzle", "Swizzle", 1, "Vector"), - ("to_int", "To Integer", 1, "Cast"), - ("to_float", "To Float", 1, "Cast"), - ("add", "Add", 2, "Operator"), - ("sub", "Subtraction", 2, "Operator"), - ("mul", "Multiplication", 2, "Operator"), - ("div", "Division", 2, "Operator"), - ("mod", "Modulo", 2, "Operator"), - ("neg", "Negation", 1, "Operator"), - ("dot", "Dot Product", 2, "Operator"), - ("and", "And", 2, "Logical"), - ("or", "Or", 2, "Logical"), - ("not", "Not", 1, "Logical"), - ("gt", "Greater", 2, "Comparison"), - ("ge", "Greater or equal", 2, "Comparison"), - ("lt", "Lower", 2, "Comparison"), - ("le", "Lower or equal", 2, "Comparison"), - ("eq", "Equal", 2, "Comparison"), - ("ne", "Not equal", 2, "Comparison"), - ("abs", "Absolute", 1, "Function"), - ("floor", "Floor", 1, "Function"), - ("ceil", "Ceil", 1, "Function"), - ("frac", "Fractional part", 1, "Function"), - ("sqrt", "Square root", 1, "Function"), - ("exp", "Exponential", 1, "Function"), - ("log", "Logarithm", 1, "Function"), - ("sin", "Sine", 1, "Function"), - ("cos", "Cosine", 1, "Function"), - ("tan", "Tangent", 1, "Function"), - ("atan2", "Arc tangent 2", 2, "Function"), - ("pow", "Power", 2, "Function"), - ("min", "Minimum", 2, "Function"), - ("max", "Maximum", 2, "Function"), - ("clamp", "Clamp", 3, "Function"), - ("lerp", "Linear interpolation", 3, "Function"), - ("length", "Length", 1, "Function"), - ("normalize", "Normalize", 1, "Function"), - ("rand", "Random", 1, "Function"), - ("noise", "Perlin noise", 1, "Function"), - ("if_else", "If...Else", 3, "Control"), -]; - -#[derive(Clone, Debug)] -enum Op { - Const([f32; 4]), - Pos, - Size, - Sample { input: usize, gray: bool }, - Unary(fn(f32) -> f32), - Binary(fn(f32, f32) -> f32), - Ternary(fn(f32, f32, f32) -> f32), - Dot, - Length, - Normalize, - Vec(usize), - Swizzle([usize; 4]), - Rand, - Noise, - IfElse, -} - -#[derive(Clone, Debug)] -struct Instr { - op: Op, - args: Vec<usize>, - /// Lanes that carry meaning (1 = scalar). - dims: usize, -} - -/// A compiled function graph. -#[derive(Clone, Debug)] -pub struct Program { - code: Vec<Instr>, - seed: u32, -} - -fn b(v: bool) -> f32 { - if v { 1.0 } else { 0.0 } -} - -fn dims_of(v: &Value) -> usize { - match v { - Value::Float2(_) | Value::Int2(_) => 2, - Value::Float3(_) => 3, - Value::Float4(_) | Value::Color(_) => 4, - _ => 1, - } -} - -fn broadcast(v: &Value) -> [f32; 4] { - match dims_of(v) { - 1 => [v.as_f32().unwrap_or(0.0); 4], - _ => v.as_vec4().unwrap_or([0.0; 4]), - } -} - -/// Compile `g` for evaluation. `vars` resolves `get_var` names (exposed graph inputs). -pub fn compile(g: &FnGraph, vars: &BTreeMap<String, Value>, seed: u32) -> Result<Program, String> { - let out = g.output.ok_or("the function has no output node")?; - let mut code: Vec<Instr> = Vec::new(); - let mut reg: BTreeMap<u32, usize> = BTreeMap::new(); - // Iterative post-order from the output; a node seen twice on the current path is a cycle. - let mut stack: Vec<(u32, bool)> = vec![(out, false)]; - let mut on_path = std::collections::BTreeSet::new(); - while let Some((id, done)) = stack.pop() { - if reg.contains_key(&id) { - continue; - } - let n = g.node(id).ok_or_else(|| format!("missing function node {id}"))?; - if !done { - if !on_path.insert(id) { - return Err("the function graph has a cycle".into()); - } - stack.push((id, true)); - for i in n.inputs.iter().flatten() { - if !reg.contains_key(i) { - stack.push((*i, false)); - } - } - continue; - } - on_path.remove(&id); - if code.len() > 4096 { - return Err("the function graph is too large".into()); - } - let args: Vec<usize> = n.inputs.iter().map(|i| i.and_then(|i| reg.get(&i).copied())).map(|r| r.unwrap_or(usize::MAX)).collect(); - let arity = FN_OPS.iter().find(|o| o.0 == n.op).map(|o| o.2).ok_or_else(|| format!("unknown function op `{}`", n.op))?; - if args.len() < arity || args.iter().take(arity).any(|a| *a == usize::MAX) { - return Err(format!("`{}` needs {arity} connected input(s)", n.op)); - } - let dim = |k: usize| args.get(k).and_then(|r| code.get(*r)).map_or(1, |i: &Instr| i.dims); - let maxd = (0..arity).map(dim).max().unwrap_or(1); - let (op, dims) = match n.op.as_str() { - o if o.starts_with("const_") => { - let v = n.value.clone().unwrap_or(Value::Float(0.0)); - (Op::Const(broadcast(&v)), dims_of(&v)) - } - "get_pos" => (Op::Pos, 2), - "get_size" => (Op::Size, 2), - "get_var" => { - let name = match &n.value { - Some(Value::Text(s)) => s.as_str(), - _ => "", - }; - let v = vars.get(name).cloned().unwrap_or(Value::Float(0.0)); - (Op::Const(broadcast(&v)), dims_of(&v)) - } - "sample_gray" | "sample_color" => { - let input = n.value.as_ref().and_then(Value::as_i32).unwrap_or(0).clamp(0, 3) as usize; - let gray = n.op == "sample_gray"; - (Op::Sample { input, gray }, if gray { 1 } else { 4 }) - } - "vec2" => (Op::Vec(2), 2), - "vec3" => (Op::Vec(3), 3), - "vec4" => (Op::Vec(4), 4), - "swizzle" => { - let s = match &n.value { - Some(Value::Text(s)) => s.clone(), - _ => "x".into(), - }; - let mut idx = [0usize; 4]; - let mut len = 0; - for (k, ch) in s.chars().take(4).enumerate() { - idx[k] = match ch { - 'y' | 'g' => 1, - 'z' | 'b' => 2, - 'w' | 'a' => 3, - _ => 0, - }; - len = k + 1; - } - if len == 1 { - idx = [idx[0]; 4]; - } - (Op::Swizzle(idx), len.max(1)) - } - "to_int" | "floor" => (Op::Unary(f32::floor), maxd), - "to_float" => (Op::Unary(|a| a), maxd), - "add" => (Op::Binary(|a, b| a + b), maxd), - "sub" => (Op::Binary(|a, b| a - b), maxd), - "mul" => (Op::Binary(|a, b| a * b), maxd), - "div" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a / b }), maxd), - "mod" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a.rem_euclid(b) }), maxd), - "neg" => (Op::Unary(|a| -a), maxd), - "dot" => (Op::Dot, 1), - "and" => (Op::Binary(|a, x| b(a != 0.0 && x != 0.0)), maxd), - "or" => (Op::Binary(|a, x| b(a != 0.0 || x != 0.0)), maxd), - "not" => (Op::Unary(|a| b(a == 0.0)), maxd), - "gt" => (Op::Binary(|a, x| b(a > x)), maxd), - "ge" => (Op::Binary(|a, x| b(a >= x)), maxd), - "lt" => (Op::Binary(|a, x| b(a < x)), maxd), - "le" => (Op::Binary(|a, x| b(a <= x)), maxd), - "eq" => (Op::Binary(|a, x| b(a == x)), maxd), - "ne" => (Op::Binary(|a, x| b(a != x)), maxd), - "abs" => (Op::Unary(f32::abs), maxd), - "ceil" => (Op::Unary(f32::ceil), maxd), - "frac" => (Op::Unary(|a| a - a.floor()), maxd), - "sqrt" => (Op::Unary(|a| a.max(0.0).sqrt()), maxd), - "exp" => (Op::Unary(f32::exp), maxd), - "log" => (Op::Unary(|a| if a > 0.0 { a.ln() } else { 0.0 }), maxd), - "sin" => (Op::Unary(f32::sin), maxd), - "cos" => (Op::Unary(f32::cos), maxd), - "tan" => (Op::Unary(f32::tan), maxd), - "atan2" => (Op::Binary(f32::atan2), maxd), - "pow" => (Op::Binary(|a, x| if a < 0.0 && x.fract() != 0.0 { 0.0 } else { a.powf(x) }), maxd), - "min" => (Op::Binary(f32::min), maxd), - "max" => (Op::Binary(f32::max), maxd), - "clamp" => (Op::Ternary(|a, lo, hi| a.max(lo).min(hi.max(lo))), maxd), - "lerp" => (Op::Ternary(|a, x, t| a + (x - a) * t), maxd.max(dim(0)).max(dim(1))), - "length" => (Op::Length, 1), - "normalize" => (Op::Normalize, dim(0)), - "rand" => (Op::Rand, dim(0)), - "noise" => (Op::Noise, 1), - "if_else" => (Op::IfElse, dim(1).max(dim(2))), - other => return Err(format!("unknown function op `{other}`")), - }; - reg.insert(id, code.len()); - code.push(Instr { op, args: args.into_iter().take(arity).collect(), dims }); - } - Ok(Program { code, seed }) -} - -impl Program { - /// Lanes of the result. - pub fn dims(&self) -> usize { - self.code.last().map_or(1, |i| i.dims) - } - - /// Run at normalized position `pos` of an image of `size`, sampling `inputs`. - pub fn eval(&self, pos: [f32; 2], size: [f32; 2], inputs: &[Option<Image>], tile: bool, regs: &mut Vec<[f32; 4]>) -> [f32; 4] { - regs.clear(); - for ins in &self.code { - let a = |k: usize| ins.args.get(k).and_then(|r| regs.get(*r)).copied().unwrap_or([0.0; 4]); - let v = match &ins.op { - Op::Const(c) => *c, - Op::Pos => [pos[0], pos[1], 0.0, 0.0], - Op::Size => [size[0], size[1], 0.0, 0.0], - Op::Sample { input, gray } => { - let p = a(0); - match inputs.get(*input).and_then(Option::as_ref) { - Some(img) if *gray => [img.sample_gray(p[0], p[1], tile); 4], - Some(img) => img.sample(p[0], p[1], tile), - None => [0.0, 0.0, 0.0, 1.0], - } - } - Op::Unary(f) => a(0).map(f), - Op::Binary(f) => { - let (x, y) = (a(0), a(1)); - [f(x[0], y[0]), f(x[1], y[1]), f(x[2], y[2]), f(x[3], y[3])] - } - Op::Ternary(f) => { - let (x, y, z) = (a(0), a(1), a(2)); - [f(x[0], y[0], z[0]), f(x[1], y[1], z[1]), f(x[2], y[2], z[2]), f(x[3], y[3], z[3])] - } - Op::Dot => { - let (x, y) = (a(0), a(1)); - let n = ins.args.iter().filter_map(|r| self.code.get(*r)).map(|i| i.dims).max().unwrap_or(1); - [(0..n).map(|k| x[k] * y[k]).sum(); 4] - } - Op::Length => { - let x = a(0); - let n = ins.args.first().and_then(|r| self.code.get(*r)).map_or(1, |i| i.dims); - [(0..n).map(|k| x[k] * x[k]).sum::<f32>().sqrt(); 4] - } - Op::Normalize => { - let x = a(0); - let l = (0..ins.dims).map(|k| x[k] * x[k]).sum::<f32>().sqrt(); - if l > 0.0 { x.map(|c| c / l) } else { x } - } - Op::Vec(n) => { - let mut o = [0.0; 4]; - for k in 0..*n { - o[k] = a(k)[0]; - } - o - } - Op::Swizzle(idx) => { - let x = a(0); - idx.map(|i| x[i]) - } - Op::Rand => a(0).map(|c| noise::rand1(c.to_bits(), self.seed)), - Op::Noise => { - let p = a(0); - [noise::perlin(p[0], p[1], 0, self.seed) * 0.5 + 0.5; 4] - } - Op::IfElse => { - if a(0)[0] != 0.0 { - a(1) - } else { - a(2) - } - } - }; - regs.push(v); - } - regs.last().copied().unwrap_or([0.0; 4]) - } -} - -/// The default pixel processor function: the first input, unchanged. -pub fn default_pixel_function() -> FnGraph { - let mut g = FnGraph::default(); - let pos = g.add("get_pos", &[], None); - let s = g.add("sample_color", &[pos], Some(Value::Int(0))); - g.output = Some(s); - g -} - -pub(crate) fn pixel_processor(ctx: &Ctx) -> CookResult { - let f = ctx.function("function").ok_or("no function")?; - let prog = compile(f, ctx.vars, ctx.seed)?; - let gray = ctx.i("output") == 1; - let dims = prog.dims(); - let size = [ctx.w as f32, ctx.h as f32]; - let kind = if gray { Kind::Gray } else { Kind::Color }; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, kind, |u, v| { - // shortcut: one register file per pixel; a thread-local would save the allocation. - let mut regs = Vec::with_capacity(prog.code.len()); - let r = prog.eval([u, v], size, ctx.inputs, ctx.tile, &mut regs); - match (gray, dims) { - (true, _) => [r[0], 0.0, 0.0, 0.0], - (false, 1) => [r[0], r[0], r[0], 1.0], - (false, 2) => [r[0], r[1], 0.0, 1.0], - (false, 3) => [r[0], r[1], r[2], 1.0], - _ => r, - } - })]) -} - -pub(crate) fn value_processor(ctx: &Ctx) -> CookResult { - let f = ctx.function("function").ok_or("no function")?; - let prog = compile(f, ctx.vars, ctx.seed)?; - let r = prog.eval([0.5, 0.5], [ctx.w as f32, ctx.h as f32], ctx.inputs, ctx.tile, &mut Vec::new()); - Ok(vec![if prog.dims() == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [r[0]; 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, r) }]) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compiles_and_runs_arithmetic() { - let mut g = FnGraph::default(); - let pos = g.add("get_pos", &[], None); - let x = g.add("swizzle", &[pos], Some(Value::Text("x".into()))); - let two = g.add("const_float", &[], Some(Value::Float(2.0))); - let m = g.add("mul", &[x, two], None); - g.output = Some(m); - let p = compile(&g, &BTreeMap::new(), 0).unwrap(); - assert_eq!(p.dims(), 1); - let r = p.eval([0.25, 0.5], [8.0, 8.0], &[], true, &mut Vec::new()); - assert_eq!(r[0], 0.5); - } - - #[test] - fn rejects_bad_graphs() { - let mut g = FnGraph::default(); - let a = g.add("add", &[], None); - g.output = Some(a); - assert!(compile(&g, &BTreeMap::new(), 0).is_err()); - g.nodes[0].inputs = vec![Some(a), Some(a)]; - assert!(compile(&g, &BTreeMap::new(), 0).is_err()); - assert!(compile(&FnGraph::default(), &BTreeMap::new(), 0).is_err()); - } -} diff --git a/crates/nodes/src/function/arithmetic.rs b/crates/nodes/src/function/arithmetic.rs new file mode 100644 index 00000000..e0671430 --- /dev/null +++ b/crates/nodes/src/function/arithmetic.rs @@ -0,0 +1,94 @@ +use super::value_type::{dimensions, float_value, floats, integer_value, integers}; +use materialcraft_core::Value; + +pub(crate) fn evaluate(op: &str, args: &[Value], random: &mut u32) -> Result<Value, String> { + let first = args.first().ok_or("missing arithmetic operand")?; + let count = dimensions(first); + let integer = matches!(first, Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_)); + if integer { + let left = integers(first)?; + let right = args.get(1).map(integers).transpose()?.unwrap_or([0; 4]); + if args.get(1).is_some_and(|value| dimensions(value) != count) { + return Err("integer operands must have the same dimensions".into()); + } + + let mut result = [0; 4]; + for ((result, left), right) in result.iter_mut().zip(left).zip(right).take(count) { + *result = match op { + "add" => left.checked_add(right), + "sub" => left.checked_sub(right), + "mul" => left.checked_mul(right), + "div" => left.checked_div(right), + "mod" => left.checked_rem(right), + "neg" => left.checked_neg(), + "abs" => left.checked_abs(), + "min" => Some(left.min(right)), + "max" => Some(left.max(right)), + _ => return Err(format!("{op} requires floating-point operands")), + } + .ok_or_else(|| format!("{op}: integer overflow or division by zero"))?; + } + + return integer_value(result.get(..count).ok_or("invalid integer dimensions")?); + } + + let left = floats(first)?; + let right = args.get(1).map(floats).transpose()?.unwrap_or([0.0; 4]); + let factor = args.get(2).map(floats).transpose()?.unwrap_or([0.0; 4]); + if args.get(1).is_some_and(|value| dimensions(value) != count && !(op == "mulscalar" && dimensions(value) == 1)) { + return Err("float operands must have the same dimensions".into()); + } + if args.get(2).is_some_and(|value| dimensions(value) != count && dimensions(value) != 1) { + return Err("interpolation factor must be a scalar or match its operands".into()); + } + + if op == "dot" { + return float_value(&[left.iter().zip(right).take(count).map(|(a, b)| a * b).sum()]); + } + if op == "atan2" { + if count != 2 { + return Err("arc tangent requires a float2".into()); + } + return float_value(&[left[1].atan2(left[0])]); + } + if op == "cartesian" { + if count != 1 { + return Err("Cartesian requires scalar radius and angle".into()); + } + return float_value(&[left[0] * right[0].cos(), left[0] * right[0].sin()]); + } + + let mut result = [0.0; 4]; + for (((result, left), right), factor) in result.iter_mut().zip(left).zip(right).zip(factor).take(count) { + *result = match op { + "add" => left + right, + "sub" => left - right, + "mul" | "mulscalar" => left * right, + "div" => left / right, + "mod" => left % right, + "neg" => -left, + "abs" => left.abs(), + "min" => left.min(right), + "max" => left.max(right), + "floor" => left.floor(), + "ceil" => left.ceil(), + "sqrt" => left.sqrt(), + "exp" => left.exp(), + "log" => left.ln(), + "log2" => left.log2(), + "pow" => left.powf(right), + "pow2" => left.exp2(), + "sin" => left.sin(), + "cos" => left.cos(), + "tan" => left.tan(), + "lerp" => left + (right - left) * factor, + "rand" => { + *random = crate::random::hash(random.wrapping_add(1)); + (*random >> 8) as f32 / 16777216.0 * left + } + _ => return Err(format!("unknown arithmetic operation `{op}`")), + }; + } + + float_value(result.get(..count).ok_or("invalid float dimensions")?) +} diff --git a/crates/nodes/src/function/catalog.rs b/crates/nodes/src/function/catalog.rs new file mode 100644 index 00000000..d8f0dacf --- /dev/null +++ b/crates/nodes/src/function/catalog.rs @@ -0,0 +1,120 @@ +use super::FunctionDefinition; +use materialcraft_core::Value; + +pub const FUNCTIONS: &[FunctionDefinition] = &[ + FunctionDefinition { id: "const_bool", label: "Boolean", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_bool", label: "Get Boolean", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_float1", label: "Float", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_float1", label: "Get Float", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_float2", label: "Float2", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_float2", label: "Get Float2", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_float3", label: "Float3", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_float3", label: "Get Float3", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_float4", label: "Float4", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_float4", label: "Get Float4", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_int1", label: "Integer", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_integer1", label: "Get Integer", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_int2", label: "Integer2", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_integer2", label: "Get Integer2", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_int3", label: "Integer3", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_integer3", label: "Get Integer3", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_int4", label: "Integer4", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_integer4", label: "Get Integer4", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "const_string", label: "String", inputs: &[], category: "Constant" }, + FunctionDefinition { id: "get_string", label: "Get String", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "add", label: "Add", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "sub", label: "Subtract", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "mul", label: "Multiply", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "div", label: "Divide", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "mod", label: "Modulo", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "neg", label: "Negate", inputs: &["a"], category: "Operator" }, + FunctionDefinition { id: "mulscalar", label: "Multiply by scalar", inputs: &["a", "scalar"], category: "Operator" }, + FunctionDefinition { id: "dot", label: "Dot product", inputs: &["a", "b"], category: "Operator" }, + FunctionDefinition { id: "and", label: "And", inputs: &["a", "b"], category: "Logical" }, + FunctionDefinition { id: "or", label: "Or", inputs: &["a", "b"], category: "Logical" }, + FunctionDefinition { id: "not", label: "Not", inputs: &["a"], category: "Logical" }, + FunctionDefinition { id: "eq", label: "Equal", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "noteq", label: "Not equal", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "gt", label: "Greater", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "gteq", label: "Greater or equal", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "lr", label: "Less", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "lreq", label: "Less or equal", inputs: &["a", "b"], category: "Comparison" }, + FunctionDefinition { id: "abs", label: "Absolute", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "floor", label: "Floor", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "ceil", label: "Ceiling", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "sqrt", label: "Square root", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "exp", label: "Exponential", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "log", label: "Natural logarithm", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "log2", label: "Logarithm base 2", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "pow2", label: "Power of 2", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "sin", label: "Sine", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "cos", label: "Cosine", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "tan", label: "Tangent", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "atan2", label: "Arc tangent", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "rand", label: "Random", inputs: &["a"], category: "Function" }, + FunctionDefinition { id: "min", label: "Minimum", inputs: &["a", "b"], category: "Function" }, + FunctionDefinition { id: "max", label: "Maximum", inputs: &["a", "b"], category: "Function" }, + FunctionDefinition { id: "pow", label: "Power", inputs: &["a", "b"], category: "Function" }, + FunctionDefinition { id: "lerp", label: "Linear interpolation", inputs: &["a", "b", "x"], category: "Function" }, + FunctionDefinition { id: "cartesian", label: "Cartesian", inputs: &["rho", "theta"], category: "Function" }, + FunctionDefinition { id: "vector2", label: "Float vector 2", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "vector3", label: "Float vector 3", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "vector4", label: "Float vector 4", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "swizzle1", label: "Float swizzle 1", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "swizzle2", label: "Float swizzle 2", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "swizzle3", label: "Float swizzle 3", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "swizzle4", label: "Float swizzle 4", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "ivector2", label: "Integer vector 2", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "ivector3", label: "Integer vector 3", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "ivector4", label: "Integer vector 4", inputs: &["componentsin", "componentslast"], category: "Vector" }, + FunctionDefinition { id: "iswizzle1", label: "Integer swizzle 1", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "iswizzle2", label: "Integer swizzle 2", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "iswizzle3", label: "Integer swizzle 3", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "iswizzle4", label: "Integer swizzle 4", inputs: &["vector"], category: "Vector" }, + FunctionDefinition { id: "tofloat", label: "To Float1", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint1", label: "To Integer1", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "tofloat2", label: "To Float2", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint2", label: "To Integer2", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "tofloat3", label: "To Float3", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint3", label: "To Integer3", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "tofloat4", label: "To Float4", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "toint4", label: "To Integer4", inputs: &["value"], category: "Cast" }, + FunctionDefinition { id: "samplecol", label: "Sample color", inputs: &["pos"], category: "Samplers" }, + FunctionDefinition { id: "samplelum", label: "Sample grayscale", inputs: &["pos"], category: "Samplers" }, + FunctionDefinition { id: "set", label: "Set variable", inputs: &["value"], category: "Variables" }, + FunctionDefinition { id: "isdefined", label: "Is defined", inputs: &[], category: "Variables" }, + FunctionDefinition { id: "ifelse", label: "If…Else", inputs: &["condition", "ifpath", "elsepath"], category: "Control" }, + FunctionDefinition { id: "sequence", label: "Sequence", inputs: &["seqin", "seqlast"], category: "Control" }, + FunctionDefinition { id: "while", label: "While loop", inputs: &["init", "cond", "loop"], category: "Control" }, + FunctionDefinition { id: "passthrough", label: "Dot", inputs: &["input"], category: "Control" }, +]; + +pub fn definition(id: &str) -> Option<&'static FunctionDefinition> { + FUNCTIONS.iter().find(|definition| definition.id == id) +} + +pub fn default_value(id: &str) -> Option<Value> { + if id.starts_with("get_") || matches!(id, "set" | "isdefined") { + return Some(Value::Text(String::new())); + } + + Some(match id { + "const_bool" => Value::Bool(false), + "const_float1" => Value::Float(0.5), + "const_float2" => Value::Float2([0.0; 2]), + "const_float3" => Value::Float3([0.0; 3]), + "const_float4" => Value::Float4([0.0, 0.0, 0.0, 1.0]), + "const_int1" => Value::Int(0), + "const_int2" => Value::Int2([0; 2]), + "const_int3" => Value::Int3([0; 3]), + "const_int4" => Value::Int4([0; 4]), + "const_string" => Value::Text(String::new()), + "swizzle1" | "iswizzle1" => Value::Int(0), + "swizzle2" | "iswizzle2" => Value::Int2([0, 1]), + "swizzle3" | "iswizzle3" => Value::Int3([0, 1, 2]), + "swizzle4" | "iswizzle4" => Value::Int4([0, 1, 2, 3]), + "samplecol" | "samplelum" => Value::Int2([0, 1]), + "while" => Value::Int(100), + _ => return None, + }) +} diff --git a/crates/nodes/src/function/compile.rs b/crates/nodes/src/function/compile.rs new file mode 100644 index 00000000..089b0667 --- /dev/null +++ b/crates/nodes/src/function/compile.rs @@ -0,0 +1,59 @@ +use super::{Program, catalog, instruction::Instruction}; +use materialcraft_core::FunctionGraph; +use std::collections::{BTreeMap, BTreeSet}; + +pub fn compile(graph: &FunctionGraph, seed: u32) -> Result<Program, String> { + if graph.nodes.len() > 4096 { + return Err("function exceeds the 4096-node execution limit".into()); + } + + let output = graph.output.ok_or("function has no result node")?; + let mut nodes = BTreeMap::new(); + for node in &graph.nodes { + if nodes.insert(node.id, node).is_some() { + return Err(format!("duplicate function node {}", node.id)); + } + } + + let mut pending = vec![(output, false)]; + let mut active = BTreeSet::new(); + let mut indices = BTreeMap::new(); + let mut instructions: Vec<Instruction> = Vec::new(); + while let Some((id, visited)) = pending.pop() { + if indices.contains_key(&id) { + continue; + } + + let node = nodes.get(&id).ok_or_else(|| format!("missing function node {id}"))?; + let definition = catalog::definition(&node.op).ok_or_else(|| format!("unknown function `{}`", node.op))?; + if node.inputs.len() != definition.inputs.len() || node.inputs.iter().any(Option::is_none) { + return Err(format!("{} ({id}) requires connected inputs: {}", definition.label, definition.inputs.join(", "))); + } + + if !visited { + if !active.insert(id) { + return Err(format!("function cycle at node {id}")); + } + + pending.push((id, true)); + pending.extend(node.inputs.iter().rev().flatten().map(|input| (*input, false))); + continue; + } + + active.remove(&id); + let inputs: Vec<usize> = + node.inputs.iter().flatten().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::<Result<_, _>>()?; + let value = node.value.clone().or_else(|| catalog::default_value(&node.op)); + let input_type = |index: usize| inputs.get(index).and_then(|index| instructions.get(*index)).map_or(256, |instruction| instruction.type_code); + let inferred = super::inferred_type::inferred_type(&node.op, value.as_ref(), input_type); + let type_code = if node.type_code == 0 { inferred } else { node.type_code }; + let pure = !matches!(node.op.as_str(), "set" | "sequence" | "while" | "rand" | "isdefined") + && !node.op.starts_with("get_") + && inputs.iter().all(|index| instructions.get(*index).is_some_and(|instruction| instruction.pure)); + indices.insert(id, instructions.len()); + instructions.push(Instruction { id, definition, inputs, value, type_code, pure }); + } + + let output = indices.get(&output).copied().ok_or("missing result instruction")?; + Ok(Program { instructions, output, seed }) +} diff --git a/crates/nodes/src/function/evaluation_context.rs b/crates/nodes/src/function/evaluation_context.rs new file mode 100644 index 00000000..94a2c5c1 --- /dev/null +++ b/crates/nodes/src/function/evaluation_context.rs @@ -0,0 +1,12 @@ +use materialcraft_core::Value; +use materialcraft_image::Image; +use std::collections::BTreeMap; + +/// Inputs shared by one function evaluation +pub struct EvaluationContext<'a> { + pub position: [f32; 2], + pub size: [f32; 2], + pub images: &'a [Option<Image>], + pub tile: bool, + pub variables: &'a BTreeMap<String, Value>, +} diff --git a/crates/nodes/src/function/evaluation_state.rs b/crates/nodes/src/function/evaluation_state.rs new file mode 100644 index 00000000..c2573bca --- /dev/null +++ b/crates/nodes/src/function/evaluation_state.rs @@ -0,0 +1,19 @@ +use super::evaluation_step::EvaluationStep; +use materialcraft_core::Value; +use std::collections::BTreeMap; + +/// Reusable execution storage for one worker +#[derive(Default)] +pub struct EvaluationState { + pub(crate) steps: Vec<EvaluationStep>, + pub(crate) values: Vec<Value>, + pub(crate) registers: Vec<Option<Value>>, + pub(crate) variables: BTreeMap<String, Value>, + pub(crate) random: u32, +} + +impl EvaluationState { + pub fn variables(&self) -> &BTreeMap<String, Value> { + &self.variables + } +} diff --git a/crates/nodes/src/function/evaluation_step.rs b/crates/nodes/src/function/evaluation_step.rs new file mode 100644 index 00000000..dd982387 --- /dev/null +++ b/crates/nodes/src/function/evaluation_step.rs @@ -0,0 +1,11 @@ +use materialcraft_core::Value; + +pub(crate) enum EvaluationStep { + Enter(usize), + Apply { instruction: usize, base: usize }, + Branch(usize), + Sequence(usize), + LoopStart(usize), + LoopCondition { instruction: usize, iteration: u32, last: Value }, + LoopBody { instruction: usize, iteration: u32 }, +} diff --git a/crates/nodes/src/function/function_definition.rs b/crates/nodes/src/function/function_definition.rs new file mode 100644 index 00000000..3cecc04f --- /dev/null +++ b/crates/nodes/src/function/function_definition.rs @@ -0,0 +1,8 @@ +/// One native function primitive and its ordered input connectors +#[derive(Clone, Copy, Debug)] +pub struct FunctionDefinition { + pub id: &'static str, + pub label: &'static str, + pub inputs: &'static [&'static str], + pub category: &'static str, +} diff --git a/crates/nodes/src/function/inferred_type.rs b/crates/nodes/src/function/inferred_type.rs new file mode 100644 index 00000000..71e3994b --- /dev/null +++ b/crates/nodes/src/function/inferred_type.rs @@ -0,0 +1,21 @@ +use super::value_type; +use materialcraft_core::Value; + +pub(super) fn inferred_type(op: &str, value: Option<&Value>, input: impl Fn(usize) -> u32) -> u32 { + match op { + "const_bool" | "get_bool" | "and" | "or" | "not" | "eq" | "noteq" | "gt" | "gteq" | "lr" | "lreq" | "isdefined" => 4, + "const_string" | "get_string" => 16384, + "get_integer1" | "const_int1" | "toint1" | "iswizzle1" => 16, + "get_integer2" | "const_int2" | "toint2" | "iswizzle2" | "ivector2" => 32, + "get_integer3" | "const_int3" | "toint3" | "iswizzle3" | "ivector3" => 64, + "get_integer4" | "const_int4" | "toint4" | "iswizzle4" | "ivector4" => 128, + "get_float1" | "const_float1" | "tofloat" | "swizzle1" | "samplelum" | "atan2" | "dot" => 256, + "get_float2" | "const_float2" | "tofloat2" | "swizzle2" | "vector2" | "cartesian" => 512, + "get_float3" | "const_float3" | "tofloat3" | "swizzle3" | "vector3" => 1024, + "get_float4" | "const_float4" | "tofloat4" | "swizzle4" | "vector4" | "samplecol" => 2048, + "ifelse" | "sequence" => input(1), + "while" => input(2), + "set" => input(0), + _ => value.map_or_else(|| input(0), value_type::type_code), + } +} diff --git a/crates/nodes/src/function/instruction.rs b/crates/nodes/src/function/instruction.rs new file mode 100644 index 00000000..73b6f4e5 --- /dev/null +++ b/crates/nodes/src/function/instruction.rs @@ -0,0 +1,11 @@ +use super::FunctionDefinition; +use materialcraft_core::Value; + +pub(crate) struct Instruction { + pub id: u32, + pub definition: &'static FunctionDefinition, + pub inputs: Vec<usize>, + pub value: Option<Value>, + pub type_code: u32, + pub pure: bool, +} diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs new file mode 100644 index 00000000..2b36446e --- /dev/null +++ b/crates/nodes/src/function/mod.rs @@ -0,0 +1,30 @@ +//! Native function primitives, compilation and bounded evaluation + +mod arithmetic; +mod catalog; +mod compile; +mod evaluation_context; +mod evaluation_state; +mod evaluation_step; +mod function_definition; +mod inferred_type; +mod instruction; +mod node_types; +mod operation; +mod processor; +mod program; +pub mod value_type; +mod vector; + +pub use catalog::{FUNCTIONS, default_value, definition}; +pub use compile::compile; +pub use evaluation_context::EvaluationContext; +pub use evaluation_state::EvaluationState; +pub use function_definition::FunctionDefinition; +pub use node_types::node_types; +pub use processor::default_pixel_function; +pub(crate) use processor::pixel_processor; +pub use program::Program; + +#[cfg(test)] +mod tests; diff --git a/crates/nodes/src/function/node_types.rs b/crates/nodes/src/function/node_types.rs new file mode 100644 index 00000000..e3962f49 --- /dev/null +++ b/crates/nodes/src/function/node_types.rs @@ -0,0 +1,51 @@ +use materialcraft_core::FunctionGraph; +use std::collections::{BTreeMap, BTreeSet}; + +use super::{catalog, inferred_type::inferred_type}; + +pub fn node_types(graph: &FunctionGraph) -> Result<BTreeMap<u32, u32>, String> { + if graph.nodes.len() > 4096 { + return Err("function exceeds the 4096-node limit".into()); + } + + let nodes: BTreeMap<_, _> = graph.nodes.iter().map(|node| (node.id, node)).collect(); + if nodes.len() != graph.nodes.len() { + return Err("duplicate function node ids".into()); + } + + let mut types = BTreeMap::new(); + let mut active = BTreeSet::new(); + for root in &graph.nodes { + let mut pending = vec![(root.id, false)]; + while let Some((id, visited)) = pending.pop() { + if types.contains_key(&id) { + continue; + } + + let node = nodes.get(&id).ok_or_else(|| format!("missing function node {id}"))?; + let definition = catalog::definition(&node.op).ok_or_else(|| format!("unknown function `{}`", node.op))?; + if node.inputs.len() > definition.inputs.len() { + return Err(format!("{} has too many inputs", node.op)); + } + if !visited { + if !active.insert(id) { + return Err(format!("function cycle at node {id}")); + } + + pending.push((id, true)); + pending.extend(node.inputs.iter().rev().flatten().map(|source| (*source, false))); + continue; + } + + active.remove(&id); + let input_type = |slot| node.inputs.get(slot).copied().flatten().and_then(|id| types.get(&id).copied()).unwrap_or(256); + let inferred = inferred_type(&node.op, node.value.as_ref(), input_type); + types.insert(id, if node.type_code == 0 { inferred } else { node.type_code }); + } + } + + if graph.output.is_some_and(|id| !types.contains_key(&id)) { + return Err("function result references a missing node".into()); + } + Ok(types) +} diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs new file mode 100644 index 00000000..0b27e04a --- /dev/null +++ b/crates/nodes/src/function/operation.rs @@ -0,0 +1,108 @@ +use super::{ + EvaluationContext, + instruction::Instruction, + value_type::{self, boolean, dimensions, floats, integers}, +}; +use materialcraft_core::Value; +use std::collections::BTreeMap; + +pub(crate) fn evaluate( + instruction: &Instruction, + arguments: &[Value], + variables: &mut BTreeMap<String, Value>, + random: &mut u32, + context: &EvaluationContext<'_>, +) -> Result<Value, String> { + let op = instruction.definition.id; + let first = || arguments.first().ok_or("missing first operand".to_string()); + let second = || arguments.get(1).ok_or("missing second operand".to_string()); + let name = || match &instruction.value { + Some(Value::Text(name)) => Ok(name.as_str()), + _ => Err("variable name must be a string".to_string()), + }; + + if op.starts_with("const_") { + let value = instruction.value.clone().ok_or("constant has no value")?; + if value_type::type_code(&value) != instruction.type_code { + return Err("constant has the wrong type".into()); + } + return Ok(value); + } + if op.starts_with("get_") { + let name = name()?; + let value = match name { + "$pos" => Value::Float2(context.position), + "$size" => Value::Float2(context.size), + "$sizelog2" => Value::Float2(context.size.map(f32::log2)), + _ => variables.get(name).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?, + }; + + if value_type::type_code(&value) != instruction.type_code { + return Err(format!("variable `{name}` has the wrong type for {op}")); + } + return Ok(value); + } + if op.starts_with("to") || op.contains("vector") || op.contains("swizzle") { + return super::vector::evaluate(op, arguments, instruction.value.as_ref()); + } + + Ok(match op { + "passthrough" => first()?.clone(), + "set" => { + let name = name()?; + if name.is_empty() || name.starts_with('$') { + return Err("use a nonempty user variable name".into()); + } + let value = first()?.clone(); + variables.insert(name.to_string(), value.clone()); + value + } + "isdefined" => Value::Bool(variables.contains_key(name()?) || matches!(name()?, "$pos" | "$size" | "$sizelog2")), + "and" => Value::Bool(boolean(first()?)? && boolean(second()?)?), + "or" => Value::Bool(boolean(first()?)? || boolean(second()?)?), + "not" => Value::Bool(!boolean(first()?)?), + "eq" | "noteq" => { + let (left, right) = (first()?, second()?); + if value_type::type_code(left) != value_type::type_code(right) { + return Err("comparison inputs must have the same type".into()); + } + Value::Bool((left == right) == (op == "eq")) + } + "gt" | "gteq" | "lr" | "lreq" => { + let (left, right) = (first()?, second()?); + if dimensions(left) != 1 || value_type::type_code(left) != value_type::type_code(right) { + return Err("comparison requires matching scalars".into()); + } + let ordering = match (left, right) { + (Value::Int(a), Value::Int(b)) => a.partial_cmp(b), + (Value::Float(a), Value::Float(b)) => a.partial_cmp(b), + _ => return Err("comparison requires numeric inputs".into()), + } + .ok_or("cannot compare non-finite values")?; + Value::Bool(match op { + "gt" => ordering.is_gt(), + "gteq" => ordering.is_ge(), + "lr" => ordering.is_lt(), + _ => ordering.is_le(), + }) + } + "samplecol" | "samplelum" => { + let position = floats(first()?)?; + if dimensions(first()?) != 2 { + return Err("sample position must be float2".into()); + } + let setting = instruction.value.as_ref().map(integers).transpose()?.unwrap_or([0, 1, 0, 0]); + 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) + } + Some(image) => image.sample(position[0], position[1], context.tile), + None => [0.0; 4], + }; + + if op == "samplelum" { Value::Float(pixel[0]) } else { Value::Float4(pixel) } + } + _ => return super::arithmetic::evaluate(op, arguments, random), + }) +} diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs new file mode 100644 index 00000000..3b25818a --- /dev/null +++ b/crates/nodes/src/function/processor.rs @@ -0,0 +1,53 @@ +use super::{EvaluationContext, EvaluationState, compile}; +use crate::{CookContext, CookResult}; +use materialcraft_core::{FunctionGraph, Value}; +use materialcraft_image::{Image, Kind}; +use rayon::prelude::*; +use std::sync::Arc; + +pub fn default_pixel_function() -> FunctionGraph { + let mut graph = FunctionGraph::default(); + let position = graph.add("get_float2", &[], Some(Value::Text("$pos".into()))); + graph.output = Some(graph.add("samplecol", &[position], Some(Value::Int2([0, 1])))); + graph +} + +fn pixel(value: Value, gray: bool) -> Result<[f32; 4], String> { + let values = super::value_type::floats(&value)?; + Ok(if gray { + [values[0], 0.0, 0.0, 0.0] + } else { + match super::value_type::dimensions(&value) { + 1 => [values[0], values[0], values[0], 1.0], + 2 => [values[0], values[1], 0.0, 1.0], + 3 => [values[0], values[1], values[2], 1.0], + _ => values, + } + }) +} + +pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { + let graph = context.function("function").ok_or("missing pixel function")?; + let program = compile(graph, context.seed)?; + 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 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> { + for (x, target) in row.chunks_exact_mut(channels).enumerate() { + let evaluation = EvaluationContext { + position: [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32], + size: [width as f32, height as f32], + images: context.inputs, + tile: context.tile, + variables: context.vars, + }; + + let result = pixel(program.evaluate(&evaluation, state)?, gray)?; + target.copy_from_slice(result.get(..channels).ok_or("invalid output channels")?); + } + Ok(()) + })?; + Ok(vec![Image { w: width, h: height, kind, data: Arc::new(data) }]) +} diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs new file mode 100644 index 00000000..0ee75a58 --- /dev/null +++ b/crates/nodes/src/function/program.rs @@ -0,0 +1,121 @@ +use super::{EvaluationContext, EvaluationState, evaluation_step::EvaluationStep, instruction::Instruction, operation, value_type}; +use materialcraft_core::Value; + +/// Validated graph with input ids resolved to instruction indices +pub struct Program { + pub(crate) instructions: Vec<Instruction>, + pub(crate) output: usize, + pub(crate) seed: u32, +} + +const MAX_EVALUATION_STEPS: usize = 100_000; + +impl Program { + pub fn output_type(&self) -> u32 { + self.instructions.get(self.output).map_or(0, |instruction| instruction.type_code) + } + + pub fn node_type(&self, id: u32) -> Option<u32> { + self.instructions.iter().find(|instruction| instruction.id == id).map(|instruction| instruction.type_code) + } + + fn instruction(&self, index: usize) -> Result<&Instruction, String> { + self.instructions.get(index).ok_or("invalid function instruction".into()) + } + + fn input(&self, index: usize, slot: usize) -> Result<usize, String> { + self.instruction(index)?.inputs.get(slot).copied().ok_or("missing function input".into()) + } + + pub fn evaluate(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> { + use EvaluationStep::*; + state.steps.clear(); + state.values.clear(); + state.registers.clear(); + state.registers.resize(self.instructions.len(), None); + state.variables.clone_from(context.variables); + state.random = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32); + state.steps.push(Enter(self.output)); + let mut remaining_steps = MAX_EVALUATION_STEPS; + while let Some(step) = state.steps.pop() { + remaining_steps = remaining_steps.checked_sub(1).ok_or("function exceeded its execution budget; check loop termination")?; + match step { + Enter(index) => { + let instruction = self.instruction(index)?; + if let Some(Some(value)) = state.registers.get(index) { + state.values.push(value.clone()); + continue; + } + + match instruction.definition.id { + "ifelse" => { + state.steps.push(Branch(index)); + state.steps.push(Enter(self.input(index, 0)?)); + } + "sequence" => { + state.steps.push(Sequence(index)); + state.steps.push(Enter(self.input(index, 0)?)); + } + "while" => { + state.steps.push(LoopStart(index)); + state.steps.push(Enter(self.input(index, 0)?)); + } + _ => { + state.steps.push(Apply { instruction: index, base: state.values.len() }); + state.steps.extend(instruction.inputs.iter().rev().map(|index| Enter(*index))); + } + } + } + Apply { instruction: index, base } => { + let instruction = self.instruction(index)?; + let arguments = state.values.get(base..).ok_or("invalid function operands")?; + let result = operation::evaluate(instruction, arguments, &mut state.variables, &mut state.random, context) + .map_err(|error| format!("{} ({}): {error}", instruction.definition.label, instruction.id))?; + state.values.truncate(base); + if instruction.pure + && let Some(register) = state.registers.get_mut(index) + { + *register = Some(result.clone()); + } + state.values.push(result); + } + Branch(index) => { + let condition = state.values.pop().ok_or("missing branch condition")?; + let slot = if value_type::boolean(&condition)? { 1 } else { 2 }; + state.steps.push(Enter(self.input(index, slot)?)); + } + Sequence(index) => { + state.values.pop().ok_or("missing sequence result")?; + state.steps.push(Enter(self.input(index, 1)?)); + } + LoopStart(index) => { + let last = state.values.pop().ok_or("missing loop initialization")?; + state.steps.push(LoopCondition { instruction: index, iteration: 0, last }); + state.steps.push(Enter(self.input(index, 1)?)); + } + LoopCondition { instruction: index, iteration, last } => { + let exit = value_type::boolean(&state.values.pop().ok_or("missing loop condition")?)?; + let maximum = self.instruction(index)?.value.as_ref().and_then(Value::as_i32).unwrap_or(100); + if exit || (maximum >= 0 && iteration >= maximum as u32) { + state.values.push(last); + } else { + state.steps.push(LoopBody { instruction: index, iteration: iteration.saturating_add(1) }); + state.steps.push(Enter(self.input(index, 2)?)); + } + } + LoopBody { instruction: index, iteration } => { + let last = state.values.pop().ok_or("missing loop body result")?; + state.steps.push(LoopCondition { instruction: index, iteration, last }); + state.steps.push(Enter(self.input(index, 1)?)); + } + } + } + + let result = state.values.pop().ok_or("function returned no value")?; + let expected = self.instruction(self.output)?.type_code; + if value_type::type_code(&result) != expected { + return Err(format!("function returned {}, expected native type {expected}", result.type_name())); + } + Ok(result) + } +} diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs new file mode 100644 index 00000000..6793d58c --- /dev/null +++ b/crates/nodes/src/function/tests.rs @@ -0,0 +1,164 @@ +use materialcraft_core::{FunctionGraph, Value}; +use materialcraft_image::{Image, Kind}; +use std::collections::{BTreeMap, BTreeSet}; + +use super::{EvaluationContext, EvaluationState, FUNCTIONS, compile, default_value}; + +fn evaluate(graph: &FunctionGraph, variables: &BTreeMap<String, Value>) -> Result<Value, String> { + let image = Image::filled(3, 5, Kind::Color, [0.25, 0.5, 0.75, 1.0]); + let context = EvaluationContext { position: [0.5; 2], size: [3.0, 5.0], images: &[Some(image)], tile: true, variables }; + compile(graph, 7)?.evaluate(&context, &mut EvaluationState::default()) +} + +fn operation(name: &str, arguments: &[Value], setting: Option<Value>) -> Result<Value, String> { + let mut graph = FunctionGraph::default(); + let inputs: Vec<_> = arguments.iter().map(|value| graph.add_constant(value.clone())).collect(); + graph.output = Some(graph.add(name, &inputs, setting)); + evaluate(&graph, &BTreeMap::new()) +} + +#[test] +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); + let mut arguments = vec![Value::Float(0.5); definition.inputs.len()]; + match name { + "get_bool" => { + variables.insert("variable".into(), Value::Bool(true)); + } + "get_string" => { + variables.insert("variable".into(), Value::Text("test".into())); + } + "get_float1" => { + variables.insert("variable".into(), Value::Float(1.0)); + } + "get_float2" => { + variables.insert("variable".into(), Value::Float2([1.0; 2])); + } + "get_float3" => { + variables.insert("variable".into(), Value::Float3([1.0; 3])); + } + "get_float4" => { + variables.insert("variable".into(), Value::Float4([1.0; 4])); + } + "get_integer1" => { + variables.insert("variable".into(), Value::Int(1)); + } + "get_integer2" => { + variables.insert("variable".into(), Value::Int2([1; 2])); + } + "get_integer3" => { + variables.insert("variable".into(), Value::Int3([1; 3])); + } + "get_integer4" => { + variables.insert("variable".into(), Value::Int4([1; 4])); + } + "and" | "or" | "not" => arguments.fill(Value::Bool(true)), + "atan2" | "samplecol" | "samplelum" => arguments = vec![Value::Float2([0.5; 2])], + "vector3" => arguments = vec![Value::Float2([1.0; 2]), Value::Float(2.0)], + "vector4" => arguments = vec![Value::Float3([1.0; 3]), Value::Float(2.0)], + "ivector2" => arguments = vec![Value::Int(1), Value::Int(2)], + "ivector3" => arguments = vec![Value::Int2([1; 2]), Value::Int(2)], + "ivector4" => arguments = vec![Value::Int3([1; 3]), Value::Int(2)], + "tofloat" => arguments = vec![Value::Int(1)], + "tofloat2" => arguments = vec![Value::Int2([1; 2])], + "tofloat3" => arguments = vec![Value::Int3([1; 3])], + "tofloat4" => arguments = vec![Value::Int4([1; 4])], + "toint2" => arguments = vec![Value::Float2([1.5; 2])], + "toint3" => arguments = vec![Value::Float3([1.5; 3])], + "toint4" => arguments = vec![Value::Float4([1.5; 4])], + "ifelse" => arguments = vec![Value::Bool(false), Value::Float(1.0), Value::Float(2.0)], + "while" => arguments = vec![Value::Float(0.0), Value::Bool(true), Value::Float(1.0)], + _ if name.starts_with("iswizzle") => arguments = vec![Value::Int4([1, 2, 3, 4])], + _ if name.starts_with("swizzle") => arguments = vec![Value::Float4([1.0, 2.0, 3.0, 4.0])], + _ => {} + } + if name.starts_with("get_") || matches!(name, "set" | "isdefined") { + setting = Some(Value::Text("variable".into())); + } + let inputs: Vec<_> = arguments.into_iter().map(|value| graph.add_constant(value)).collect(); + graph.output = Some(graph.add(name, &inputs, setting)); + evaluate(&graph, &variables).unwrap_or_else(|error| panic!("{name}: {error}")); + } + assert_eq!(covered.len(), 85); +} + +#[test] +fn integer_math_preserves_all_32_bits_and_rejects_overflow() { + assert_eq!(operation("add", &[Value::Int(16_777_217), Value::Int(1)], None).unwrap(), Value::Int(16_777_218)); + assert_eq!(operation("mul", &[Value::Int3([2, 3, 4]), Value::Int3([3, 4, 5])], None).unwrap(), Value::Int3([6, 12, 20])); + assert!(operation("add", &[Value::Int(i32::MAX), Value::Int(1)], None).is_err()); + assert!(operation("div", &[Value::Int(i32::MIN), Value::Int(-1)], None).is_err()); + assert!(operation("div", &[Value::Float(1.0), Value::Float(0.0)], None).is_err()); +} + +#[test] +fn vectors_concatenate_swizzle_and_cast_without_broadcasting() { + let vector = operation("vector4", &[Value::Float2([1.0, 2.0]), Value::Float2([3.0, 4.0])], None).unwrap(); + assert_eq!(vector, Value::Float4([1.0, 2.0, 3.0, 4.0])); + assert_eq!(operation("swizzle3", &[vector], Some(Value::Int3([3, 0, 3]))).unwrap(), Value::Float3([4.0, 1.0, 4.0])); + assert_eq!(operation("toint2", &[Value::Float2([-1.9, 2.9])], None).unwrap(), Value::Int2([-1, 2])); + assert!(operation("swizzle1", &[Value::Float2([0.0; 2])], Some(Value::Int(2))).is_err()); + assert_eq!(operation("pow2", &[Value::Float(3.0)], None).unwrap(), Value::Float(8.0)); +} + +#[test] +fn branches_are_lazy_and_sequence_orders_side_effects() { + let mut graph = FunctionGraph::default(); + let condition = graph.add_constant(Value::Bool(true)); + 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)); +} + +#[test] +fn loops_recompute_state_and_have_a_budget() { + let mut graph = FunctionGraph::default(); + let zero = graph.add_constant(Value::Int(0)); + let one = graph.add_constant(Value::Int(1)); + let three = graph.add_constant(Value::Int(3)); + let init = graph.add("set", &[zero], Some(Value::Text("counter".into()))); + let get = graph.add("get_integer1", &[], Some(Value::Text("counter".into()))); + let condition = graph.add("gteq", &[get, three], None); + 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")); +} + +#[test] +fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { + let mut graph = FunctionGraph::constant(Value::Float(1.0)); + let mut previous = graph.output.unwrap(); + for _ in 0..3000 { + previous = graph.add("passthrough", &[previous], None); + } + graph.output = Some(previous); + 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)); + let mut previous = graph.output.unwrap(); + for _ in 0..30 { + 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)); +} diff --git a/crates/nodes/src/function/value_type.rs b/crates/nodes/src/function/value_type.rs new file mode 100644 index 00000000..4c104008 --- /dev/null +++ b/crates/nodes/src/function/value_type.rs @@ -0,0 +1,65 @@ +use materialcraft_core::Value; + +pub fn type_code(value: &Value) -> u32 { + materialcraft_core::ValueType::of(value).map_or(0, |value_type| value_type as u32) +} + +pub fn dimensions(value: &Value) -> usize { + match value { + Value::Float2(_) | Value::Int2(_) => 2, + Value::Float3(_) | Value::Int3(_) => 3, + Value::Float4(_) | Value::Int4(_) | Value::Color(_) => 4, + _ => 1, + } +} + +pub fn floats(value: &Value) -> Result<[f32; 4], String> { + Ok(match value { + Value::Float(v) => [*v; 4], + Value::Float2(v) => [v[0], v[1], 0.0, 0.0], + Value::Float3(v) => [v[0], v[1], v[2], 0.0], + Value::Float4(v) | Value::Color(v) => *v, + _ => return Err(format!("expected float, got {}", value.type_name())), + }) +} + +pub fn integers(value: &Value) -> Result<[i32; 4], String> { + Ok(match value { + Value::Int(v) => [*v; 4], + Value::Int2(v) => [v[0], v[1], 0, 0], + Value::Int3(v) => [v[0], v[1], v[2], 0], + Value::Int4(v) => *v, + _ => return Err(format!("expected integer, got {}", value.type_name())), + }) +} + +pub fn float_value(values: &[f32]) -> Result<Value, String> { + if values.iter().any(|v| !v.is_finite()) { + return Err("operation produced a non-finite number".into()); + } + + Ok(match values { + [a] => Value::Float(*a), + [a, b] => Value::Float2([*a, *b]), + [a, b, c] => Value::Float3([*a, *b, *c]), + [a, b, c, d] => Value::Float4([*a, *b, *c, *d]), + _ => return Err("expected one to four components".into()), + }) +} + +pub fn integer_value(values: &[i32]) -> Result<Value, String> { + Ok(match values { + [a] => Value::Int(*a), + [a, b] => Value::Int2([*a, *b]), + [a, b, c] => Value::Int3([*a, *b, *c]), + [a, b, c, d] => Value::Int4([*a, *b, *c, *d]), + _ => return Err("expected one to four components".into()), + }) +} + +pub fn boolean(value: &Value) -> Result<bool, String> { + match value { + Value::Bool(value) => Ok(*value), + _ => Err(format!("expected boolean, got {}", value.type_name())), + } +} diff --git a/crates/nodes/src/function/vector.rs b/crates/nodes/src/function/vector.rs new file mode 100644 index 00000000..682494c4 --- /dev/null +++ b/crates/nodes/src/function/vector.rs @@ -0,0 +1,70 @@ +use super::value_type::{dimensions, float_value, floats, integer_value, integers}; +use materialcraft_core::Value; + +pub(crate) fn evaluate(op: &str, args: &[Value], setting: Option<&Value>) -> Result<Value, String> { + let first = args.first().ok_or("missing vector input")?; + let count = op.chars().last().and_then(|c| c.to_digit(10)).unwrap_or(1) as usize; + if !(1..=4).contains(&count) { + return Err("invalid vector size".into()); + } + let integer = op.starts_with('i') || op.starts_with("toint"); + let mut result_float = [0.0; 4]; + let mut result_int = [0; 4]; + if op.contains("swizzle") { + let indices = setting.map(integers).transpose()?.unwrap_or([0; 4]); + let floats = if integer { [0.0; 4] } else { floats(first)? }; + let integers = if integer { integers(first)? } else { [0; 4] }; + for (lane, index) in indices.iter().take(count).enumerate() { + let index = usize::try_from(*index).ok().filter(|index| *index < dimensions(first)).ok_or("swizzle component is outside its input")?; + if integer { + if let Some(result) = result_int.get_mut(lane) { + *result = *integers.get(index).ok_or("invalid swizzle")?; + } + } else if let Some(result) = result_float.get_mut(lane) { + *result = *floats.get(index).ok_or("invalid swizzle")?; + } + } + } else if op.contains("vector") { + let last = args.get(1).ok_or("missing final vector component")?; + if dimensions(first) + dimensions(last) != count { + return Err(format!("vector{count} requires inputs totaling {count} components")); + } + + if integer { + let left = integers(first)?; + let right = integers(last)?; + for (result, value) in result_int.iter_mut().zip(left.into_iter().take(dimensions(first)).chain(right.into_iter().take(dimensions(last)))) { + *result = value; + } + } else { + let left = floats(first)?; + let right = floats(last)?; + for (result, value) in result_float.iter_mut().zip(left.into_iter().take(dimensions(first)).chain(right.into_iter().take(dimensions(last)))) { + *result = value; + } + } + } else { + if dimensions(first) != count { + return Err("casts preserve the number of components".into()); + } + if integer { + let values = floats(first)?; + for (result, value) in result_int.iter_mut().zip(values).take(count) { + if !value.is_finite() || !(-2147483648.0..2147483648.0).contains(&value) { + return Err("float is outside the integer range".into()); + } + *result = value.trunc() as i32; + } + } else { + for (result, value) in result_float.iter_mut().zip(integers(first)?).take(count) { + *result = value as f32; + } + } + } + + if integer { + integer_value(result_int.get(..count).ok_or("invalid integer dimensions")?) + } else { + float_value(result_float.get(..count).ok_or("invalid float dimensions")?) + } +} diff --git a/crates/nodes/src/fx_map.rs b/crates/nodes/src/fx_map.rs deleted file mode 100644 index baae5adf..00000000 --- a/crates/nodes/src/fx_map.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Atomic › FX-Map: a pattern instancer (regular grid, random scatter or random quadtree -//! subdivision), plus the shared splatting engine of the scatter nodes. Instances wrap across the -//! edges, so the output tiles. - -use std::f32::consts::{SQRT_2, TAU}; - -use materialcraft_image::{Image, Kind}; - -use crate::atomic::ATOMIC; -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::noise::{hash, rand1}; -use crate::patterns::{PATTERNS, SHAPES, shape}; - -/// One placed pattern: center (uv), half extents (uv), rotation (turns), luminance and the index -/// of the pattern it shows. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Inst { - pub c: [f32; 2], - pub r: [f32; 2], - pub rot: f32, - pub lum: f32, - pub pat: usize, -} - -pub(crate) const BLENDS: &[&str] = &["Max", "Add", "Alpha over"]; - -/// Renders `items` over black. Item `i` covers the rotated box ±`r` around its center, where -/// `pat(i, x, y)` is its pattern (0..1) at local coordinates -1..1. Items are binned on a grid about -/// their size so a pixel only tests its neighbours; later items draw on top (Alpha over). -pub(crate) fn splat(ctx: &Ctx, items: &[Inst], blend: i32, pat: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image { - let valid = |it: &Inst| it.r[0] > 1e-6 && it.r[1] > 1e-6 && it.c.iter().chain(&it.r).all(|v| v.is_finite()); - let n = items.iter().filter(|it| valid(it)).count().max(1); - let mean_r = items.iter().filter(|it| valid(it)).map(|it| it.r[0].max(it.r[1])).sum::<f32>() / n as f32; - let g = ((0.5 / mean_r.max(1e-4)) as usize).clamp(1, 256); - let gf = g as f32; - let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g]; - for (i, it) in items.iter().enumerate().filter(|(_, it)| valid(it)) { - let br = it.r[0].max(it.r[1]) * SQRT_2; - // At most one full turn of bins per axis, so no item lands twice in a bin. - let span = |c: f32| { - let a = ((c - br) * gf).floor() as i64; - (a, (((c + br) * gf).floor() as i64).min(a + g as i64 - 1)) - }; - let ((x0, x1), (y0, y1)) = (span(it.c[0]), span(it.c[1])); - for gy in y0..=y1 { - for gx in x0..=x1 { - if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) { - b.push(i as u32); - } - } - } - } - let rots: Vec<(f32, f32)> = items.iter().map(|it| (-it.rot * TAU).sin_cos()).collect(); - let tile = ctx.tile; - Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let mut acc = 0.0f32; - let bin = bins.get(((v * gf) as usize).min(g - 1) * g + ((u * gf) as usize).min(g - 1)); - for &i in bin.into_iter().flatten() { - let (Some(it), Some(&(s, c))) = (items.get(i as usize), rots.get(i as usize)) else { continue }; - let (mut dx, mut dy) = (u - it.c[0], v - it.c[1]); - if tile { - dx -= dx.round(); - dy -= dy.round(); - } - let (x, y) = ((dx * c - dy * s) / it.r[0], (dx * s + dy * c) / it.r[1]); - if x.abs() > 1.0 || y.abs() > 1.0 { - continue; - } - let p = pat(i as usize, x, y); - if p <= 0.0 { - continue; - } - acc = match blend { - 1 => acc + p * it.lum, - 2 => acc + (it.lum - acc) * p.min(1.0), - _ => acc.max(p * it.lum), - }; - } - [acc, 0.0, 0.0, 0.0] - }) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("fx_map", "FX-Map", ATOMIC) - .desc( - "Instances up to three patterns on a grid, at random positions or in a random quadtree, with per-instance scale, rotation, \ - position and luminance jitter. Scale 1 fills an instance's cell. Unconnected: soft discs. Tiles.", - ) - .atomic() - .generator() - .gray_in("pattern0", "Pattern 0") - .gray_in("pattern1", "Pattern 1") - .gray_in("pattern2", "Pattern 2") - .choice("mode", "Mode", &["Grid", "Random", "Quadtree"], 2) - .int("count", "Count (random)", 64, 1, 20000) - .int("x_amount", "X amount", 4, 1, 256) - .int("y_amount", "Y amount", 4, 1, 256) - .int("subdivisions", "Subdivisions (quadtree)", 3, 0, 8) - .float("split_chance", "Subdivide chance", 0.5, 0.0, 1.0) - .float("scale", "Scale", 0.9, 0.0, 2.0) - .float("scale_random", "Scale random", 0.2, 0.0, 1.0) - .angle("rotation", "Rotation", 0.0) - .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) - .float("position_random", "Position random", 0.0, 0.0, 1.0) - .float("luminance", "Luminance", 1.0, 0.0, 1.0) - .float("luminance_random", "Luminance random", 0.4, 0.0, 1.0) - .float("pattern_random", "Pattern random", 1.0, 0.0, 1.0) - .choice("blending", "Blending", BLENDS, 0) - .int("seed_offset", "Seed offset", 0, 0, 10000) - .gray_out() - .cook(fx_map), - node("shape_splatter", "Shape Splatter", PATTERNS) - .desc("Scatters the pattern input (or a shape) with random scale, rotation and luminance; the mask input sets where instances land.") - .generator() - .gray_in("pattern", "Pattern") - .gray_in("mask", "Mask") - .choice("shape", "Shape (no input)", SHAPES, 3) - .int("count", "Count", 300, 1, 20000) - .float("size", "Size", 0.05, 0.0, 1.0) - .float("size_random", "Size random", 0.5, 0.0, 1.0) - .float("rotation_random", "Rotation random", 1.0, 0.0, 1.0) - .float("luminance_random", "Luminance random", 0.4, 0.0, 1.0) - .choice("blending", "Blending", BLENDS, 0) - .gray_out() - .cook(shape_splatter), - ] -} - -/// A connected pattern at local `(x, y)` (-1..1), or a soft disc when there is none. -pub(crate) fn sample_pattern(pats: &[Image], k: usize, x: f32, y: f32) -> f32 { - match pats.get(k) { - Some(img) => img.sample_gray((x + 1.0) * 0.5, (y + 1.0) * 0.5, false), - None => shape(3, x, y), - } -} - -/// Cells of a random quadtree over an `nx × ny` root grid: (center, size, key). A cell splits -/// with probability `chance` until `depth`. -fn quadtree(nx: i32, ny: i32, depth: i32, chance: f32, seed: u32) -> Vec<([f32; 2], [f32; 2], u32)> { - const MAX_CELLS: usize = 1 << 18; - let mut out = Vec::new(); - let mut stack: Vec<([f32; 2], [f32; 2], i32, u32)> = Vec::new(); - for j in (0..ny).rev() { - for i in (0..nx).rev() { - let size = [1.0 / nx as f32, 1.0 / ny as f32]; - stack.push(([i as f32 * size[0], j as f32 * size[1]], size, 0, hash((j * nx + i) as u32 ^ 0x5157_0000))); - } - } - while let Some((p, s, lvl, key)) = stack.pop() { - if lvl < depth && rand1(key, seed ^ 0x51ed) < chance && out.len() + stack.len() + 4 <= MAX_CELLS { - let h = [s[0] * 0.5, s[1] * 0.5]; - for q in (0..4u32).rev() { - let o = [p[0] + (q & 1) as f32 * h[0], p[1] + (q >> 1) as f32 * h[1]]; - stack.push((o, h, lvl + 1, hash(key.wrapping_mul(4).wrapping_add(q + 1)))); - } - } else { - out.push(([p[0] + s[0] * 0.5, p[1] + s[1] * 0.5], s, key)); - } - } - out -} - -/// The instances an FX-Map places (separate from rendering, so it can be tested). -pub(crate) fn fx_instances(ctx: &Ctx, n_patterns: usize) -> Vec<Inst> { - let seed = ctx.seed.wrapping_add(ctx.i("seed_offset") as u32); - let (nx, ny) = (ctx.i("x_amount").clamp(1, 256), ctx.i("y_amount").clamp(1, 256)); - let cells: Vec<([f32; 2], [f32; 2], u32)> = match ctx.i("mode") { - 0 => (0..ny) - .flat_map(|j| { - (0..nx).map(move |i| ([(i as f32 + 0.5) / nx as f32, (j as f32 + 0.5) / ny as f32], [1.0 / nx as f32, 1.0 / ny as f32], (j * nx + i) as u32)) - }) - .collect(), - 1 => { - let count = ctx.i("count").clamp(1, 20000) as u32; - let side = 1.0 / (count as f32).sqrt(); - (0..count).map(|i| ([rand1(i * 2, seed ^ 0xa11), rand1(i * 2 + 1, seed ^ 0xa11)], [side, side], i)).collect() - } - _ => quadtree(nx, ny, ctx.i("subdivisions").clamp(0, 8), ctx.f("split_chance"), seed), - }; - let (sc, sr, rot, rr, pr) = (ctx.f("scale"), ctx.f("scale_random"), ctx.f("rotation"), ctx.f("rotation_random"), ctx.f("position_random")); - let (lum, lr, patr) = (ctx.f("luminance"), ctx.f("luminance_random"), ctx.f("pattern_random")); - let n = n_patterns.max(1); - cells - .into_iter() - .map(|(c, size, key)| { - let r = |k: u32| rand1(key.wrapping_mul(8).wrapping_add(k), seed); - let s = sc * (1.0 - sr * r(2)); - Inst { - c: [c[0] + (r(0) - 0.5) * pr * size[0], c[1] + (r(1) - 0.5) * pr * size[1]], - r: [size[0] * 0.5 * s, size[1] * 0.5 * s], - rot: rot + (r(3) - 0.5) * rr, - lum: lum * (1.0 - lr * r(4)), - pat: if r(5) < patr { ((r(6) * n as f32) as usize).min(n - 1) } else { 0 }, - } - }) - .collect() -} - -fn fx_map(ctx: &Ctx) -> CookResult { - let pats: Vec<Image> = (0..3).filter_map(|i| ctx.input(i).map(Image::to_gray)).collect(); - let items = fx_instances(ctx, pats.len()); - Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| sample_pattern(&pats, items.get(i).map_or(0, |it| it.pat), x, y))]) -} - -fn shape_splatter(ctx: &Ctx) -> CookResult { - let pats: Vec<Image> = ctx.input(0).map(Image::to_gray).into_iter().collect(); - let mask = ctx.input(1); - let (k, s) = (ctx.i("shape"), ctx.seed); - let (size, sr, rr, lr) = (ctx.f("size"), ctx.f("size_random"), ctx.f("rotation_random"), ctx.f("luminance_random")); - let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 20000) as u32) - .filter_map(|i| { - let r = |k: u32| rand1(i * 8 + k, s); - let c = [r(0), r(1)]; - // Instances land where the mask is bright: kept with probability = mask value. - if mask.is_some_and(|m| r(2) >= m.sample_gray(c[0], c[1], ctx.tile)) { - return None; - } - let rad = size * (1.0 - sr * r(3)); - Some(Inst { c, r: [rad, rad], rot: (r(4) - 0.5) * rr, lum: 1.0 - lr * r(5), pat: 0 }) - }) - .collect(); - Ok(vec![splat(ctx, &items, ctx.i("blending"), |_, x, y| if pats.is_empty() { shape(k, x, y) } else { sample_pattern(&pats, 0, x, y) })]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use materialcraft_core::Value; - - use super::*; - use crate::catalog::{find, resolve_params}; - - fn with(params: &[(&str, Value)], f: impl FnOnce(&Ctx)) { - let def = find("fx_map").unwrap(); - let mut p = resolve_params(def, &BTreeMap::new()); - for (k, v) in params { - p.insert(k.to_string(), v.clone()); - } - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = [None, None, None]; - f(&Ctx { w: 64, h: 64, seed: 3, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars }); - } - - #[test] - fn fx_map_instance_counts() { - with(&[("mode", Value::Enum(0)), ("x_amount", Value::Int(5)), ("y_amount", Value::Int(3))], |c| assert_eq!(fx_instances(c, 1).len(), 15)); - with(&[("mode", Value::Enum(1)), ("count", Value::Int(77))], |c| assert_eq!(fx_instances(c, 1).len(), 77)); - let quad = |chance: f32, depth: i32| { - let mut n = 0; - with( - &[ - ("mode", Value::Enum(2)), - ("x_amount", Value::Int(2)), - ("y_amount", Value::Int(1)), - ("subdivisions", Value::Int(depth)), - ("split_chance", Value::Float(chance)), - ], - |c| n = fx_instances(c, 1).len(), - ); - n - }; - assert_eq!(quad(0.0, 3), 2); - assert_eq!(quad(1.0, 3), 2 * 64); - let some = quad(0.5, 4); - assert!(some > 2 && some < 2 * 256, "{some}"); - } - - #[test] - fn fx_map_is_deterministic_per_seed() { - let cook = |off: i32| { - let mut img = None; - with(&[("seed_offset", Value::Int(off))], |c| img = Some(fx_map(c).unwrap().remove(0))); - img.unwrap() - }; - assert_eq!(cook(0), cook(0)); - assert_ne!(cook(0), cook(1)); - assert!(cook(0).mean()[0] > 0.05); - } -} diff --git a/crates/nodes/src/generators.rs b/crates/nodes/src/generators.rs deleted file mode 100644 index f30db65a..00000000 --- a/crates/nodes/src/generators.rs +++ /dev/null @@ -1,413 +0,0 @@ -//! Texture generators › Noises. All tile seamlessly: lattice scales are whole numbers of cells. - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::noise::{self, cellular, fbm, perlin, rand2, ridged, value}; -use crate::ops; - -pub const NOISES: &str = "Texture generators/Noises"; - -fn scale(ctx: &Ctx) -> f32 { - ctx.f("scale").max(1.0).round() -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let n = |id, label| node(id, label, NOISES).generator(); - vec![ - n("anisotropic_noise", "Anisotropic Noise") - .desc("Streaks of value noise stretched along one axis.") - .float("scale", "X amount", 4.0, 1.0, 64.0) - .float("scale_y", "Y amount", 64.0, 1.0, 512.0) - .float("smoothness", "Smoothness", 0.5, 0.0, 1.0) - .float("interpolation", "Interpolation", 1.0, 0.0, 1.0) - .gray_out() - .cook(anisotropic), - n("bnw_spots_1", "BnW Spots 1") - .desc("Contrasted black and white spots.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(bnw1), - n("bnw_spots_2", "BnW Spots 2") - .desc("Rounder black and white spots.") - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.3, 0.0, 1.0) - .gray_out() - .cook(bnw2), - n("bnw_spots_3", "BnW Spots 3") - .desc("Fine black and white speckles.") - .float("scale", "Scale", 16.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.6, 0.0, 1.0) - .gray_out() - .cook(bnw3), - n("cells_1", "Cells 1") - .desc("Distance to the nearest cell point (soft bumps).") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells1), - n("cells_2", "Cells 2") - .desc("Cell borders (second minus first distance).") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells2), - n("cells_3", "Cells 3") - .desc("Flat cells, each a random gray.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells3), - n("cells_4", "Cells 4") - .desc("Chebyshev cells: square bumps.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells4), - n("clouds_1", "Clouds 1") - .desc("Soft fractal clouds.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(clouds1), - n("clouds_2", "Clouds 2") - .desc("Warped, wispy clouds.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.55, 0.0, 1.0) - .gray_out() - .cook(clouds2), - n("clouds_3", "Clouds 3") - .desc("Detailed, contrasted clouds.") - .float("scale", "Scale", 6.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.6, 0.0, 1.0) - .gray_out() - .cook(clouds3), - n("creased", "Creased") - .desc("Ridged fractal noise: folds and creases.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.55, 0.0, 1.0) - .float("warp", "Warp intensity", 0.3, 0.0, 1.0) - .gray_out() - .cook(creased), - n("crystal_1", "Crystal 1").desc("Faceted crystal plates.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal1), - n("crystal_2", "Crystal 2").desc("Sharp crystal shards.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal2), - n("dirt", "Dirt").desc("Clumps of dirt.").float("scale", "Scale", 6.0, 1.0, 64.0).float("density", "Density", 0.5, 0.0, 1.0).gray_out().cook(dirt), - n("dust", "Dust").desc("Sparse specks of dust.").float("density", "Density", 0.02, 0.0, 0.2).float("size", "Size", 1.0, 0.0, 8.0).gray_out().cook(dust), - n("fractal_sum_base", "Fractal Sum Base") - .desc("Sum of Perlin noise octaves.") - .float("scale", "Min level", 2.0, 1.0, 64.0) - .int("octaves", "Octaves", 8, 1, 12) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(fractal_sum), - n("fur", "Fur") - .desc("Short directional fibers.") - .float("scale", "Density", 1.0, 0.1, 4.0) - .angle("angle", "Direction", 0.25) - .float("length", "Length", 8.0, 0.0, 64.0) - .gray_out() - .cook(fur), - n("gaussian_noise", "Gaussian Noise") - .desc("Smoothly interpolated value noise.") - .float("scale", "Scale", 16.0, 1.0, 256.0) - .gray_out() - .cook(gaussian_noise), - n("grunge_map_1", "Grunge Map 1") - .desc("Stains and blotches.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(grunge1), - n("grunge_map_2", "Grunge Map 2") - .desc("Speckled grime.") - .float("scale", "Scale", 5.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(grunge2), - n("grunge_map_3", "Grunge Map 3") - .desc("Streaky leaks.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(grunge3), - n("liquid", "Liquid") - .desc("Domain-warped flowing noise.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("warp", "Warp", 0.6, 0.0, 2.0) - .gray_out() - .cook(liquid), - n("moisture_noise", "Moisture Noise") - .desc("Damp patches with soft edges.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(moisture), - n("perlin_noise", "Perlin Noise") - .desc("Single-octave gradient noise.") - .float("scale", "Scale", 8.0, 1.0, 256.0) - .float("disorder", "Disorder", 0.0, 0.0, 1.0) - .gray_out() - .cook(perlin_noise), - n("plasma", "Plasma").desc("Interfering sine waves through noise.").float("scale", "Scale", 4.0, 1.0, 32.0).gray_out().cook(plasma), - n("turbulence", "Turbulence") - .desc("Billowing absolute-value fractal noise.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(turbulence), - n("voronoi", "Voronoi") - .desc("Cellular noise with a choice of distance and output.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .choice("metric", "Distance", &["Euclidean", "Manhattan", "Chebyshev"], 0) - .choice("style", "Output", &["F1", "F2", "F2 - F1", "Cell id"], 2) - .gray_out() - .cook(voronoi), - n("white_noise", "White Noise").desc("Independent random value per pixel.").choice("mode", "Output", &["Grayscale", "Color"], 0).cook(white_noise), - ] -} - -fn anisotropic(ctx: &Ctx) -> CookResult { - let (sx, sy) = (scale(ctx), ctx.f("scale_y").max(1.0).round()); - let smooth = ctx.f("smoothness"); - let s = ctx.seed; - let base = ctx.gen_gray(|u, v| { - let a = value(u * sx, v * sy, sy as i32, s); - let b = value(u * sx * 2.0, v * sy, sy as i32, s ^ 77) * 0.5; - (a * 0.75 + b * 0.25 * (1.0 - smooth) + 0.125 * smooth).clamp(0.0, 1.0) - }); - Ok(vec![if smooth > 0.0 { ops::gaussian(&base, smooth * 2.0, ctx.tile) } else { base }]) -} - -fn contrast(v: f32, c: f32) -> f32 { - ((v - 0.5) * (1.0 + c * 8.0) + 0.5).clamp(0.0, 1.0) -} - -fn bnw1(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 6, 0.3 + r * 0.4, s), 0.6))]) -} - -fn bnw2(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 3, 0.3 + r * 0.4, s), 1.2))]) -} - -fn bnw3(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 7, 0.4 + r * 0.4, s), 0.9))]) -} - -fn cell_cook(ctx: &Ctx, metric: u32, f: impl Fn(noise::Cell) -> f32 + Sync) -> CookResult { - let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| f(cellular(u * sc, v * sc, sc as i32, dis, metric, s)).clamp(0.0, 1.0))]) -} - -fn cells1(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 0, |c| 1.0 - c.f1 * 1.2) -} - -fn cells2(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 0, |c| ((c.f2 - c.f1) * 2.5).min(1.0)) -} - -fn cells3(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 0, |c| c.id) -} - -fn cells4(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 2, |c| 1.0 - c.f1 * 1.6) -} - -fn crystal1(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, 1.0, 0, s); - (c.id * 0.6 + (c.f2 - c.f1).min(0.4) + 0.1).clamp(0.0, 1.0) - })]) -} - -fn crystal2(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, 1.0, 1, s); - (c.id * 0.7 + (1.0 - c.f1).max(0.0) * 0.3).clamp(0.0, 1.0) - })]) -} - -fn dirt(ctx: &Ctx) -> CookResult { - let (sc, d, s) = (scale(ctx), ctx.f("density"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let base = fbm(u, v, sc, 6, 0.55, s); - let spots = 1.0 - cellular(u * sc * 4.0, v * sc * 4.0, (sc * 4.0) as i32, 1.0, 0, s ^ 9).f1; - let t = 1.0 - d; - (((base * 0.7 + spots * 0.3) - t * 0.6) * 3.0).clamp(0.0, 1.0) - })]) -} - -fn dust(ctx: &Ctx) -> CookResult { - let (d, s) = (ctx.f("density"), ctx.seed); - let img = Image::gray(ctx.w, ctx.h, |x, y| if noise::rand2(x as i32, y as i32, s) < d { 0.5 + 0.5 * noise::rand2(y as i32, x as i32, s ^ 3) } else { 0.0 }); - let sigma = ctx.f("size") * ctx.w as f32 / 1024.0; - let b = ops::gaussian(&img, sigma, ctx.tile); - let gain = 1.0 + sigma * sigma * 4.0; - Ok(vec![b.map(Kind::Gray, |p| [(p[0] * gain).min(1.0), 0.0, 0.0, 0.0])]) -} - -fn fractal_sum(ctx: &Ctx) -> CookResult { - let (sc, o, r, s) = (scale(ctx), ctx.i("octaves").clamp(1, 12) as u32, ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, o, r, s))]) -} - -fn fur(ctx: &Ctx) -> CookResult { - let s = ctx.seed; - let density = ctx.f("scale").clamp(0.1, 4.0); - let img = Image::gray(ctx.w, ctx.h, |x, y| { - let r = rand2(x as i32, y as i32, s); - if r < 0.15 * density { rand2(y as i32, x as i32, s ^ 5) } else { 0.0 } - }); - let len = ctx.f("length") * ctx.w as f32 / 256.0; - let (dx, dy) = ((ctx.f("angle") * std::f32::consts::TAU).cos(), -(ctx.f("angle") * std::f32::consts::TAU).sin()); - let n = (len.ceil() as i32).clamp(1, 256); - let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let mut acc = 0.0; - for i in 0..=n { - let t = i as f32 / n as f32 * len; - acc += img.sample_nearest(u - dx * t * iw, v - dy * t * ih, ctx.tile)[0] * (1.0 - i as f32 / (n + 1) as f32); - } - [(acc * 2.5 / (n as f32).sqrt()).min(1.0), 0.0, 0.0, 0.0] - })]) -} - -fn gaussian_noise(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let a = value(u * sc, v * sc, sc as i32, s); - let b = value(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 1); - (a * 0.7 + b * 0.3).clamp(0.0, 1.0) - })]) -} - -fn grunge(ctx: &Ctx, f: impl Fn(f32, f32, f32, u32) -> f32 + Sync) -> CookResult { - let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(f(u, v, sc, s), c))]) -} - -fn grunge1(ctx: &Ctx) -> CookResult { - grunge(ctx, |u, v, sc, s| { - let a = fbm(u, v, sc, 7, 0.6, s); - let b = 1.0 - cellular(u * sc * 3.0, v * sc * 3.0, (sc * 3.0) as i32, 1.0, 0, s ^ 4).f1; - a * 0.75 + b * 0.25 - }) -} - -fn grunge2(ctx: &Ctx) -> CookResult { - grunge(ctx, |u, v, sc, s| { - let a = fbm(u, v, sc, 8, 0.65, s); - let speck = if rand2((u * 512.0) as i32, (v * 512.0) as i32, s ^ 8) > 0.9 { 0.25 } else { 0.0 }; - (a - speck).clamp(0.0, 1.0) - }) -} - -fn grunge3(ctx: &Ctx) -> CookResult { - grunge(ctx, |u, v, sc, s| { - let streak = value(u * sc * 8.0, v * sc * 0.5, (sc * 8.0) as i32, s); - let a = fbm(u, v, sc, 6, 0.55, s ^ 2); - streak * 0.5 + a * 0.5 - }) -} - -fn liquid(ctx: &Ctx) -> CookResult { - let (sc, w, s) = (scale(ctx), ctx.f("warp"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = fbm(u, v, sc, 4, 0.5, s) - 0.5; - let qy = fbm(u + 0.37, v + 0.71, sc, 4, 0.5, s ^ 3) - 0.5; - fbm(u + qx * w, v + qy * w, sc, 5, 0.5, s ^ 7) - })]) -} - -fn moisture(ctx: &Ctx) -> CookResult { - let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let a = fbm(u, v, sc, 6, 0.5, s); - let b = (perlin(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 6)).abs(); - contrast(a * 0.8 + (1.0 - b) * 0.2, c) - })]) -} - -fn perlin_noise(ctx: &Ctx) -> CookResult { - let (sc, d, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let (wu, wv) = if d > 0.0 { ((perlin(u * 3.0, v * 3.0, 3, s ^ 1)) * d * 0.1, (perlin(u * 3.0, v * 3.0, 3, s ^ 2)) * d * 0.1) } else { (0.0, 0.0) }; - (perlin((u + wu) * sc, (v + wv) * sc, sc as i32, s) * 0.5 + 0.5).clamp(0.0, 1.0) - })]) -} - -fn plasma(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - let tau = std::f32::consts::TAU; - Ok(vec![ctx.gen_gray(|u, v| { - let n = fbm(u, v, sc, 3, 0.5, s) * 2.0; - let a = (u * tau * sc + n * 3.0).sin() + (v * tau * sc + n * 2.0).sin() + ((u + v) * tau * sc.round() + n).sin(); - (a / 6.0 + 0.5).clamp(0.0, 1.0) - })]) -} - -fn turbulence(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - // A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN. - Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())]) -} - -fn creased(ctx: &Ctx) -> CookResult { - let (sc, r, w, s) = (scale(ctx), ctx.f("roughness"), ctx.f("warp"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = fbm(u, v, sc, 3, 0.5, s ^ 11) - 0.5; - ridged(u + q * w * 0.3, v - q * w * 0.3, sc, 6, r, s) - })]) -} - -fn clouds1(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, 8, r, s))]) -} - -fn clouds2(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5; - fbm(u + q * 0.35, v + q * 0.35, sc, 8, r, s) - })]) -} - -fn clouds3(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 9, r, s), 0.35))]) -} - -fn voronoi(ctx: &Ctx) -> CookResult { - let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); - let (metric, style) = (ctx.i("metric").clamp(0, 2) as u32, ctx.i("style")); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, dis, metric, s); - match style { - 0 => c.f1.min(1.0), - 1 => (c.f2 * 0.8).min(1.0), - 3 => c.id, - _ => ((c.f2 - c.f1) * 2.0).min(1.0), - } - })]) -} - -fn white_noise(ctx: &Ctx) -> CookResult { - let s = ctx.seed; - Ok(vec![if ctx.i("mode") == 1 { - Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - [rand2(x as i32, y as i32, s), rand2(x as i32, y as i32, s ^ 1), rand2(x as i32, y as i32, s ^ 2), 1.0] - }) - } else { - Image::gray(ctx.w, ctx.h, |x, y| rand2(x as i32, y as i32, s)) - }]) -} diff --git a/crates/nodes/src/image_input.rs b/crates/nodes/src/image_input.rs new file mode 100644 index 00000000..c545687e --- /dev/null +++ b/crates/nodes/src/image_input.rs @@ -0,0 +1,9 @@ +pub const MAX_IMAGE_INPUTS: usize = 256; + +pub fn image_input_prefix(definition: &str) -> Option<&'static str> { + match definition { + "fx_map" => Some("pattern"), + "pixel_processor" | "value_processor" => Some("input"), + _ => None, + } +} diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index a30494ac..6548a375 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -1,193 +1,37 @@ -//! # materialcraft-nodes -//! -//! The node library, L1: every node's definition (ports, parameters, library category) and its -//! CPU implementation. A cook is a pure function of its inputs, resolved parameters, size, seed -//! and tiling ([`Ctx`]), so every node is testable on its own and identical in the app, the CLI, -//! the MCP server and the browser. Noises tile seamlessly. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod atomic; pub mod catalog; -pub mod filters; -pub mod filters_extra; -pub mod filters_more; -pub mod flood_fill; pub mod function; -pub mod fx_map; -pub mod generators; -pub mod material; -pub mod material_more; -pub mod noise; -pub mod noise3d; -pub mod noises_more; pub mod ops; -pub mod patterns; -pub mod patterns_more; -pub mod svg; -pub mod text; -pub mod weathering; +pub mod pattern; +mod raster; -pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, clamp_params, find, resolve_params}; +mod cook_context; +mod image_input; +mod node_definition; +mod node_definition_builder; +mod output_value_type; +mod parameter; +mod parameter_definition; +mod port_definition; +mod port_kind; +mod random; + +pub use catalog::{catalog, categories, find}; +pub use cook_context::CookContext; +pub use image_input::{MAX_IMAGE_INPUTS, image_input_prefix}; +pub use node_definition::NodeDefinition; +pub(crate) use node_definition_builder::node; +pub use output_value_type::output_value_type; +pub use parameter::{clamp_params, resolve_params}; +pub use parameter_definition::ParameterDefinition; +pub use port_definition::PortDefinition; +pub use port_kind::PortKind; + +pub type CookResult = Result<Vec<materialcraft_image::Image>, String>; +pub type Cook = fn(&CookContext<'_>) -> CookResult; #[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use materialcraft_core::Value; - use materialcraft_image::{Image, Kind}; - - use super::*; - - fn cook(def: &NodeDef, inputs: &[Option<Image>], size: u32) -> CookResult { - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: size, h: size, seed: 7, tile: true, inputs, params: ¶ms, resource: &no_res, vars: &vars }; - (def.cook)(&ctx) - } - - /// Every node cooks with no inputs and with hostile-sized inputs, returns as many images as - /// it has outputs, at the requested size, with finite values. - #[test] - fn every_node_cooks() { - let ids: Vec<&str> = catalog().iter().map(|d| d.id).collect(); - let mut seen = std::collections::BTreeSet::new(); - for id in &ids { - assert!(seen.insert(*id), "duplicate node id {id}"); - } - let odd = Image::generate(5, 3, Kind::Color, |x, y| [x as f32 / 4.0, y as f32 / 2.0, 0.5, 1.0]); - for def in catalog() { - if def.id == "graph_instance" { - continue; - } - for inputs in [vec![None; def.inputs.len()], vec![Some(odd.clone()); def.inputs.len()]] { - let out = cook(def, &inputs, 32).unwrap_or_else(|e| panic!("{}: {e}", def.id)); - assert_eq!(out.len(), def.outputs.len().max(1), "{}", def.id); - for img in &out { - assert_eq!((img.w, img.h), (32, 32), "{}", def.id); - assert!(img.data.iter().all(|v| v.is_finite()), "{} produced a non-finite value", def.id); - } - } - } - assert!(catalog().len() >= 200, "{} nodes", catalog().len()); - } - - /// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN): - /// the hard limits keep the cook bounded, finite and the right size. - #[test] - fn every_node_survives_hostile_params() { - use std::time::{Duration, Instant}; - - let mut slow: Vec<(String, Duration)> = Vec::new(); - let total = Instant::now(); - for def in catalog() { - if def.id == "graph_instance" { - continue; - } - for p in &def.params { - for h in [1e30_f32, -1e30, f32::NAN] { - let v = match p.default { - Value::Float(_) => Value::Float(h), - Value::Int(_) => Value::Int(h as i32), - Value::Float2(_) => Value::Float2([h, h]), - Value::Enum(_) => Value::Enum(h as u32), - _ => continue, - }; - let mut params = resolve_params(def, &BTreeMap::from([(p.id.to_string(), v)])); - clamp_params(def, &mut params); - let inputs = vec![None; def.inputs.len()]; - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: 16, h: 16, seed: 7, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - let t = Instant::now(); - let out = (def.cook)(&ctx).unwrap_or_else(|e| panic!("{}.{}={h}: {e}", def.id, p.id)); - let dt = t.elapsed(); - assert!(dt < Duration::from_secs(2), "{}.{}={h} took {dt:?}", def.id, p.id); - if dt > Duration::from_millis(250) { - slow.push((format!("{}.{}={h}", def.id, p.id), dt)); - } - 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); - } - } - } - } - eprintln!("hostile params: total {:?}; cooks over 250 ms: {slow:?}", total.elapsed()); - } - - #[test] - fn noises_tile() { - for id in [ - "perlin_noise", - "clouds_1", - "cells_1", - "voronoi", - "brick_generator", - "tile_generator", - "hexagons", - "value_noise", - "ridged_fractal", - "voronoi_fractal", - "cells_fractal", - "directional_noise", - "fibers", - "messy_fibers", - "leather", - "microscope", - "gaussian_spots", - "crackle", - "sand_dunes", - "wood_grain", - "marble", - "stones", - "ripples", - "concrete", - "bark", - "grid_lines", - "dots_grid", - "chevron", - "basketweave", - "tread_plate", - "fx_map", - "shape_splatter", - "perlin_noise_3d", - "simplex_noise_3d", - "worley_noise_3d", - "cracks", - "paint_strokes", - "scratches_generator", - "rust", - "moss", - ] { - let def = find(id).unwrap(); - let img = &cook(def, &[], 64).unwrap()[0]; - // The jump across the wrap is no larger than typical neighbouring differences. - let mut seam = 0.0f32; - let mut inner = 0.0f32; - for y in 0..64 { - seam += (img.get(63, y, false)[0] - img.get(0, y, false)[0]).abs(); - inner += (img.get(31, y, false)[0] - img.get(32, y, false)[0]).abs(); - } - assert!(seam <= inner * 3.0 + 0.5, "{id}: seam {seam} vs inner {inner}"); - } - } - - #[test] - fn blend_and_levels_math() { - let fg = Image::filled(4, 4, Kind::Gray, [0.25; 4]); - let bg = Image::filled(4, 4, Kind::Gray, [0.5; 4]); - let def = find("blend").unwrap(); - let mut params = resolve_params(def, &BTreeMap::new()); - params.insert("mode".into(), materialcraft_core::Value::Enum(3)); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = [Some(fg), Some(bg), None]; - let ctx = Ctx { w: 4, h: 4, seed: 0, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - let out = (def.cook)(&ctx).unwrap(); - 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); - } -} +mod tests; diff --git a/crates/nodes/src/material.rs b/crates/nodes/src/material.rs deleted file mode 100644 index 88252900..00000000 --- a/crates/nodes/src/material.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Material filters: nodes that make or process whole PBR materials (several outputs). - -use materialcraft_image::{Image, Kind, linear_to_srgb, srgb_to_linear}; - -use crate::atomic::height_to_normal; -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::ops; - -const PBR: &str = "Material filters/PBR utilities"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("pbr_base_material", "PBR Base Material", PBR) - .desc("A uniform PBR material: base color, normal, roughness, metallic, height and ambient occlusion.") - .generator() - .color("base_color", "Base color", [0.5, 0.5, 0.5, 1.0]) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("metallic", "Metallic", 0.0, 0.0, 1.0) - .float("height", "Height", 0.5, 0.0, 1.0) - .float("ao", "Ambient occlusion", 1.0, 0.0, 1.0) - .output("base_color", "Base color", PortKind::Color) - .output("normal", "Normal", PortKind::Color) - .output("roughness", "Roughness", PortKind::Gray) - .output("metallic", "Metallic", PortKind::Gray) - .output("height", "Height", PortKind::Gray) - .output("ambient_occlusion", "Ambient occlusion", PortKind::Gray) - .cook(pbr_base), - node("height_normal_ao", "Height to Normal and AO", PBR) - .desc("A normal map and an ambient occlusion map from one height map.") - .gray_in("height", "Height") - .float("normal_intensity", "Normal intensity", 1.0, 0.0, 10.0) - .float("ao_spread", "AO spreading", 0.15, 0.0, 1.0) - .float("ao_depth", "AO depth", 0.5, 0.0, 1.0) - .output("normal", "Normal", PortKind::Color) - .output("ambient_occlusion", "Ambient occlusion", PortKind::Gray) - .cook(height_normal_ao), - node("albedo_safe", "Albedo Safe Color", PBR) - .desc("Keeps base colors inside the physically plausible range (sRGB 30-240).") - .color_in("input", "Base color") - .color_out() - .cook(albedo_safe), - node("metallic_mask", "Metallic From Mask", PBR) - .desc("Turns a mask into a clean metallic map (fully metallic or not).") - .gray_in("input", "Mask") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .gray_out() - .cook(metallic_mask), - ] -} - -fn pbr_base(ctx: &Ctx) -> CookResult { - let (w, h) = (ctx.w, ctx.h); - let g = |v: f32| Image::filled(w, h, Kind::Gray, [v; 4]); - Ok(vec![ - Image::filled(w, h, Kind::Color, ctx.v4("base_color")), - Image::filled(w, h, Kind::Color, [0.5, 0.5, 1.0, 1.0]), - g(ctx.f("roughness")), - g(ctx.f("metallic")), - g(ctx.f("height")), - g(ctx.f("ao")), - ]) -} - -fn height_normal_ao(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.5); - let n = height_to_normal(&h, ctx.f("normal_intensity") * ctx.w as f32 / 32.0, false, ctx.tile, false); - let spread = ctx.f("ao_spread").max(0.001) * ctx.w as f32 * 0.25; - let wide = ops::gaussian(&h, spread, ctx.tile); - let depth = ctx.f("ao_depth"); - let ao = Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let i = (y * ctx.w + x) as usize; - [(1.0 - (wide.data[i] - h.data[i]).max(0.0) * depth * 6.0).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - }); - Ok(vec![n, ao]) -} - -fn albedo_safe(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let (lo, hi) = (30.0 / 255.0, 240.0 / 255.0); - Ok(vec![img.map(Kind::Color, |p| { - let f = |v: f32| srgb_to_linear(linear_to_srgb(v).clamp(lo, hi)); - [f(p[0]), f(p[1]), f(p[2]), p[3]] - })]) -} - -fn metallic_mask(ctx: &Ctx) -> CookResult { - let t = ctx.f("threshold"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |p| [if p[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])]) -} diff --git a/crates/nodes/src/material_more.rs b/crates/nodes/src/material_more.rs deleted file mode 100644 index 6206b35c..00000000 --- a/crates/nodes/src/material_more.rs +++ /dev/null @@ -1,274 +0,0 @@ -//! More material filters: blending whole PBR materials (by mask or by height), weathering masks -//! (edge wear, dirt, dust) and base color utilities. - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{B, CookResult, Ctx, NodeDef, PortKind, node}; -use crate::filters_more::{pack, unpack}; -use crate::noise::fbm; -use crate::noises_more::smoothstep; -use crate::ops; - -const MAT_BLEND: &str = "Material filters/Blending"; -const WEATHER: &str = "Material filters/Weathering"; -const PBR: &str = "Material filters/PBR utilities"; - -/// The channels of a blended material: kind and default (unconnected) value. -const KINDS: [(PortKind, [f32; 4]); 5] = [ - (PortKind::Color, [0.5, 0.5, 0.5, 1.0]), - (PortKind::Color, [0.5, 0.5, 1.0, 1.0]), - (PortKind::Gray, [0.5; 4]), - (PortKind::Gray, [0.0; 4]), - (PortKind::Gray, [0.5; 4]), -]; -const IN_1: [(&str, &str); 5] = - [("base_color_1", "Base color 1"), ("normal_1", "Normal 1"), ("roughness_1", "Roughness 1"), ("metallic_1", "Metallic 1"), ("height_1", "Height 1")]; -const IN_2: [(&str, &str); 5] = - [("base_color_2", "Base color 2"), ("normal_2", "Normal 2"), ("roughness_2", "Roughness 2"), ("metallic_2", "Metallic 2"), ("height_2", "Height 2")]; -const OUT: [(&str, &str); 5] = [("base_color", "Base color"), ("normal", "Normal"), ("roughness", "Roughness"), ("metallic", "Metallic"), ("height", "Height")]; - -/// Inputs for two materials, then the blended material's outputs. -fn material_ports(mut b: B) -> B { - for set in [IN_1, IN_2] { - for ((id, label), (kind, _)) in set.into_iter().zip(KINDS) { - b = b.input(id, label, kind); - } - } - for ((id, label), (kind, _)) in OUT.into_iter().zip(KINDS) { - b = b.output(id, label, kind); - } - b -} - -fn kind_of(k: PortKind) -> Kind { - if k == PortKind::Color { Kind::Color } else { Kind::Gray } -} - -/// Material `slot` (0 or 1), channel `c`, at the output size. -fn channel(ctx: &Ctx, slot: usize, c: usize) -> Image { - let (pk, def) = KINDS[c]; - let kind = kind_of(pk); - ctx.any_or(slot * 5 + c, kind, def).to_kind(kind) -} - -/// Blend the two input materials by `t` per pixel (0 = material 1); normals are renormalized. -fn mix_materials(ctx: &Ctx, t: &[f32]) -> Vec<Image> { - (0..5) - .map(|c| { - let (a, b) = (channel(ctx, 0, c), channel(ctx, 1, c)); - Image::generate(ctx.w, ctx.h, a.kind, |x, y| { - let t = t.get((y * ctx.w + x) as usize).copied().unwrap_or(0.0); - let (p, q) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - let mut o: [f32; 4] = std::array::from_fn(|k| p[k] + (q[k] - p[k]) * t); - if c == 1 { - let (n1, n2) = (unpack(p), unpack(q)); - o = pack(std::array::from_fn(|k| n1[k] + (n2[k] - n1[k]) * t), o[3]); - } - o - }) - }) - .collect() -} - -/// Weathering parameters shared by the mask nodes. -fn weather_params(b: B) -> B { - b.float("amount", "Amount", 0.5, 0.0, 1.0) - .float("noise_scale", "Noise scale", 8.0, 1.0, 64.0) - .float("noise_amount", "Noise amount", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.6, 0.0, 1.0) -} - -/// A weathering mask: `base(i)` (0..1, where the effect belongs) broken up by fractal noise and -/// thresholded by the amount. -fn weather(ctx: &Ctx, base: impl Fn(usize) -> f32 + Sync) -> Image { - let (amt, ns, na, s) = (ctx.f("amount"), ctx.f("noise_scale").max(1.0).round(), ctx.f("noise_amount"), ctx.seed); - let soft = (1.0 - ctx.f("contrast")) * 0.5 + 0.01; - Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let i = ((v * ctx.h as f32) as usize).min((ctx.h as usize).saturating_sub(1)) * ctx.w as usize - + ((u * ctx.w as f32) as usize).min((ctx.w as usize).saturating_sub(1)); - let val = base(i) - 2.0 * na * (1.0 - fbm(u, v, ns, 6, 0.6, s)); - [smoothstep(1.0 - amt - soft, 1.0 - amt + soft, val), 0.0, 0.0, 0.0] - }) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - material_ports(node("material_blend", "Material Blend", MAT_BLEND)) - .desc("Blends two whole PBR materials by a mask (white = material 2).") - .gray_in("mask", "Mask") - .float("opacity", "Opacity", 1.0, 0.0, 1.0) - .cook(material_blend), - material_ports(node("material_height_blend", "Material Height Blend", MAT_BLEND)) - .desc("Blends two whole PBR materials by their heights: the higher one shows, with a soft transition.") - .float("height_offset", "Height offset", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.9, 0.0, 1.0) - .output("mask", "Mask", PortKind::Gray) - .cook(material_height_blend), - weather_params( - node("edge_wear", "Edge Wear", WEATHER) - .desc("A mask of worn, exposed edges from the convex areas of a height map (or a curvature map), broken up by noise.") - .gray_in("height", "Height") - .gray_in("curvature", "Curvature (optional)") - .float("width", "Edge width", 4.0, 0.25, 64.0), - ) - .gray_out() - .cook(edge_wear), - weather_params( - node("dirt_mask", "Dirt Mask", WEATHER) - .desc("A mask of dirt gathering in cavities of a height map (and dark ambient occlusion), broken up by noise.") - .gray_in("height", "Height") - .gray_in("ao", "Ambient occlusion (optional)") - .float("spread", "Spread", 16.0, 0.5, 128.0), - ) - .gray_out() - .cook(dirt_mask), - weather_params( - node("dust_mask", "Dust Mask", WEATHER) - .desc("A mask of dust settling on surfaces facing a direction (from a normal map) and on flat areas.") - .color_in("normal", "Normal") - .angle("direction", "Up direction", 0.25) - .float("flat", "On flat areas", 0.3, 0.0, 1.0), - ) - .gray_out() - .cook(dust_mask), - node("material_color_adjust", "Material Color Adjust", PBR) - .desc("Hue, saturation and value of a base color, optionally through a mask.") - .color_in("input", "Base color") - .gray_in("mask", "Mask") - .float("hue", "Hue", 0.0, -0.5, 0.5) - .float("saturation", "Saturation", 0.0, -1.0, 1.0) - .float("value", "Value", 0.0, -1.0, 1.0) - .color_out() - .cook(material_color_adjust), - node("metal_base_color", "Metal Base Color", PBR) - .desc("The measured base color (linear reflectance) of a common metal, with metallic = 1.") - .generator() - .choice("metal", "Metal", &["Iron", "Silver", "Aluminum", "Gold", "Copper", "Chromium", "Nickel", "Titanium", "Cobalt", "Platinum"], 0) - .output("base_color", "Base color", PortKind::Color) - .output("metallic", "Metallic", PortKind::Gray) - .cook(metal_base_color), - ] -} - -fn material_blend(ctx: &Ctx) -> CookResult { - let op = ctx.f("opacity"); - let m = ctx.gray_or(10, 1.0); - let t: Vec<f32> = m.data.iter().map(|v| (v * op).clamp(0.0, 1.0)).collect(); - Ok(mix_materials(ctx, &t)) -} - -fn material_height_blend(ctx: &Ctx) -> CookResult { - let (h1, h2) = (channel(ctx, 0, 4), channel(ctx, 1, 4)); - let (off, c) = (ctx.f("height_offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999)); - let soft = (1.0 - c) * 0.5 + 1e-4; - let t: Vec<f32> = h1.data.iter().zip(h2.data.iter()).map(|(a, b)| ((b + off - a) / soft * 0.5 + 0.5).clamp(0.0, 1.0)).collect(); - let mut out = mix_materials(ctx, &t); - out.push(ops::gray_from(ctx.w, ctx.h, t)); - Ok(out) -} - -fn edge_wear(ctx: &Ctx) -> CookResult { - let edge: Vec<f32> = match ctx.sized(1) { - Some(c) => c.to_gray().data.iter().map(|v| ((v - 0.5) * 2.0).clamp(0.0, 1.0)).collect(), - None => { - let h = ctx.gray_or(0, 0.0); - let wide = ops::gaussian(&h, ctx.f("width") * ctx.w as f32 / 256.0, ctx.tile); - h.data.iter().zip(wide.data.iter()).map(|(a, b)| ((a - b) * 4.0).clamp(0.0, 1.0)).collect() - } - }; - Ok(vec![weather(ctx, |i| edge.get(i).copied().unwrap_or(0.0))]) -} - -fn dirt_mask(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let wide = ops::gaussian(&h, ctx.f("spread") * ctx.w as f32 / 256.0, ctx.tile); - let ao = ctx.sized(1).map(|a| a.to_gray()); - let cav: Vec<f32> = (0..h.data.len()) - .map(|i| { - let c = ((wide.data[i] - h.data[i]) * 4.0).clamp(0.0, 1.0); - ao.as_ref().and_then(|a| a.data.get(i)).map_or(c, |a| c.max(1.0 - a)) - }) - .collect(); - Ok(vec![weather(ctx, |i| cav.get(i).copied().unwrap_or(0.0))]) -} - -fn dust_mask(ctx: &Ctx) -> CookResult { - let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color(); - let (s, c) = (ctx.f("direction") * std::f32::consts::TAU).sin_cos(); - let flat = ctx.f("flat"); - let base: Vec<f32> = n - .data - .chunks(4) - .map(|p| { - let v = unpack([p[0], p[1], p[2], 1.0]); - ((v[0] * c + v[1] * s) * 3.0 + flat * ((v[2] - 0.8) * 5.0).max(0.0)).clamp(0.0, 1.0) - }) - .collect(); - Ok(vec![weather(ctx, |i| base.get(i).copied().unwrap_or(0.0))]) -} - -fn material_color_adjust(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let m = ctx.gray_or(1, 1.0); - let (dh, ds, dv) = (ctx.f("hue"), ctx.f("saturation"), ctx.f("value")); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let p = img.get(x as i64, y as i64, false); - let t = m.get_gray(x as i64, y as i64, false); - let hsl = ops::rgb_to_hsl(p); - let q = ops::hsl_to_rgb(hsl[0] + dh, (hsl[1] * (1.0 + ds)).clamp(0.0, 1.0), (hsl[2] * (1.0 + dv)).max(0.0)); - [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t, p[3]] - })]) -} - -/// Linear base colors (normal-incidence reflectance) of metals, from published measurements. -const METALS: [[f32; 3]; 10] = [ - [0.560, 0.570, 0.580], - [0.972, 0.960, 0.915], - [0.913, 0.922, 0.924], - [1.000, 0.766, 0.336], - [0.955, 0.638, 0.538], - [0.550, 0.556, 0.554], - [0.660, 0.609, 0.526], - [0.542, 0.497, 0.449], - [0.662, 0.655, 0.634], - [0.672, 0.637, 0.585], -]; - -fn metal_base_color(ctx: &Ctx) -> CookResult { - let c = METALS.get(ctx.i("metal").max(0) as usize).copied().unwrap_or(METALS[0]); - Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, [c[0], c[1], c[2], 1.0]), Image::filled(ctx.w, ctx.h, Kind::Gray, [1.0; 4])]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use materialcraft_image::{Image, Kind}; - - use crate::{Ctx, find, resolve_params}; - - #[test] - fn material_blend_picks_material_2_under_white_mask() { - let def = find("material_blend").unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let red = Image::filled(8, 8, Kind::Color, [1.0, 0.0, 0.0, 1.0]); - let tilted = Image::filled(8, 8, Kind::Color, [0.8, 0.5, 0.9, 1.0]); - let mut inputs = vec![None; def.inputs.len()]; - inputs[5] = Some(red); - inputs[6] = Some(tilted); - inputs[7] = Some(Image::filled(8, 8, Kind::Gray, [0.1; 4])); - inputs[10] = Some(Image::gray(8, 8, |x, _| if x < 4 { 0.0 } else { 1.0 })); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: 8, h: 8, seed: 0, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - let out = (def.cook)(&ctx).unwrap(); - assert_eq!(out.len(), 5); - assert_eq!(out[0].get(6, 2, false), [1.0, 0.0, 0.0, 1.0], "white mask: material 2's base color"); - assert_eq!(out[0].get(1, 2, false), [0.5, 0.5, 0.5, 1.0], "black mask: material 1 (default gray)"); - assert!((out[2].get(6, 2, false)[0] - 0.1).abs() < 1e-6); - let n = out[1].get(6, 2, false); - let len = ((n[0] * 2.0 - 1.0).powi(2) + (n[1] * 2.0 - 1.0).powi(2) + (n[2] * 2.0 - 1.0).powi(2)).sqrt(); - assert!((len - 1.0).abs() < 1e-4, "blended normals are unit length"); - assert!(n[0] > 0.7, "material 2's normal: {n:?}"); - } -} diff --git a/crates/nodes/src/node_definition.rs b/crates/nodes/src/node_definition.rs new file mode 100644 index 00000000..d8170c6d --- /dev/null +++ b/crates/nodes/src/node_definition.rs @@ -0,0 +1,38 @@ +use crate::{Cook, ParameterDefinition, PortDefinition}; + +/// A node in the library +#[derive(Clone, Debug)] +pub struct NodeDefinition { + pub id: &'static str, + pub label: &'static str, + /// Library path, e.g. `Filters/Blurs`, `Texture generators/Noises`, `Atomic nodes` + pub category: &'static str, + pub description: &'static str, + pub inputs: Vec<PortDefinition>, + pub outputs: Vec<PortDefinition>, + pub params: Vec<ParameterDefinition>, + /// A generator takes its size from the graph, not from an input + pub generator: bool, + /// One of the engine's built-in ("atomic") nodes (shown with a grey header) + pub atomic: bool, + pub cook: Cook, +} + +impl NodeDefinition { + pub fn param(&self, id: &str) -> Option<&ParameterDefinition> { + self.params.iter().find(|p| p.id == id) + } + + pub fn input_index(&self, id: &str) -> Option<usize> { + self.inputs.iter().position(|p| p.id == id) + } + + pub fn output_index(&self, id: &str) -> Option<usize> { + self.outputs.iter().position(|p| p.id == id) + } + + /// The last path element of the category ("Blurs") + pub fn group(&self) -> &'static str { + self.category.rsplit('/').next().unwrap_or(self.category) + } +} diff --git a/crates/nodes/src/node_definition_builder.rs b/crates/nodes/src/node_definition_builder.rs new file mode 100644 index 00000000..52697c4b --- /dev/null +++ b/crates/nodes/src/node_definition_builder.rs @@ -0,0 +1,155 @@ +use crate::{Cook, CookContext, CookResult, NodeDefinition, ParameterDefinition, PortDefinition, PortKind}; +use materialcraft_core::{Curve, FunctionGraph, Gradient, PatternGraph, Value}; + +pub(crate) fn no_cook(_: &CookContext) -> CookResult { + Err("this node is cooked by the graph evaluator".into()) +} + +/// Builder for [`NodeDefinition`]s +pub(crate) struct NodeDefinitionBuilder(NodeDefinition); + +pub(crate) fn node(id: &'static str, label: &'static str, category: &'static str) -> NodeDefinitionBuilder { + NodeDefinitionBuilder(NodeDefinition { + id, + label, + category, + description: "", + inputs: Vec::new(), + outputs: Vec::new(), + params: Vec::new(), + generator: false, + atomic: false, + cook: no_cook, + }) +} + +impl NodeDefinitionBuilder { + pub fn desc(mut self, d: &'static str) -> NodeDefinitionBuilder { + self.0.description = d; + self + } + + pub fn atomic(mut self) -> NodeDefinitionBuilder { + self.0.atomic = true; + self + } + + pub fn generator(mut self) -> NodeDefinitionBuilder { + self.0.generator = true; + self + } + + pub fn input(mut self, id: &'static str, label: &'static str, kind: PortKind) -> NodeDefinitionBuilder { + self.0.inputs.push(PortDefinition { id, label, kind }); + self + } + + pub fn gray_in(self, id: &'static str, label: &'static str) -> NodeDefinitionBuilder { + self.input(id, label, PortKind::Gray) + } + + pub fn color_in(self, id: &'static str, label: &'static str) -> NodeDefinitionBuilder { + self.input(id, label, PortKind::Color) + } + + pub fn any_in(self, id: &'static str, label: &'static str) -> NodeDefinitionBuilder { + self.input(id, label, PortKind::Any) + } + + pub fn output(mut self, id: &'static str, label: &'static str, kind: PortKind) -> NodeDefinitionBuilder { + self.0.outputs.push(PortDefinition { id, label, kind }); + self + } + + pub fn gray_out(self) -> NodeDefinitionBuilder { + self.output("output", "Output", PortKind::Gray) + } + + pub fn color_out(self) -> NodeDefinitionBuilder { + self.output("output", "Output", PortKind::Color) + } + + pub fn any_out(self) -> NodeDefinitionBuilder { + self.output("output", "Output", PortKind::Any) + } + fn push(mut self, id: &'static str, label: &'static str, default: Value, min: f32, max: f32) -> NodeDefinitionBuilder { + self.0.params.push(ParameterDefinition { id, label, default, min, max, options: &[], group: "", angle: false, resource: false }); + self + } + fn last(&mut self) -> Option<&mut ParameterDefinition> { + self.0.params.last_mut() + } + + pub fn float(self, id: &'static str, label: &'static str, d: f32, min: f32, max: f32) -> NodeDefinitionBuilder { + self.push(id, label, Value::Float(d), min, max) + } + + pub fn angle(mut self, id: &'static str, label: &'static str, d: f32) -> NodeDefinitionBuilder { + self = self.push(id, label, Value::Float(d), -1.0, 1.0); + if let Some(p) = self.last() { + p.angle = true; + } + self + } + + pub fn int(self, id: &'static str, label: &'static str, d: i32, min: i32, max: i32) -> NodeDefinitionBuilder { + self.push(id, label, Value::Int(d), min as f32, max as f32) + } + + pub fn float2(self, id: &'static str, label: &'static str, d: [f32; 2], min: f32, max: f32) -> NodeDefinitionBuilder { + self.push(id, label, Value::Float2(d), min, max) + } + + pub fn float4(self, id: &'static str, label: &'static str, default: [f32; 4], min: f32, max: f32) -> NodeDefinitionBuilder { + self.push(id, label, Value::Float4(default), min, max) + } + + pub fn boolean(self, id: &'static str, label: &'static str, d: bool) -> NodeDefinitionBuilder { + self.push(id, label, Value::Bool(d), 0.0, 1.0) + } + + pub fn color(self, id: &'static str, label: &'static str, d: [f32; 4]) -> NodeDefinitionBuilder { + self.push(id, label, Value::Color(d), 0.0, 1.0) + } + + pub fn choice(mut self, id: &'static str, label: &'static str, options: &'static [&'static str], d: u32) -> NodeDefinitionBuilder { + self = self.push(id, label, Value::Enum(d), 0.0, options.len().saturating_sub(1) as f32); + if let Some(p) = self.last() { + p.options = options; + } + self + } + + pub fn text(self, id: &'static str, label: &'static str, d: &str) -> NodeDefinitionBuilder { + self.push(id, label, Value::Text(d.into()), 0.0, 0.0) + } + + pub fn resource(mut self, id: &'static str, label: &'static str) -> NodeDefinitionBuilder { + self = self.push(id, label, Value::Text(String::new()), 0.0, 0.0); + if let Some(p) = self.last() { + p.resource = true; + } + self + } + + pub fn curve(self, id: &'static str, label: &'static str) -> NodeDefinitionBuilder { + self.push(id, label, Value::Curve(Curve::default()), 0.0, 1.0) + } + + pub fn gradient(self, id: &'static str, label: &'static str, g: Gradient) -> NodeDefinitionBuilder { + self.push(id, label, Value::Gradient(g), 0.0, 1.0) + } + + pub fn function(self, id: &'static str, label: &'static str, g: FunctionGraph) -> NodeDefinitionBuilder { + self.push(id, label, Value::Function(Box::new(g)), 0.0, 0.0) + } + + pub fn pattern_graph(self, id: &'static str, label: &'static str, graph: PatternGraph) -> NodeDefinitionBuilder { + self.push(id, label, Value::PatternGraph(Box::new(graph)), 0.0, 0.0) + } + + pub fn cook(mut self, f: Cook) -> NodeDefinition { + self.0.cook = f; + self.0 + } +} diff --git a/crates/nodes/src/noise.rs b/crates/nodes/src/noise.rs deleted file mode 100644 index 95cd36d5..00000000 --- a/crates/nodes/src/noise.rs +++ /dev/null @@ -1,184 +0,0 @@ -//! Tileable noise primitives: integer hashing, value and gradient (Perlin) noise on a periodic -//! lattice, fractal sums and cellular (Worley) noise. Every function takes normalized coordinates -//! (0..1 across the image) and a period in cells, so whole-number scales tile seamlessly. - -/// A 32-bit integer hash (lowbias32 by Chris Wellons, public domain). -#[inline] -pub fn hash(mut x: u32) -> u32 { - x ^= x >> 16; - x = x.wrapping_mul(0x7feb_352d); - x ^= x >> 15; - x = x.wrapping_mul(0x846c_a68b); - x ^= x >> 16; - x -} - -#[inline] -pub fn hash3(x: i32, y: i32, seed: u32) -> u32 { - hash((x as u32).wrapping_mul(0x8da6_b343) ^ hash((y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f))) -} - -/// Uniform 0..1 from a lattice point. -#[inline] -pub fn rand2(x: i32, y: i32, seed: u32) -> f32 { - (hash3(x, y, seed) >> 8) as f32 / (1u32 << 24) as f32 -} - -/// Uniform 0..1 from an index. -#[inline] -pub fn rand1(i: u32, seed: u32) -> f32 { - (hash(i ^ hash(seed.wrapping_add(0x9e37_79b9))) >> 8) as f32 / (1u32 << 24) as f32 -} - -#[inline] -fn fade(t: f32) -> f32 { - t * t * t * (t * (t * 6.0 - 15.0) + 10.0) -} - -#[inline] -fn wrapi(i: i32, p: i32) -> i32 { - if p <= 0 { i } else { i.rem_euclid(p) } -} - -/// Value noise in 0..1, lattice period `p` cells (coordinates already scaled to cells). -pub fn value(x: f32, y: f32, p: i32, seed: u32) -> f32 { - let (x0, y0) = (x.floor(), y.floor()); - let (tx, ty) = (fade(x - x0), fade(y - y0)); - let (ix, iy) = (x0 as i32, y0 as i32); - let r = |i: i32, j: i32| rand2(wrapi(i, p), wrapi(j, p), seed); - let a = r(ix, iy) + (r(ix + 1, iy) - r(ix, iy)) * tx; - let b = r(ix, iy + 1) + (r(ix + 1, iy + 1) - r(ix, iy + 1)) * tx; - a + (b - a) * ty -} - -/// Gradient (Perlin) noise in about -1..1, lattice period `p` cells. -pub fn perlin(x: f32, y: f32, p: i32, seed: u32) -> f32 { - let (x0, y0) = (x.floor(), y.floor()); - let (fx, fy) = (x - x0, y - y0); - let (ix, iy) = (x0 as i32, y0 as i32); - let g = |i: i32, j: i32, dx: f32, dy: f32| { - let h = hash3(wrapi(i, p), wrapi(j, p), seed); - let a = (h >> 8) as f32 * (std::f32::consts::TAU / (1u32 << 24) as f32); - a.cos() * dx + a.sin() * dy - }; - let (u, v) = (fade(fx), fade(fy)); - let n00 = g(ix, iy, fx, fy); - let n10 = g(ix + 1, iy, fx - 1.0, fy); - let n01 = g(ix, iy + 1, fx, fy - 1.0); - let n11 = g(ix + 1, iy + 1, fx - 1.0, fy - 1.0); - let a = n00 + (n10 - n00) * u; - let b = n01 + (n11 - n01) * u; - (a + (b - a) * v) * std::f32::consts::SQRT_2 -} - -/// Fractal sum of Perlin noise in 0..1: `octaves` layers from `scale` cells, each `lacunarity` -/// (2) times finer and `gain` times weaker. Tileable when `scale` is whole. -pub fn fbm(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 { - let mut sum = 0.0; - let mut amp = 1.0; - let mut norm = 0.0; - let mut s = scale.max(1.0).round(); - for o in 0..octaves.clamp(1, 12) { - sum += perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 1013)) * amp; - norm += amp; - amp *= gain; - s *= 2.0; - } - (sum / norm.max(1e-6)) * 0.5 + 0.5 -} - -/// Ridged (creased) fractal: `1 - |perlin|` layers, 0..1. -pub fn ridged(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 { - let mut sum = 0.0; - let mut amp = 1.0; - let mut norm = 0.0; - let mut s = scale.max(1.0).round(); - for o in 0..octaves.clamp(1, 12) { - let n = 1.0 - perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 7919)).abs(); - sum += n * n * amp; - norm += amp; - amp *= gain; - s *= 2.0; - } - sum / norm.max(1e-6) -} - -/// Result of a cellular lookup: the nearest and second-nearest feature distances (in cells), -/// the nearest feature's random id (0..1) and its position (cells). -#[derive(Clone, Copy, Debug)] -pub struct Cell { - pub f1: f32, - pub f2: f32, - pub id: f32, - pub center: [f32; 2], -} - -/// Worley noise with one jittered feature point per cell (`jitter` 0..1), period `p` cells. -/// `metric`: 0 Euclidean, 1 Manhattan, 2 Chebyshev. -pub fn cellular(x: f32, y: f32, p: i32, jitter: f32, metric: u32, seed: u32) -> Cell { - let (ix, iy) = (x.floor() as i32, y.floor() as i32); - let mut f1 = f32::MAX; - let mut f2 = f32::MAX; - let mut id = 0.0; - let mut center = [0.0, 0.0]; - for j in -2..=2 { - for i in -2..=2 { - let (cx, cy) = (ix + i, iy + j); - let (wx, wy) = (wrapi(cx, p), wrapi(cy, p)); - let px = cx as f32 + 0.5 + (rand2(wx, wy, seed) - 0.5) * jitter; - let py = cy as f32 + 0.5 + (rand2(wx, wy, seed ^ 0x5bd1_e995) - 0.5) * jitter; - let (dx, dy) = (px - x, py - y); - let d = match metric { - 1 => dx.abs() + dy.abs(), - 2 => dx.abs().max(dy.abs()), - _ => (dx * dx + dy * dy).sqrt(), - }; - if d < f1 { - f2 = f1; - f1 = d; - id = rand2(wx, wy, seed ^ 0x2545_f491); - center = [px, py]; - } else if d < f2 { - f2 = d; - } - } - } - Cell { f1, f2, id, center } -} - -/// Gaussian-distributed sample (Box–Muller) from two uniforms. -pub fn gauss(u1: f32, u2: f32) -> f32 { - (-2.0 * u1.max(1e-7).ln()).sqrt() * (std::f32::consts::TAU * u2).cos() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn perlin_tiles_at_its_period() { - for k in 0..20 { - let y = k as f32 * 0.37; - let a = perlin(0.0, y, 4, 7); - let b = perlin(4.0, y, 4, 7); - assert!((a - b).abs() < 1e-5, "{a} {b}"); - } - let a = fbm(0.0, 0.3, 4.0, 5, 0.5, 1); - let b = fbm(1.0, 0.3, 4.0, 5, 0.5, 1); - assert!((a - b).abs() < 1e-4); - } - - #[test] - fn cellular_tiles_and_ranges() { - let a = cellular(0.1, 0.2, 5, 1.0, 0, 3).f1; - let b = cellular(5.1, 0.2, 5, 1.0, 0, 3).f1; - assert!((a - b).abs() < 1e-4); - assert!((0.0..1.5).contains(&a)); - } - - #[test] - fn rand_is_uniformish() { - let m: f32 = (0..10000).map(|i| rand1(i, 9)).sum::<f32>() / 10000.0; - assert!((m - 0.5).abs() < 0.02); - } -} diff --git a/crates/nodes/src/noise3d.rs b/crates/nodes/src/noise3d.rs deleted file mode 100644 index a443440e..00000000 --- a/crates/nodes/src/noise3d.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Texture generators › Noises: 3D noises that still tile. Perlin and Worley use a 3D lattice that -//! is periodic in x and y (whole-number scales) and free in z, so scrubbing `z` animates the -//! pattern. The simplex variant samples 4D simplex noise on a flat torus (u and v each mapped to a -//! circle), which tiles at any scale; `z` slides the torus through the 4D field. - -use std::f32::consts::TAU; - -use crate::catalog::{B, CookResult, Ctx, NodeDef, node}; -use crate::generators::NOISES; -use crate::noise::{hash, hash3}; -use crate::noises_more::fractal; - -#[inline] -fn wrap(i: i32, p: i32) -> i32 { - if p <= 0 { i } else { i.rem_euclid(p) } -} - -/// A hash of a 3D lattice point, periodic in x and y. -#[inline] -fn hash_xyz(i: i32, j: i32, k: i32, px: i32, py: i32, seed: u32) -> u32 { - hash(hash3(wrap(i, px), wrap(j, py), seed) ^ (k as u32).wrapping_mul(0x9e37_79b1)) -} - -#[inline] -fn fade(t: f32) -> f32 { - t * t * t * (t * (t * 6.0 - 15.0) + 10.0) -} - -/// 3D gradient (Perlin) noise in about -1..1, periods `px`, `py` cells in x and y. -pub fn perlin3(x: f32, y: f32, z: f32, px: i32, py: i32, seed: u32) -> f32 { - const G: [[f32; 3]; 12] = [ - [1.0, 1.0, 0.0], - [-1.0, 1.0, 0.0], - [1.0, -1.0, 0.0], - [-1.0, -1.0, 0.0], - [1.0, 0.0, 1.0], - [-1.0, 0.0, 1.0], - [1.0, 0.0, -1.0], - [-1.0, 0.0, -1.0], - [0.0, 1.0, 1.0], - [0.0, -1.0, 1.0], - [0.0, 1.0, -1.0], - [0.0, -1.0, -1.0], - ]; - let (x0, y0, z0) = (x.floor(), y.floor(), z.floor()); - let (fx, fy, fz) = (x - x0, y - y0, z - z0); - let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32); - let g = |a: i32, b: i32, c: i32| { - let gr = G[(hash_xyz(ix + a, iy + b, iz + c, px, py, seed) % 12) as usize]; - gr[0] * (fx - a as f32) + gr[1] * (fy - b as f32) + gr[2] * (fz - c as f32) - }; - let (u, v, w) = (fade(fx), fade(fy), fade(fz)); - let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t; - let x00 = lerp(g(0, 0, 0), g(1, 0, 0), u); - let x10 = lerp(g(0, 1, 0), g(1, 1, 0), u); - let x01 = lerp(g(0, 0, 1), g(1, 0, 1), u); - let x11 = lerp(g(0, 1, 1), g(1, 1, 1), u); - lerp(lerp(x00, x10, v), lerp(x01, x11, v), w) -} - -/// Uniform 0..1 from a hash. -#[inline] -fn unit(h: u32) -> f32 { - (h >> 8) as f32 / (1u32 << 24) as f32 -} - -/// 3D Worley noise: nearest and second-nearest feature distances (cells), periodic in x and y. -pub fn worley3(x: f32, y: f32, z: f32, px: i32, py: i32, jitter: f32, seed: u32) -> (f32, f32) { - let (ix, iy, iz) = (x.floor() as i32, y.floor() as i32, z.floor() as i32); - let (mut f1, mut f2) = (f32::MAX, f32::MAX); - for k in -1..=1 { - for j in -1..=1 { - for i in -1..=1 { - let (cx, cy, cz) = (ix + i, iy + j, iz + k); - let h = hash_xyz(cx, cy, cz, px, py, seed); - let o = |s: u32| 0.5 + (unit(hash(h ^ s)) - 0.5) * jitter; - let (dx, dy, dz) = (cx as f32 + o(1) - x, cy as f32 + o(2) - y, cz as f32 + o(3) - z); - let d = (dx * dx + dy * dy + dz * dz).sqrt(); - if d < f1 { - f2 = f1; - f1 = d; - } else if d < f2 { - f2 = d; - } - } - } - } - (f1, f2) -} - -/// 4D simplex noise in about -1..1 (after Gustavson's public description of the algorithm). -pub fn simplex4(p: [f32; 4], seed: u32) -> f32 { - const F4: f32 = 0.309_017; // (√5 − 1) / 4 - const G4: f32 = 0.138_196_6; // (5 − √5) / 20 - let s = (p[0] + p[1] + p[2] + p[3]) * F4; - let i: [f32; 4] = std::array::from_fn(|k| (p[k] + s).floor()); - let t = (i[0] + i[1] + i[2] + i[3]) * G4; - let x0: [f32; 4] = std::array::from_fn(|k| p[k] - (i[k] - t)); - // Rank the coordinates to find the simplex the point is in. - let mut rank = [0i32; 4]; - for a in 0..4 { - for b in a + 1..4 { - if x0[a] > x0[b] { - rank[a] += 1; - } else { - rank[b] += 1; - } - } - } - let ii: [i32; 4] = std::array::from_fn(|k| i[k] as i32); - let mut n = 0.0; - for c in 0..5 { - let off: [i32; 4] = std::array::from_fn(|k| (rank[k] >= 4 - c) as i32); - let x: [f32; 4] = std::array::from_fn(|k| x0[k] - off[k] as f32 + c as f32 * G4); - let t = 0.6 - x.iter().map(|v| v * v).sum::<f32>(); - if t <= 0.0 { - continue; - } - let h = hash(hash3(ii[0] + off[0], ii[1] + off[1], seed) ^ hash3(ii[2] + off[2], ii[3] + off[3], seed ^ 0x68e3_1da4)); - // 32 gradients: one coordinate zero, the other three ±1. - let zero = (h >> 3) as usize & 3; - let mut dot = 0.0; - let mut bit = 0; - for k in 0..4 { - if k != zero { - dot += if h >> bit & 1 == 0 { x[k] } else { -x[k] }; - bit += 1; - } - } - n += t * t * t * t * dot; - } - 27.0 * n -} - -/// Fractal 4D simplex on a torus at `(u, v)`: tiles in u and v for any scale. -fn simplex_torus(u: f32, v: f32, z: f32, scale: f32, octaves: i32, gain: f32, seed: u32) -> f32 { - let (su, cu) = (u * TAU).sin_cos(); - let (sv, cv) = (v * TAU).sin_cos(); - // Circumference `scale` cells per axis. - let r = scale / TAU; - fractal(octaves, gain, |m, o| { - let (r, z) = (r * m, z * m); - let p = [r * cu + z * 0.7, r * su + z * 0.3, r * cv - z * 0.5, r * sv + z * 0.4]; - (simplex4(p, seed.wrapping_add(o * 977)) * 0.5 + 0.5).clamp(0.0, 1.0) - }) -} - -/// Shared noise parameters. -fn noise_params(b: B, scale: f32, octaves: i32) -> B { - b.generator() - .float("scale", "Scale", scale, 1.0, 64.0) - .int("octaves", "Octaves", octaves, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("z", "Z (slice)", 0.0, 0.0, 16.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let n = |id, label| node(id, label, NOISES); - vec![ - noise_params(n("perlin_noise_3d", "Perlin Noise 3D").desc("Fractal 3D gradient noise; Z scrubs through the volume. Tiles."), 4.0, 5) - .cook(perlin_noise_3d), - noise_params( - n("simplex_noise_3d", "Simplex Noise 3D").desc("Fractal simplex noise sampled on a 4D torus; Z moves through it. Tiles at any scale."), - 4.0, - 5, - ) - .cook(simplex_noise_3d), - noise_params( - n("worley_noise_3d", "Worley Noise 3D") - .desc("Cellular noise from 3D feature points; Z scrubs through the cells. Tiles.") - .choice("distance", "Distance", &["F1", "F2", "F2 - F1"], 0) - .float("jitter", "Jitter", 1.0, 0.0, 1.0), - 6.0, - 1, - ) - .cook(worley_noise_3d), - ] -} - -/// Common noise settings: whole-number scale, octaves, gain, z, contrast gain, seed. -fn settings(ctx: &Ctx) -> (f32, i32, f32, f32, f32, u32) { - (ctx.f("scale").max(1.0).round(), ctx.i("octaves"), ctx.f("roughness"), ctx.f("z"), 1.0 + ctx.f("contrast") * 3.0, ctx.seed) -} - -/// Expand around mid gray by `k`. -#[inline] -fn spread(v: f32, k: f32) -> f32 { - ((v - 0.5) * k + 0.5).clamp(0.0, 1.0) -} - -fn perlin_noise_3d(ctx: &Ctx) -> CookResult { - let (s, oct, gain, z, k, seed) = settings(ctx); - Ok(vec![ctx.gen_gray(|u, v| { - let n = fractal(oct, gain, |m, o| { - let p = s * m; - perlin3(u * p, v * p, z * m + o as f32 * 17.31, p as i32, p as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5 - }); - spread(n, k) - })]) -} - -fn simplex_noise_3d(ctx: &Ctx) -> CookResult { - let (_, oct, gain, z, k, seed) = settings(ctx); - let s = ctx.f("scale").max(0.1); - Ok(vec![ctx.gen_gray(|u, v| spread(simplex_torus(u, v, z, s, oct, gain, seed), k))]) -} - -fn worley_noise_3d(ctx: &Ctx) -> CookResult { - let (s, oct, gain, z, k, seed) = settings(ctx); - let (mode, jit) = (ctx.i("distance"), ctx.f("jitter").clamp(0.0, 1.0)); - Ok(vec![ctx.gen_gray(|u, v| { - let n = fractal(oct, gain, |m, o| { - let p = s * m; - let (f1, f2) = worley3(u * p, v * p, z * m, p as i32, p as i32, jit, seed.wrapping_add(o * 977)); - match mode { - 1 => f2 * 0.75, - 2 => (f2 - f1) * 1.5, - _ => f1, - } - .clamp(0.0, 1.0) - }); - // Cell distances already span 0..1: contrast 0.5 leaves them as they are. - spread(n, k * 0.4) - })]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use super::*; - use crate::catalog::{find, resolve_params}; - - #[test] - fn primitives_tile_and_stay_in_range() { - for k in 0..20 { - let (y, z) = (k as f32 * 0.37, k as f32 * 0.11); - assert!((perlin3(0.0, y, z, 4, 4, 7) - perlin3(4.0, y, z, 4, 4, 7)).abs() < 1e-5); - assert!((perlin3(y, 0.0, z, 4, 4, 7) - perlin3(y, 4.0, z, 4, 4, 7)).abs() < 1e-5); - assert!((worley3(0.0, y, z, 5, 5, 1.0, 3).0 - worley3(5.0, y, z, 5, 5, 1.0, 3).0).abs() < 1e-4); - } - let mut lo = f32::MAX; - let mut hi = f32::MIN; - for k in 0..20000 { - let p = [k as f32 * 0.131, k as f32 * 0.071 + 0.3, (k as f32 * 0.017).sin() * 9.0, k as f32 * 0.029]; - let v = simplex4(p, 1); - lo = lo.min(v); - hi = hi.max(v); - } - assert!(lo > -1.2 && hi < 1.2 && hi - lo > 1.0, "{lo} {hi}"); - } - - /// Each 3D noise matches across u = 0/1 and v = 0/1, and z changes it. - #[test] - fn noises_3d_tile_both_ways() { - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - for id in ["perlin_noise_3d", "simplex_noise_3d", "worley_noise_3d"] { - let def = find(id).unwrap(); - let cook = |z: f32| { - let mut p = resolve_params(def, &BTreeMap::new()); - p.insert("z".into(), materialcraft_core::Value::Float(z)); - let ctx = Ctx { w: 64, h: 64, seed: 5, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap().remove(0) - }; - let img = cook(0.5); - let (mut seam_x, mut seam_y, mut inner) = (0.0f32, 0.0f32, 0.0f32); - for i in 0..64 { - seam_x += (img.get(63, i, false)[0] - img.get(0, i, false)[0]).abs(); - seam_y += (img.get(i, 63, false)[0] - img.get(i, 0, false)[0]).abs(); - inner += (img.get(31, i, false)[0] - img.get(32, i, false)[0]).abs() + (img.get(i, 31, false)[0] - img.get(i, 32, false)[0]).abs(); - } - assert!(seam_x <= inner * 1.5 + 0.2 && seam_y <= inner * 1.5 + 0.2, "{id}: seams {seam_x} {seam_y} vs inner {inner}"); - assert_ne!(img, cook(1.7), "{id}: z changes the slice"); - let (lo, hi) = img.range(); - assert!(hi - lo > 0.3, "{id}: contrast {lo}..{hi}"); - } - } -} diff --git a/crates/nodes/src/noises_more.rs b/crates/nodes/src/noises_more.rs deleted file mode 100644 index d59f7cd2..00000000 --- a/crates/nodes/src/noises_more.rs +++ /dev/null @@ -1,440 +0,0 @@ -//! More Texture generators › Noises: fractal variants, fibers, organic cells and natural -//! materials (sand, wood, marble, stone, bark, concrete). All tile: every lattice uses whole-number -//! periods per axis. - -use std::f32::consts::{PI, TAU}; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::generators::NOISES; -use crate::noise::{cellular, fbm, hash3, rand1, rand2, value}; - -#[inline] -pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0).max(1e-6)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -#[inline] -fn wrap(i: i32, p: i32) -> i32 { - if p <= 0 { i } else { i.rem_euclid(p) } -} - -/// Gradient (Perlin) noise in about -1..1 with separate lattice periods per axis, so stretched -/// noise still tiles. -pub(crate) fn perlin_xy(x: f32, y: f32, px: i32, py: i32, seed: u32) -> f32 { - let (x0, y0) = (x.floor(), y.floor()); - let (fx, fy) = (x - x0, y - y0); - let (ix, iy) = (x0 as i32, y0 as i32); - let g = |i: i32, j: i32, dx: f32, dy: f32| { - let a = (hash3(wrap(i, px), wrap(j, py), seed) >> 8) as f32 * (TAU / (1u32 << 24) as f32); - a.cos() * dx + a.sin() * dy - }; - let fade = |t: f32| t * t * t * (t * (t * 6.0 - 15.0) + 10.0); - let (u, v) = (fade(fx), fade(fy)); - let a = g(ix, iy, fx, fy) + (g(ix + 1, iy, fx - 1.0, fy) - g(ix, iy, fx, fy)) * u; - let b = g(ix, iy + 1, fx, fy - 1.0) + (g(ix + 1, iy + 1, fx - 1.0, fy - 1.0) - g(ix, iy + 1, fx, fy - 1.0)) * u; - (a + (b - a) * v) * std::f32::consts::SQRT_2 -} - -/// Fractal sum of `f(level multiplier, octave)` (each 0..1): `octaves` layers, each twice as fine -/// and `gain` times weaker. Normalized to 0..1. -pub(crate) fn fractal(octaves: i32, gain: f32, f: impl Fn(f32, u32) -> f32) -> f32 { - let (mut sum, mut amp, mut norm, mut m) = (0.0, 1.0, 0.0, 1.0); - for o in 0..octaves.clamp(1, 10) as u32 { - sum += f(m, o) * amp; - norm += amp; - amp *= gain; - m *= 2.0; - } - sum / f32::max(norm, 1e-6) -} - -/// Stretched fractal Perlin noise in 0..1 with `sx` × `sy` base cells. -fn fbm_xy(u: f32, v: f32, sx: f32, sy: f32, octaves: i32, gain: f32, seed: u32) -> f32 { - fractal(octaves, gain, |m, o| { - let (px, py) = (sx * m, sy * m); - perlin_xy(u * px, v * py, px as i32, py as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5 - }) -} - -/// A thin bright line per stretched noise zero crossing (fibers, grain). -fn fiber(u: f32, v: f32, along: f32, across: f32, sharp: f32, seed: u32) -> f32 { - (1.0 - perlin_xy(u * along, v * across, along as i32, across as i32, seed).abs()).powf(sharp) -} - -fn whole(ctx: &Ctx, id: &str) -> f32 { - ctx.f(id).max(1.0).round() -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let n = |id, label| node(id, label, NOISES).generator(); - vec![ - n("value_noise", "Value Noise") - .desc("Fractal value noise: smooth blocks of random values.") - .float("scale", "Scale", 8.0, 1.0, 256.0) - .int("octaves", "Octaves", 1, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(value_noise), - n("ridged_fractal", "Ridged Fractal") - .desc("Ridged multi-octave noise: sharp crests like mountain ridges.") - .float("scale", "Scale", 4.0, 1.0, 64.0) - .int("octaves", "Octaves", 6, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("sharpness", "Sharpness", 2.0, 0.5, 8.0) - .gray_out() - .cook(ridged_fractal), - n("voronoi_fractal", "Voronoi Fractal") - .desc("Several octaves of cell bumps.") - .float("scale", "Scale", 4.0, 1.0, 64.0) - .int("octaves", "Octaves", 4, 1, 8) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(voronoi_fractal), - n("cells_fractal", "Cells Fractal") - .desc("Several octaves of cell borders: cracked, crystalline networks.") - .float("scale", "Scale", 4.0, 1.0, 64.0) - .int("octaves", "Octaves", 3, 1, 8) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells_fractal), - n("directional_noise", "Directional Noise") - .desc("Fractal noise stretched along one axis: streaks and brushed patterns.") - .float("scale", "Scale along", 2.0, 1.0, 64.0) - .float("scale_across", "Scale across", 24.0, 1.0, 256.0) - .int("octaves", "Octaves", 5, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(directional_noise), - n("fibers", "Fibers") - .desc("Thin, nearly parallel fibers.") - .float("density", "Density", 96.0, 4.0, 512.0) - .float("length", "Length", 2.0, 1.0, 32.0) - .float("sharpness", "Sharpness", 12.0, 1.0, 64.0) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(fibers), - n("messy_fibers", "Messy Fibers") - .desc("Tangled fibers in both directions, warped by clouds.") - .float("density", "Density", 64.0, 4.0, 512.0) - .float("warp", "Warp", 0.5, 0.0, 2.0) - .float("sharpness", "Sharpness", 10.0, 1.0, 64.0) - .gray_out() - .cook(messy_fibers), - n("leather", "Leather") - .desc("Leather grain: small bumpy cells split by creases, over soft clouds.") - .float("scale", "Scale", 24.0, 2.0, 128.0) - .float("crease", "Crease width", 0.25, 0.0, 1.0) - .float("warp", "Warp", 0.4, 0.0, 1.0) - .float("clouds", "Clouds", 0.3, 0.0, 1.0) - .gray_out() - .cook(leather), - n("microscope", "Microscope View") - .desc("Strongly warped cell walls, like tissue under a microscope.") - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("warp", "Warp", 0.6, 0.0, 2.0) - .float("width", "Wall width", 0.15, 0.01, 1.0) - .gray_out() - .cook(microscope), - n("gaussian_spots", "Gaussian Spots") - .desc("Scattered soft round spots of random size and intensity.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("size", "Size", 0.3, 0.01, 1.0) - .float("size_random", "Size random", 0.5, 0.0, 1.0) - .float("density", "Density", 0.8, 0.0, 1.0) - .gray_out() - .cook(gaussian_spots), - n("crackle", "Crackle") - .desc("Wiggly cracks along cell borders, with finer secondary cracks.") - .float("scale", "Scale", 5.0, 1.0, 64.0) - .float("width", "Width", 0.08, 0.005, 0.5) - .float("disorder", "Disorder", 0.5, 0.0, 2.0) - .float("amount", "Amount", 1.0, 0.0, 1.0) - .gray_out() - .cook(crackle), - n("sand_dunes", "Sand Dunes") - .desc("Wind-shaped dunes: gentle windward slopes, steep lee sides and fine ripples.") - .int("count", "Dunes", 6, 1, 64) - .float("warp", "Warp", 0.6, 0.0, 2.0) - .float("steepness", "Lee side", 0.3, 0.05, 0.95) - .float("ripples", "Ripples", 0.15, 0.0, 1.0) - .gray_out() - .cook(sand_dunes), - n("wood_grain", "Wood Grain") - .desc("Distorted growth rings and fibers of sawn wood (grain along X).") - .float("rings", "Rings", 16.0, 1.0, 128.0) - .float("stretch", "Stretch", 6.0, 1.0, 32.0) - .float("sharpness", "Ring sharpness", 3.0, 0.5, 16.0) - .float("fibers", "Fibers", 0.3, 0.0, 1.0) - .gray_out() - .cook(wood_grain), - n("marble", "Marble") - .desc("Thin veins from sine bands warped by fractal noise.") - .float("scale", "Bands", 2.0, 1.0, 32.0) - .float("turbulence", "Turbulence", 3.0, 0.0, 10.0) - .float("sharpness", "Vein sharpness", 4.0, 1.0, 64.0) - .choice("direction", "Direction", &["Horizontal", "Vertical", "Diagonal"], 2) - .gray_out() - .cook(marble), - n("stones", "Stones") - .desc("Packed rounded stones with gaps (height).") - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("gap", "Gap", 0.06, 0.0, 0.5) - .float("bevel", "Bevel", 0.25, 0.01, 1.0) - .float("height_random", "Height random", 0.4, 0.0, 1.0) - .float("detail", "Detail", 0.2, 0.0, 1.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(stones), - n("ripples", "Ripples") - .desc("Interfering waves, like a water surface.") - .float("scale", "Scale", 8.0, 1.0, 32.0) - .int("waves", "Waves", 10, 1, 32) - .float("warp", "Warp", 0.3, 0.0, 2.0) - .gray_out() - .cook(ripples), - n("concrete", "Concrete") - .desc("Cement clouds with small air pits and fine grain.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("pits", "Pit density", 0.3, 0.0, 1.0) - .float("pit_size", "Pit size", 0.5, 0.0, 1.0) - .float("roughness", "Roughness", 0.6, 0.0, 1.0) - .gray_out() - .cook(concrete), - n("bark", "Bark") - .desc("Deep vertical bark furrows.") - .float("scale", "Furrows", 8.0, 1.0, 64.0) - .float("stretch", "Length", 1.0, 1.0, 16.0) - .float("warp", "Warp", 0.4, 0.0, 2.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(bark), - ] -} - -fn value_noise(ctx: &Ctx) -> CookResult { - let (sc, o, r, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fractal(o, r, |m, k| value(u * sc * m, v * sc * m, (sc * m) as i32, s.wrapping_add(k * 131))))]) -} - -fn ridged_fractal(ctx: &Ctx) -> CookResult { - let (sc, o, r, sh, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.f("sharpness").max(0.1), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - fractal(o, r, |m, k| (1.0 - perlin_xy(u * sc * m, v * sc * m, (sc * m) as i32, (sc * m) as i32, s.wrapping_add(k * 7919)).abs()).powf(sh)) - })]) -} - -fn cell_fractal(ctx: &Ctx, f: impl Fn(crate::noise::Cell) -> f32 + Sync) -> CookResult { - let (sc, o, r, d, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fractal(o, r, |m, k| f(cellular(u * sc * m, v * sc * m, (sc * m) as i32, d, 0, s.wrapping_add(k * 311)))))]) -} - -fn voronoi_fractal(ctx: &Ctx) -> CookResult { - cell_fractal(ctx, |c| (1.0 - c.f1).clamp(0.0, 1.0)) -} - -fn cells_fractal(ctx: &Ctx) -> CookResult { - cell_fractal(ctx, |c| ((c.f2 - c.f1) * 2.0).min(1.0)) -} - -fn directional_noise(ctx: &Ctx) -> CookResult { - let (along, across, o, r, s) = (whole(ctx, "scale"), whole(ctx, "scale_across"), ctx.i("octaves"), ctx.f("roughness"), ctx.seed); - let vert = ctx.b("vertical"); - Ok(vec![ctx.gen_gray(|u, v| if vert { fbm_xy(u, v, across, along, o, r, s) } else { fbm_xy(u, v, along, across, o, r, s) })]) -} - -fn fibers(ctx: &Ctx) -> CookResult { - let (d, l, sh, s) = (whole(ctx, "density"), whole(ctx, "length"), ctx.f("sharpness").max(1.0), ctx.seed); - let vert = ctx.b("vertical"); - Ok(vec![ctx.gen_gray(|u, v| { - let (u, v) = if vert { (v, u) } else { (u, v) }; - let a = fiber(u, v, l, d, sh, s); - let b = fiber(u, v, l * 2.0, d * 2.0, sh, s ^ 0x51); - (a + b * 0.6).min(1.0) - })]) -} - -fn messy_fibers(ctx: &Ctx) -> CookResult { - let (d, w, sh, s) = (whole(ctx, "density"), ctx.f("warp") * 0.15, ctx.f("sharpness").max(1.0), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let wu = u + (fbm(u, v, 3.0, 4, 0.5, s ^ 1) - 0.5) * w; - let wv = v + (fbm(u, v, 3.0, 4, 0.5, s ^ 2) - 0.5) * w; - let h = fiber(wu, wv, 3.0, d, sh, s); - let vt = fiber(wv, wu, 3.0, d, sh, s ^ 0x77); - let fine = fiber(wv, wu, 6.0, d * 2.0, sh, s ^ 0x99); - (h + vt * 0.8 + fine * 0.4).min(1.0) - })]) -} - -fn leather(ctx: &Ctx) -> CookResult { - let (sc, cw, w, cl, s) = (whole(ctx, "scale"), ctx.f("crease").max(1e-3), ctx.f("warp"), ctx.f("clouds"), ctx.seed); - let lo = (sc / 6.0).round().max(1.0); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = (fbm(u, v, lo, 4, 0.5, s ^ 3) - 0.5) * w / sc * 2.0; - let qy = (fbm(u, v, lo, 4, 0.5, s ^ 4) - 0.5) * w / sc * 2.0; - let c = cellular((u + qx) * sc, (v + qy) * sc, sc as i32, 1.0, 0, s); - let crease = smoothstep(0.0, cw, c.f2 - c.f1); - let bump = (1.0 - c.f1 * 0.9).clamp(0.0, 1.0); - let clouds = fbm(u, v, lo, 5, 0.5, s ^ 7); - (crease * (0.55 + 0.45 * bump) * (1.0 - cl + cl * clouds)).clamp(0.0, 1.0) - })]) -} - -fn microscope(ctx: &Ctx) -> CookResult { - let (sc, w, wd, s) = (whole(ctx, "scale"), ctx.f("warp"), ctx.f("width").max(1e-3), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = (fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5) * w / sc * 3.0; - let qy = (fbm(u, v, sc, 4, 0.5, s ^ 6) - 0.5) * w / sc * 3.0; - let c = cellular((u + qx) * sc, (v + qy) * sc, sc as i32, 1.0, 0, s); - let wall = 1.0 - smoothstep(0.0, wd, c.f2 - c.f1); - let inner = fbm(u, v, sc * 2.0, 4, 0.5, s ^ 8) * 0.35 * (1.0 - c.f1).max(0.0); - (wall + inner).clamp(0.0, 1.0) - })]) -} - -fn gaussian_spots(ctx: &Ctx) -> CookResult { - let (sc, size, sr, dens, s) = (whole(ctx, "scale"), ctx.f("size").max(0.01), ctx.f("size_random"), ctx.f("density"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let mut sum = 0.0; - for layer in 0..2u32 { - let n = sc * (layer + 1) as f32; - let (x, y) = (u * n, v * n); - let (ix, iy) = (x.floor() as i32, y.floor() as i32); - let ls = s.wrapping_add(layer * 0x3c6e); - for j in -1..=1 { - for i in -1..=1 { - let (cx, cy) = (wrap(ix + i, n as i32), wrap(iy + j, n as i32)); - if rand2(cx, cy, ls ^ 9) > dens { - continue; - } - let px = (ix + i) as f32 + rand2(cx, cy, ls); - let py = (iy + j) as f32 + rand2(cx, cy, ls ^ 1); - let r = size * (1.0 - sr * rand2(cx, cy, ls ^ 2)) * 0.5; - let d2 = (px - x).powi(2) + (py - y).powi(2); - sum += (-d2 / (2.0 * r * r)).exp() * (0.4 + 0.6 * rand2(cx, cy, ls ^ 3)) / (layer + 1) as f32; - } - } - } - sum.min(1.0) - })]) -} - -fn crackle(ctx: &Ctx) -> CookResult { - let (sc, wd, dis, amt, s) = (whole(ctx, "scale"), ctx.f("width").max(1e-3), ctx.f("disorder"), ctx.f("amount"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = (fbm(u, v, sc, 4, 0.5, s ^ 1) - 0.5) * dis / sc; - let qy = (fbm(u, v, sc, 4, 0.5, s ^ 2) - 0.5) * dis / sc; - let (wu, wv) = (u + qx, v + qy); - let c = cellular(wu * sc, wv * sc, sc as i32, 1.0, 0, s); - let main = 1.0 - smoothstep(0.0, wd, c.f2 - c.f1); - let n2 = sc * 3.0; - let c2 = cellular(wu * n2, wv * n2, n2 as i32, 1.0, 0, s ^ 5); - // Finer cracks only in some areas, so they break off instead of closing into cells. - let fine = (1.0 - smoothstep(0.0, wd * 1.5, c2.f2 - c2.f1)) * smoothstep(0.55, 0.65, fbm(u, v, sc * 2.0, 3, 0.5, s ^ 11)) * 0.6; - let vis = smoothstep(0.9 - amt, 1.1 - amt, fbm(u, v, 2.0, 3, 0.5, s ^ 3) * 0.999); - (main.max(fine) * if amt >= 1.0 { 1.0 } else { vis }).clamp(0.0, 1.0) - })]) -} - -fn sand_dunes(ctx: &Ctx) -> CookResult { - let (n, w, k, rp, s) = (ctx.i("count").max(1) as f32, ctx.f("warp"), ctx.f("steepness").clamp(0.05, 0.95), ctx.f("ripples"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = fbm(u, v, 3.0, 5, 0.5, s) - 0.5; - let t = (v * n + q * w * 2.0).rem_euclid(1.0); - let p = if t < 1.0 - k { t / (1.0 - k) } else { (1.0 - t) / k }; - let p = p * p * (3.0 - 2.0 * p); - let rip = (TAU * (v * n * 8.0 + q * 6.0 + u * 2.0)).sin() * 0.5 + 0.5; - p * (1.0 - rp) + rip * rp * (0.5 + 0.5 * p) - })]) -} - -fn wood_grain(ctx: &Ctx) -> CookResult { - let (rings, st, sh, fb, s) = (ctx.f("rings").max(1.0), whole(ctx, "stretch"), ctx.f("sharpness").max(0.1), ctx.f("fibers"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let n = fbm_xy(u, v, 1.0, st, 4, 0.45, s); - let t = (n * rings).rem_euclid(1.0); - let ring = t.powf(sh); - let f = fiber(u, v, 2.0, 160.0, 8.0, s ^ 0x3b); - ((1.0 - ring * 0.65) * (1.0 - f * fb * 0.35)).clamp(0.0, 1.0) - })]) -} - -fn marble(ctx: &Ctx) -> CookResult { - let (n, turb, sh, dir, s) = (whole(ctx, "scale"), ctx.f("turbulence"), ctx.f("sharpness").max(1.0), ctx.i("direction"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let base = match dir { - 0 => v, - 1 => u, - _ => u + v, - }; - let f = fbm(u, v, 3.0, 6, 0.55, s); - let vein = |k: f32, f: f32| (1.0 - (PI * (base * n * k + turb * f)).sin().abs()).powf(sh * k); - // Main veins plus a finer, fainter network. - let v2 = vein(2.0, fbm(u, v, 4.0, 6, 0.55, s ^ 9)); - (0.25 + 0.2 * fbm(u, v, 6.0, 5, 0.5, s ^ 4) + 0.6 * vein(1.0, f).max(v2 * 0.45)).clamp(0.0, 1.0) - })]) -} - -fn stones(ctx: &Ctx) -> CookResult { - let (sc, gap, bev, hr, det, dis, s) = - (whole(ctx, "scale"), ctx.f("gap"), ctx.f("bevel").max(1e-3), ctx.f("height_random"), ctx.f("detail"), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, dis, 0, s); - let e = (c.f2 - c.f1) * 0.5 - gap * 0.5; - if e <= 0.0 { - return 0.0; - } - let dome = smoothstep(0.0, bev, e).sqrt(); - let d = fbm(u, v, sc * 2.0, 4, 0.5, s ^ 3); - (dome * (1.0 - hr * c.id) * (1.0 - det + det * d)).clamp(0.0, 1.0) - })]) -} - -fn ripples(ctx: &Ctx) -> CookResult { - let (sc, n, w, s) = (whole(ctx, "scale"), ctx.i("waves").clamp(1, 32) as u32, ctx.f("warp"), ctx.seed); - // Whole-number wave vectors keep every wave periodic over the image. - let waves: Vec<(f32, f32, f32, f32)> = (0..n) - .map(|k| { - let (dy, dx) = (rand1(k * 4, s) * TAU).sin_cos(); - let mag = sc * (0.5 + 0.5 * rand1(k * 4 + 1, s)); - let (mut kx, ky) = ((dx * mag).round(), (dy * mag).round()); - if kx == 0.0 && ky == 0.0 { - kx = 1.0; - } - (kx, ky, rand1(k * 4 + 2, s), 1.0 / (1.0 + k as f32 * 0.3)) - }) - .collect(); - let norm: f32 = waves.iter().map(|w| w.3).sum(); - Ok(vec![ctx.gen_gray(|u, v| { - let q = (fbm(u, v, 2.0, 3, 0.5, s ^ 7) - 0.5) * w; - let sum: f32 = waves.iter().map(|(kx, ky, ph, a)| (TAU * (kx * u + ky * v + ph + q)).sin() * a).sum(); - (sum / norm.max(1e-6) * 0.5 + 0.5).clamp(0.0, 1.0) - })]) -} - -fn concrete(ctx: &Ctx) -> CookResult { - let (sc, pits, ps, r, s) = (whole(ctx, "scale"), ctx.f("pits"), ctx.f("pit_size"), ctx.f("roughness"), ctx.seed); - let pn = (sc * 12.0).round(); - Ok(vec![ctx.gen_gray(|u, v| { - let base = fbm(u, v, sc, 8, r, s); - let c = cellular(u * pn, v * pn, pn as i32, 1.0, 0, s ^ 5); - let rad = 0.08 + ps * 0.3; - let pit = if c.id < pits { 1.0 - smoothstep(rad * 0.6, rad, c.f1) } else { 0.0 }; - let grain = value(u * 192.0, v * 192.0, 192, s ^ 9); - (base * 0.75 + grain * 0.25 - pit * 0.45).clamp(0.0, 1.0) - })]) -} - -fn bark(ctx: &Ctx) -> CookResult { - let (sx, sy, w, r, s) = (whole(ctx, "scale"), whole(ctx, "stretch"), ctx.f("warp"), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = (fbm(u, v, 4.0, 4, 0.5, s ^ 3) - 0.5) * w / sx; - fractal(5, r, |m, k| { - let (px, py) = (sx * m, sy * m); - (1.0 - perlin_xy((u + q) * px, v * py, px as i32, py as i32, s.wrapping_add(k * 613)).abs()).powi(2) - }) - })]) -} diff --git a/crates/nodes/src/output_value_type.rs b/crates/nodes/src/output_value_type.rs new file mode 100644 index 00000000..7eb3e8a1 --- /dev/null +++ b/crates/nodes/src/output_value_type.rs @@ -0,0 +1,34 @@ +use materialcraft_core::{Graph, NodeId, Value, ValueType}; +use std::collections::BTreeSet; + +use crate::find; + +pub fn output_value_type(graph: &Graph, mut id: NodeId) -> Result<Option<ValueType>, String> { + let mut visited = BTreeSet::new(); + loop { + if !visited.insert(id) { + return Err("cycle while resolving a value connection".into()); + } + + let node = graph.node(id).map_err(|error| error.to_string())?; + match node.def.as_str() { + "dot" | "output" => match graph.input_of(id, "input") { + Some(connection) => id = connection.from, + None => return Ok(None), + }, + "input_value" => return Ok(Some(node.params.get("default").and_then(ValueType::of).unwrap_or(ValueType::Float))), + "value_processor" => { + let default = find("value_processor").and_then(|definition| definition.param("function")); + let function = node.params.get("function").or_else(|| default.map(|parameter| ¶meter.default)); + let Some(Value::Function(function)) = function else { + return Err("missing value function".into()); + }; + + let types = crate::function::node_types(function)?; + let code = function.output.and_then(|id| types.get(&id).copied()).unwrap_or(256); + return ValueType::from_code(code).map(Some).ok_or_else(|| format!("unsupported value type {code}")); + } + _ => return Ok(None), + } + } +} diff --git a/crates/nodes/src/parameter.rs b/crates/nodes/src/parameter.rs new file mode 100644 index 00000000..e15f358a --- /dev/null +++ b/crates/nodes/src/parameter.rs @@ -0,0 +1,68 @@ +use crate::NodeDefinition; +use materialcraft_core::Value; +use std::collections::BTreeMap; + +/// How many slider spans the hard limit extends past each end of a parameter's range +const HARD_SPAN: f32 = 16.0; + +/// Clamp `v` to `[lo, hi]`; a non-finite `v` becomes `fallback` +fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 { + if v.is_finite() { v.clamp(lo, hi) } else { fallback } +} + +pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) { + for p in &def.params { + let Some(v) = params.get_mut(p.id) else { continue }; + if let Value::Enum(i) = v { + if !p.options.is_empty() { + *i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX)); + } + continue; + } + if let Value::Color(c) = v { + for x in c { + *x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0); + } + continue; + } + if p.min >= p.max { + continue; + } + let span = p.max - p.min; + let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span); + // The default's component `i`, or 0 when the default is a different variant + let fallback = |i: usize| match &p.default { + Value::Float(d) => [*d].get(i).copied(), + Value::Float2(d) => d.get(i).copied(), + Value::Float3(d) => d.get(i).copied(), + Value::Float4(d) => d.get(i).copied(), + _ => None, + }; + + let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0)); + let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32; + match v { + Value::Float(x) => clamp_at(x, 0), + Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), + Value::Int(x) => clamp_int(x), + Value::Int2(a) => a.iter_mut().for_each(clamp_int), + _ => {} + } + } +} + +/// Parameter values for a node: catalog defaults overlaid with `overrides` +pub fn resolve_params(def: &NodeDefinition, overrides: &BTreeMap<String, Value>) -> BTreeMap<String, Value> { + let mut m: BTreeMap<String, Value> = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect(); + for (k, v) in overrides { + // Keep only known parameters whose type matches (a hand-edited file may have anything) + if let Some(d) = m.get(k) + && (d.type_name() == v.type_name() || (def.id == "input_value" && k == "default" && materialcraft_core::ValueType::of(v).is_some())) + { + m.insert(k.clone(), v.clone()); + } + } + m +} diff --git a/crates/nodes/src/parameter_definition.rs b/crates/nodes/src/parameter_definition.rs new file mode 100644 index 00000000..f61dd9f3 --- /dev/null +++ b/crates/nodes/src/parameter_definition.rs @@ -0,0 +1,19 @@ +use materialcraft_core::Value; + +/// The editor widget and range of a parameter +#[derive(Clone, Debug)] +pub struct ParameterDefinition { + pub id: &'static str, + pub label: &'static str, + pub default: Value, + pub min: f32, + pub max: f32, + /// Labels of an enum parameter + pub options: &'static [&'static str], + /// Section heading in the Properties panel ("" = none) + pub group: &'static str, + /// An angle in turns (shown in degrees) + pub angle: bool, + /// The name of a package resource (bitmap / SVG) + pub resource: bool, +} diff --git a/crates/nodes/src/pattern/catalog.rs b/crates/nodes/src/pattern/catalog.rs new file mode 100644 index 00000000..45f96a84 --- /dev/null +++ b/crates/nodes/src/pattern/catalog.rs @@ -0,0 +1,42 @@ +use materialcraft_core::PatternNodeKind; +use std::sync::OnceLock; + +use crate::{NodeDefinition, node}; + +pub fn definitions() -> &'static [NodeDefinition] { + static DEFINITIONS: OnceLock<Vec<NodeDefinition>> = OnceLock::new(); + DEFINITIONS.get_or_init(|| { + vec![ + node("passthrough", "Dot", "Pattern nodes").cook(crate::node_definition_builder::no_cook), + node("paramset", "Quadrant", "Pattern nodes") + .int("patterntype", "Pattern", 0, 0, 255 + crate::MAX_IMAGE_INPUTS as i32) + .float4("opacity", "Color / luminosity", [1.0; 4], 0.0, 1.0) + .float2("branchoffset", "Branch offset", [0.0; 2], -1.0, 1.0) + .float2("frameoffset", "Pattern offset", [0.0; 2], -1.0, 1.0) + .float2("patternsize", "Pattern size", [1.0; 2], 0.0, 2.0) + .angle("patternrotation", "Pattern rotation", 0.0) + .float("patternsuppl", "Pattern variation", 0.0, 0.0, 1.0) + .int("blendingmode", "Blending", 0, 0, 2) + .int("imagefiltering", "Image filtering", 1, 0, 1) + .boolean("imagepremul", "Premultiplied image", false) + .int("imageindex", "Image input", 1, 1, crate::MAX_IMAGE_INPUTS as i32) + .int("randomseed", "Random seed", 0, 0, 10000) + .boolean("randominherited", "Inherit random seed", true) + .cook(crate::node_definition_builder::no_cook), + node("markov2", "Switch", "Pattern nodes") + .boolean("switch", "Right branch", false) + .int("randomseed", "Random seed", 0, 0, 10000) + .boolean("randominherited", "Inherit random seed", true) + .cook(crate::node_definition_builder::no_cook), + node("addnode", "Iterate", "Pattern nodes") + .int("numberadded", "Iterations", 1, 0, 10000) + .int("randomseed", "Random seed", 0, 0, 10000) + .boolean("randominherited", "Inherit random seed", true) + .cook(crate::node_definition_builder::no_cook), + ] + }) +} + +pub fn definition(kind: PatternNodeKind) -> Option<&'static NodeDefinition> { + definitions().iter().find(|definition| definition.id == kind.native_id()) +} diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs new file mode 100644 index 00000000..d8d9aade --- /dev/null +++ b/crates/nodes/src/pattern/evaluation.rs @@ -0,0 +1,163 @@ +use materialcraft_core::{PatternNodeKind, Value}; +use std::collections::BTreeMap; + +use super::{catalog, pattern_stamp::PatternStamp, pattern_visit::PatternVisit, raster}; +use crate::function::{EvaluationContext, EvaluationState, compile}; +use crate::{CookContext, CookResult}; + +const MAX_VISITS: usize = 65_536; + +pub(crate) fn cook(context: &CookContext) -> CookResult { + let Some(Value::PatternGraph(graph)) = context.params.get("pattern") else { + return Err("missing pattern graph".into()); + }; + + graph.validate()?; + let nodes: BTreeMap<_, _> = graph.nodes.iter().map(|node| (node.id, node)).collect(); + let mut functions = BTreeMap::new(); + for node in &graph.nodes { + for (name, value) in &node.parameters { + if let Value::Function(function) = value { + functions.insert((node.id, name.as_str()), compile(function, context.seed)?); + } + } + } + + let mut pending = Vec::new(); + if let Some(root) = graph.root { + pending.push(PatternVisit { node: root, center: [0.5; 2], extent: 1.0, depth: 0, number: 0, seed: context.seed, variables: context.vars.clone() }); + } + + let mut stamps = Vec::new(); + let mut state = EvaluationState::default(); + let mut remaining = MAX_VISITS; + while let Some(mut visit) = pending.pop() { + remaining = remaining.checked_sub(1).ok_or("pattern graph exceeded its execution budget")?; + let node = nodes.get(&visit.node).ok_or("missing pattern node")?; + if node.kind == PatternNodeKind::Dot { + if let Some(Some(child)) = node.children.first() { + visit.node = *child; + pending.push(visit); + } + continue; + } + + let definition = catalog::definition(node.kind).ok_or("missing pattern definition")?; + if node.parameters.get("randominherited").and_then(Value::as_bool) == Some(false) { + visit.seed = node.parameters.get("randomseed").and_then(Value::as_i32).unwrap_or(0) as u32; + } + visit.variables.insert("$randomseed".into(), Value::Int(visit.seed as i32)); + visit.variables.insert("$depth".into(), Value::Float(visit.depth as f32)); + visit.variables.insert("$depthpow2".into(), Value::Float(visit.extent)); + visit.variables.insert("$number".into(), Value::Float(visit.number as f32)); + visit.variables.insert("$time".into(), Value::Float(0.0)); + + let mut parameters = BTreeMap::new(); + for parameter in &definition.params { + let value = match functions.get(&(node.id, parameter.id)) { + Some(program) => { + let evaluation = EvaluationContext { + position: visit.center, + size: [context.w as f32, context.h as f32], + images: context.inputs.get(1..).unwrap_or(&[]), + tile: context.tile, + variables: &visit.variables, + }; + + let value = program.evaluate(&evaluation, &mut state)?; + visit.variables.clone_from(state.variables()); + value + } + None => node.parameters.get(parameter.id).unwrap_or(¶meter.default).clone(), + }; + + parameters.insert(parameter.id, value); + } + + let scalar = |name: &str| parameters.get(name).and_then(Value::as_f32).unwrap_or(0.0); + let integer = |name: &str| parameters.get(name).and_then(Value::as_i32).unwrap_or(0); + let vector = |name: &str| parameters.get(name).and_then(Value::as_vec4).map(|value| [value[0], value[1]]).unwrap_or([0.0; 2]); + if parameters.get("randominherited").and_then(Value::as_bool) == Some(false) { + visit.seed = integer("randomseed") as u32; + } + + let mut children = Vec::new(); + match node.kind { + PatternNodeKind::Dot => {} + PatternNodeKind::Quadrant => { + let offset = vector("branchoffset"); + visit.center = [visit.center[0] + offset[0] * visit.extent, visit.center[1] + offset[1] * visit.extent]; + let pattern = integer("patterntype"); + let pattern = if pattern == 1 { integer("imageindex").max(1).saturating_add(255) } else { pattern }; + if pattern != 0 { + let offset = vector("frameoffset"); + let color = match parameters.get("opacity") { + Some(Value::Float(value)) => [*value, *value, *value, 1.0], + Some(value) => value.as_vec4().ok_or("pattern color must be a float or float4")?, + None => [1.0; 4], + }; + + stamps.push(PatternStamp { + center: [visit.center[0] + offset[0] * visit.extent, visit.center[1] + offset[1] * visit.extent], + size: vector("patternsize").map(|size| size * visit.extent), + rotation: scalar("patternrotation"), + color, + pattern, + variation: scalar("patternsuppl"), + blend: integer("blendingmode"), + filtering: integer("imagefiltering"), + premultiplied: parameters.get("imagepremul").and_then(Value::as_bool).unwrap_or(false), + }); + } + + for (slot, child) in node.children.iter().enumerate() { + if let Some(child) = child { + let mut child_visit = visit.clone(); + child_visit.node = *child; + child_visit.depth = visit.depth.saturating_add(1); + child_visit.extent *= 0.5; + child_visit.center = [ + visit.center[0] + (if slot & 1 == 0 { -0.25 } else { 0.25 }) * visit.extent, + visit.center[1] + (if slot & 2 == 0 { -0.25 } else { 0.25 }) * visit.extent, + ]; + children.push(child_visit); + } + } + } + PatternNodeKind::Switch => { + let slot = usize::from(parameters.get("switch").and_then(Value::as_bool).unwrap_or(false)); + if let Some(Some(child)) = node.children.get(slot) { + visit.node = *child; + children.push(visit); + } + } + PatternNodeKind::Iterate => { + let count = usize::try_from(integer("numberadded")).map_err(|_| "iteration count cannot be negative")?; + if count > remaining || count > 10_000 { + return Err("pattern iteration count exceeds the execution budget".into()); + } + if let Some(Some(child)) = node.children.first() { + let mut first = visit.clone(); + first.node = *child; + first.number = 0; + children.push(first); + } + if let Some(Some(child)) = node.children.get(1) { + for number in 0..count { + let mut repeated = visit.clone(); + repeated.node = *child; + repeated.number = number as u32; + children.push(repeated); + } + } + } + } + + if children.len().saturating_add(pending.len()) > remaining { + return Err("pattern graph exceeded its execution budget".into()); + } + pending.extend(children.into_iter().rev()); + } + + Ok(vec![raster::render(context, &stamps)?]) +} diff --git a/crates/nodes/src/pattern/mod.rs b/crates/nodes/src/pattern/mod.rs new file mode 100644 index 00000000..61085572 --- /dev/null +++ b/crates/nodes/src/pattern/mod.rs @@ -0,0 +1,12 @@ +mod catalog; +mod evaluation; +mod pattern_stamp; +mod pattern_visit; +mod raster; +mod shape; + +pub use catalog::{definition, definitions}; +pub(crate) use evaluation::cook; + +#[cfg(test)] +mod tests; diff --git a/crates/nodes/src/pattern/pattern_stamp.rs b/crates/nodes/src/pattern/pattern_stamp.rs new file mode 100644 index 00000000..4add1539 --- /dev/null +++ b/crates/nodes/src/pattern/pattern_stamp.rs @@ -0,0 +1,11 @@ +pub(super) struct PatternStamp { + pub center: [f32; 2], + pub size: [f32; 2], + pub rotation: f32, + pub color: [f32; 4], + pub pattern: i32, + pub variation: f32, + pub blend: i32, + pub filtering: i32, + pub premultiplied: bool, +} diff --git a/crates/nodes/src/pattern/pattern_visit.rs b/crates/nodes/src/pattern/pattern_visit.rs new file mode 100644 index 00000000..348eb548 --- /dev/null +++ b/crates/nodes/src/pattern/pattern_visit.rs @@ -0,0 +1,13 @@ +use materialcraft_core::Value; +use std::collections::BTreeMap; + +#[derive(Clone)] +pub(super) struct PatternVisit { + pub node: u32, + pub center: [f32; 2], + pub extent: f32, + pub depth: u32, + pub number: u32, + pub seed: u32, + pub variables: BTreeMap<String, Value>, +} diff --git a/crates/nodes/src/pattern/raster.rs b/crates/nodes/src/pattern/raster.rs new file mode 100644 index 00000000..368693ff --- /dev/null +++ b/crates/nodes/src/pattern/raster.rs @@ -0,0 +1,96 @@ +use materialcraft_image::{Image, Kind}; +use std::sync::Arc; + +use super::{pattern_stamp::PatternStamp, shape}; +use crate::CookContext; + +const MAX_SAMPLES: u64 = 256_000_000; + +pub(super) fn render(context: &CookContext, stamps: &[PatternStamp]) -> Result<Image, String> { + let (width, height) = materialcraft_image::clamp_size(context.w, context.h); + let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; + let mut image = + 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() }; + let channels = kind.channels(); + let opacity = context.f("opacity").max(0.0); + let pixels = Arc::make_mut(&mut image.data); + let mut budget = MAX_SAMPLES; + + for stamp in stamps { + if !stamp.center.iter().chain(&stamp.size).chain(&stamp.color).chain([&stamp.rotation, &stamp.variation]).all(|value| value.is_finite()) { + return Err("pattern parameters must be finite".into()); + } + if stamp.size.iter().any(|size| size.abs() < 1e-8) { + continue; + } + if !matches!(stamp.blend, 0..=2) { + return Err(format!("unsupported pattern blending mode {}", stamp.blend)); + } + if !(2..=18).contains(&stamp.pattern) && !(256..256 + crate::MAX_IMAGE_INPUTS as i32).contains(&stamp.pattern) { + return Err(format!("unsupported pattern {}", stamp.pattern)); + } + + let (sine, cosine) = (stamp.rotation * std::f32::consts::TAU).sin_cos(); + let radius = [ + (stamp.size[0] * cosine).abs() * 0.5 + (stamp.size[1] * sine).abs() * 0.5, + (stamp.size[0] * sine).abs() * 0.5 + (stamp.size[1] * cosine).abs() * 0.5, + ]; + let center = if context.tile { stamp.center.map(|value| value.rem_euclid(1.0)) } else { stamp.center }; + let bounds = |axis: usize, side: u32| { + let first = ((center[axis] - radius[axis]) * side as f32).floor() as i64; + let last = ((center[axis] + radius[axis]) * side as f32).ceil() as i64; + if context.tile { (first, last) } else { (first.max(0), last.min(i64::from(side))) } + }; + + let (left, right) = bounds(0, width); + let (top, bottom) = bounds(1, height); + let samples = + (right.saturating_sub(left).max(0) as u64).checked_mul(bottom.saturating_sub(top).max(0) as u64).ok_or("pattern bounds exceed the pixel budget")?; + budget = budget.checked_sub(samples).ok_or("pattern rendering exceeded its pixel budget")?; + + for y in top..bottom { + for x in left..right { + let delta = [(x as f32 + 0.5) / width as f32 - center[0], (y as f32 + 0.5) / height as f32 - center[1]]; + let local = [(delta[0] * cosine + delta[1] * sine) * 2.0 / stamp.size[0], (-delta[0] * sine + delta[1] * cosine) * 2.0 / stamp.size[1]]; + if local.iter().any(|coordinate| coordinate.abs() > 1.0) { + continue; + } + + let pattern = if stamp.pattern >= 256 { + let index = (stamp.pattern - 256) as usize + 1; + match context.input(index) { + 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) + } else { + input.sample(uv[0], uv[1], false) + } + } + None => [0.0; 4], + } + } else { + let coverage = shape::coverage(stamp.pattern, local[0], local[1], stamp.variation)?; + [coverage, coverage, coverage, coverage] + }; + + let pixel = (y.rem_euclid(i64::from(height)) as usize * width as usize + x.rem_euclid(i64::from(width)) as usize) * channels; + let target = pixels.get_mut(pixel..pixel + channels).ok_or("invalid pattern pixel")?; + for (channel, target) in target.iter_mut().enumerate() { + let alpha = if stamp.pattern >= 256 && !stamp.premultiplied && channel < 3 { pattern[3] } else { 1.0 }; + let value = pattern[channel] * stamp.color[channel] * alpha * opacity; + *target = match stamp.blend { + 1 => value + *target * (1.0 - (pattern[3] * stamp.color[3] * opacity).clamp(0.0, 1.0)), + 2 => target.max(value), + _ => *target + value, + }; + if !target.is_finite() { + return Err("pattern accumulation overflowed".into()); + } + } + } + } + } + Ok(image) +} diff --git a/crates/nodes/src/pattern/shape.rs b/crates/nodes/src/pattern/shape.rs new file mode 100644 index 00000000..6e44cd80 --- /dev/null +++ b/crates/nodes/src/pattern/shape.rs @@ -0,0 +1,49 @@ +pub(super) fn coverage(pattern: i32, x: f32, y: f32, variation: f32) -> Result<f32, String> { + let radius_squared = x * x + y * y; + let radial = (1.0 - radius_squared).max(0.0); + let value = match pattern - 1 { + 1 => 1.0, + 2 => { + if radius_squared <= 1.0 { + 1.0 + } else { + 0.0 + } + } + 3 => radial, + 4 => radial * radial, + 5 => (-4.0 * radius_squared).exp(), + 6 => (1.0 - radius_squared.sqrt()).max(0.0).powi(4), + 7 => (1.0 - x.abs().max(y.abs())).max(0.0), + 8 => { + if x.abs() <= 1.0 - variation.clamp(0.0, 0.99) { + 1.0 + } else { + 0.0 + } + } + 9 => (x + 1.0) * 0.5, + 10 => (x * std::f32::consts::PI).cos() * 0.5 + 0.5, + 11 => radial * radial * if x >= 0.0 { 1.0 } else { 0.0 }, + 12 => (1.0 - x.abs()).max(0.0).powi(2), + 13 => { + if radius_squared <= 1.0 && (x - variation.max(0.05)).powi(2) + y * y > 1.0 { + 1.0 + } else { + 0.0 + } + } + 14 => { + if (x.abs() - 0.5).max(0.0).powi(2) + y * y <= 0.25 { + 1.0 + } else { + 0.0 + } + } + 15 => (1.0 - radius_squared.sqrt()).max(0.0), + 16 => radial.sqrt(), + 17 => ((x + 1.0) * 0.5 + variation).fract(), + _ => return Err(format!("unknown built-in pattern {pattern}")), + }; + Ok(value) +} diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs new file mode 100644 index 00000000..69dc8867 --- /dev/null +++ b/crates/nodes/src/pattern/tests.rs @@ -0,0 +1,60 @@ +use crate::{CookContext, find, resolve_params}; +use materialcraft_core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}; +use std::collections::BTreeMap; + +fn cook(graph: PatternGraph) -> crate::CookResult { + let definition = find("fx_map").unwrap(); + let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))])); + let variables = BTreeMap::new(); + let context = CookContext { w: 16, h: 16, seed: 7, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: &variables }; + (definition.cook)(&context) +} + +#[test] +fn iterate_sets_number_and_switch_selects_one_child() { + let mut graph = PatternGraph::default(); + let iterate = graph.add(PatternNodeKind::Iterate).unwrap(); + let switch = graph.add(PatternNodeKind::Switch).unwrap(); + let quadrant = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.root = Some(iterate); + graph.nodes[0].children = vec![None, Some(switch)]; + graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(3)); + graph.nodes[1].children = vec![Some(quadrant), None]; + graph.nodes[2].parameters.insert("patterntype".into(), Value::Int(2)); + let mut function = FunctionGraph::default(); + 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); + graph.nodes[1].parameters.insert("switch".into(), Value::Bool(true)); + assert_eq!(cook(graph).unwrap()[0].mean()[0], 0.0); +} + +#[test] +fn patterns_reject_cycles_and_bound_exponential_traversal() { + let mut graph = PatternGraph::default(); + let root = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].children[0] = Some(root); + assert!(cook(graph).unwrap_err().contains("cycle")); + + let mut graph = PatternGraph::default(); + for _ in 0..12 { + graph.add(PatternNodeKind::Quadrant).unwrap(); + } + for index in 0..11 { + graph.nodes[index].children = vec![Some(graph.nodes[index + 1].id); 4]; + } + assert!(cook(graph).unwrap_err().contains("budget")); +} + +#[test] +fn image_indices_outside_the_supported_range_return_an_error() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + graph.nodes[0].parameters.insert("patterntype".into(), Value::Int(1)); + graph.nodes[0].parameters.insert("imageindex".into(), Value::Int(i32::MAX)); + assert!(cook(graph).unwrap_err().contains("unsupported pattern")); +} diff --git a/crates/nodes/src/patterns.rs b/crates/nodes/src/patterns.rs deleted file mode 100644 index e62c319f..00000000 --- a/crates/nodes/src/patterns.rs +++ /dev/null @@ -1,548 +0,0 @@ -//! Texture generators › Patterns: shapes, tilings, gradients and scattered elements. - -use std::f32::consts::{PI, TAU}; - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::noise::{rand1, rand2}; - -pub const PATTERNS: &str = "Texture generators/Patterns"; - -pub const SHAPES: &[&str] = &[ - "Square", - "Disc", - "Paraboloid", - "Bell", - "Gaussian", - "Thorn", - "Pyramid", - "Brick", - "Gradation", - "Waves", - "Half bell", - "Ridged bell", - "Crescent", - "Capsule", - "Cone", - "Hexagon", -]; - -/// A shape's value at local coordinates `(x, y)` in -1..1 (1 at the center, 0 outside). -pub fn shape(kind: i32, x: f32, y: f32) -> f32 { - let r = (x * x + y * y).sqrt(); - let m = x.abs().max(y.abs()); - let v = match kind { - 0 => (m <= 1.0) as i32 as f32, - 1 => (r <= 1.0) as i32 as f32, - 2 => 1.0 - r * r, - 3 => { - let t = (1.0 - r).max(0.0); - t * t * (3.0 - 2.0 * t) - } - 4 => (-r * r * 4.0).exp() * (r <= 1.0) as i32 as f32, - 5 => (1.0 - r).max(0.0).powi(3), - 6 => 1.0 - m, - 7 => { - let bx = (1.0 - x.abs()) * 6.0; - let by = (1.0 - y.abs()) * 3.0; - bx.min(by).clamp(0.0, 1.0) - } - 8 => (x * 0.5 + 0.5) * (m <= 1.0) as i32 as f32, - 9 => (x * PI * 2.0).cos() * 0.5 + 0.5, - 10 => { - let t = (1.0 - r).max(0.0); - if y < 0.0 { 0.0 } else { t * t * (3.0 - 2.0 * t) } - } - 11 => { - let t = (1.0 - r).max(0.0); - (t * t * (3.0 - 2.0 * t)) * (1.0 - ((r * PI * 3.0).sin()).abs() * 0.4) - } - 12 => { - let r2 = ((x - 0.35) * (x - 0.35) + y * y).sqrt(); - ((r <= 1.0) && (r2 > 0.75)) as i32 as f32 - } - 13 => { - let dx = (x.abs() - 0.5).max(0.0); - let d = (dx * dx + y * y * 4.0).sqrt(); - (d <= 0.5) as i32 as f32 - } - 14 => (1.0 - r).max(0.0), - 15 => { - let (ax, ay) = (x.abs(), y.abs()); - ((ax * 0.866 + ay * 0.5).max(ay) <= 0.95) as i32 as f32 - } - _ => 0.0, - }; - v.clamp(0.0, 1.0) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let p = |id, label| node(id, label, PATTERNS).generator(); - vec![ - p("brick_generator", "Brick Generator") - .desc("Rows of bricks with mortar gaps, bevels and random heights.") - .int("bricks_x", "Bricks X", 4, 1, 64) - .int("bricks_y", "Bricks Y", 8, 1, 64) - .float("offset", "Row offset", 0.5, 0.0, 1.0) - .float("gap", "Gap", 0.04, 0.0, 0.5) - .float("bevel", "Bevel", 0.12, 0.0, 1.0) - .float("height_random", "Height random", 0.3, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) - .gray_out() - .cook(bricks), - p("checker", "Checker").desc("A checkerboard.").int("tiling", "Tiling", 4, 1, 64).gray_out().cook(checker), - p("gradient_linear_1", "Gradient Linear 1") - .desc("A ramp from black to white.") - .int("tiling", "Tiling", 1, 1, 16) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(gradient_linear_1), - p("gradient_linear_2", "Gradient Linear 2") - .desc("A mirrored ramp (white in the middle).") - .int("tiling", "Tiling", 1, 1, 16) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(gradient_linear_2), - p("gradient_radial", "Gradient Radial") - .desc("White at the center fading outward.") - .float("radius", "Radius", 0.5, 0.0, 1.0) - .gray_out() - .cook(gradient_radial), - p("hexagons", "Hexagons") - .desc("A honeycomb of beveled hexagons.") - .int("tiling", "Tiling", 4, 1, 64) - .float("size", "Size", 0.9, 0.0, 1.0) - .float("bevel", "Bevel", 0.3, 0.0, 1.0) - .gray_out() - .cook(hexagons), - p("polygon", "Polygon") - .desc("A regular polygon.") - .int("sides", "Sides", 6, 3, 32) - .float("scale", "Scale", 0.8, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .float("gradient", "Gradient", 0.0, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(polygon), - p("scratches", "Scratches") - .desc("Random thin scratches.") - .int("count", "Count", 60, 0, 1000) - .float("length", "Length", 0.25, 0.0, 1.0) - .float("width", "Width", 1.0, 0.1, 8.0) - .angle("angle", "Angle", 0.1) - .float("angle_random", "Angle random", 0.2, 0.0, 1.0) - .gray_out() - .cook(scratches), - p("shape", "Shape") - .desc("A single shape, optionally tiled.") - .choice("pattern", "Pattern", SHAPES, 1) - .int("tiling", "Tiling", 1, 1, 64) - .float("size", "Size", 0.8, 0.0, 2.0) - .float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0) - .angle("angle", "Angle", 0.0) - .gray_out() - .cook(shape_node), - p("splatter", "Splatter") - .desc("Scattered shapes of random size and gray.") - .choice("pattern", "Pattern", SHAPES, 4) - .int("count", "Count", 64, 1, 2000) - .float("size", "Size", 0.08, 0.0, 1.0) - .float("size_random", "Size random", 0.6, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.5, 0.0, 1.0) - .gray_out() - .cook(splatter), - p("star", "Star") - .desc("A star shape.") - .int("points", "Points", 5, 2, 32) - .float("inner", "Inner radius", 0.45, 0.0, 1.0) - .float("scale", "Scale", 0.8, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(star), - p("stripes", "Stripes") - .desc("Parallel bands with soft edges.") - .int("count", "Count", 8, 1, 128) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .gray_out() - .cook(stripes), - p("tile_generator", "Tile Generator") - .desc("Places a shape on a grid with per-tile random size, position, rotation and luminance.") - .choice("pattern", "Pattern", SHAPES, 0) - .int("x_amount", "X amount", 8, 1, 128) - .int("y_amount", "Y amount", 8, 1, 128) - .float("scale", "Scale", 0.9, 0.0, 2.0) - .float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0) - .float("scale_random", "Scale random", 0.0, 0.0, 1.0) - .float("offset", "Row offset", 0.0, 0.0, 1.0) - .float("position_random", "Position random", 0.0, 0.0, 1.0) - .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) - .float("mask_random", "Mask random", 0.0, 0.0, 1.0) - .gray_out() - .cook(tile_generator), - p("tile_sampler", "Tile Sampler") - .desc("Like Tile Generator, but each tile shows the pattern input.") - .gray_in("pattern", "Pattern input") - .gray_in("scale_map", "Scale map") - .int("x_amount", "X amount", 8, 1, 128) - .int("y_amount", "Y amount", 8, 1, 128) - .float("scale", "Scale", 1.0, 0.0, 2.0) - .float("scale_random", "Scale random", 0.0, 0.0, 1.0) - .float("offset", "Row offset", 0.0, 0.0, 1.0) - .float("position_random", "Position random", 0.0, 0.0, 1.0) - .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) - .choice("blend", "Blending", &["Max", "Add"], 0) - .gray_out() - .cook(tile_sampler), - p("weave", "Weave") - .desc("Interlaced threads (height).") - .int("tiling", "Tiling", 6, 1, 64) - .float("width", "Thread width", 0.8, 0.0, 1.0) - .gray_out() - .cook(weave), - p("waveform", "Waveform") - .desc("Sine bands.") - .int("count", "Count", 8, 1, 128) - .float("amplitude", "Amplitude", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .gray_out() - .cook(waveform), - ] -} - -/// Rotate `(x, y)` by `turns`. -#[inline] -fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) { - let (s, c) = (turns * TAU).sin_cos(); - (x * c - y * s, x * s + y * c) -} - -fn bricks(ctx: &Ctx) -> CookResult { - let (bx, by) = (ctx.i("bricks_x").max(1) as f32, ctx.i("bricks_y").max(1) as f32); - let (off, gap, bevel, hr, lr, s) = (ctx.f("offset"), ctx.f("gap"), ctx.f("bevel").max(1e-4), ctx.f("height_random"), ctx.f("lum_random"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * by).floor(); - let x = u * bx + off * row; - let col = x.floor(); - let (fx, fy) = (x - col, v * by - row); - let colw = (col as i32).rem_euclid(bx as i32); - // Distance to the brick's edge, in brick-height units. - let ex = fx.min(1.0 - fx) * by / bx; - let ey = fy.min(1.0 - fy); - let e = ex.min(ey) - gap * 0.5; - if e <= 0.0 { - return 0.0; - } - let t = (e / (bevel * 0.5)).min(1.0); - let rnd = rand2(colw, row as i32, s); - let base = 1.0 - hr * rnd; - let lum = 1.0 - lr * rand2(colw, row as i32, s ^ 99); - (t * base * lum).clamp(0.0, 1.0) - })]) -} - -fn checker(ctx: &Ctx) -> CookResult { - let n = ctx.i("tiling").max(1) as f32; - Ok(vec![ctx.gen_gray(|u, v| (((u * n).floor() + (v * n).floor()) as i32 & 1) as f32)]) -} - -fn gradient_linear_1(ctx: &Ctx) -> CookResult { - let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical")); - Ok(vec![ctx.gen_gray(|u, v| ((if vert { v } else { u }) * n).fract())]) -} - -fn gradient_linear_2(ctx: &Ctx) -> CookResult { - let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical")); - Ok(vec![ctx.gen_gray(|u, v| 1.0 - ((((if vert { v } else { u }) * n).fract()) * 2.0 - 1.0).abs())]) -} - -fn gradient_radial(ctx: &Ctx) -> CookResult { - let r = ctx.f("radius").max(1e-3); - Ok(vec![ctx.gen_gray(|u, v| (1.0 - ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() / r).clamp(0.0, 1.0))]) -} - -fn hexagons(ctx: &Ctx) -> CookResult { - let n = ctx.i("tiling").max(1) as f32; - let (size, bevel) = (ctx.f("size"), ctx.f("bevel").max(1e-3)); - let sq3 = 3f32.sqrt(); - // Flat-top hexes of circumradius 1: two lattices, (3i, √3j) and (3i + 1.5, √3j + √3/2). The - // image holds n lattice periods across and the nearest whole number down, so it tiles. - let m = (n * 3.0 / sq3).round().max(1.0); - Ok(vec![ctx.gen_gray(|u, v| { - let (px, py) = (u * n * 3.0, v * m * sq3); - let a = ((px / 3.0).round() * 3.0, (py / sq3).round() * sq3); - let b = (((px - 1.5) / 3.0).round() * 3.0 + 1.5, ((py - sq3 * 0.5) / sq3).round() * sq3 + sq3 * 0.5); - let da = (px - a.0).powi(2) + (py - a.1).powi(2); - let db = (px - b.0).powi(2) + (py - b.1).powi(2); - let (cx, cy) = if da < db { a } else { b }; - let (dx, dy) = ((px - cx).abs(), (py - cy).abs()); - let inr = sq3 * 0.5; - let d = (dy / inr).max((dx * inr + dy * 0.5) / inr); - ((size - d) / bevel).clamp(0.0, 1.0) - })]) -} - -fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) { - (((u * n).fract() - 0.5) * 2.0, ((v * n).fract() - 0.5) * 2.0) -} - -fn polygon(ctx: &Ctx) -> CookResult { - let sides = ctx.i("sides").clamp(3, 64) as f32; - let (sc, ang, grad, n) = (ctx.f("scale").max(1e-3), ctx.f("angle"), ctx.f("gradient"), ctx.i("tiling").max(1) as f32); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, n); - let (x, y) = rot(x, y, ang); - let a = y.atan2(x); - let seg = TAU / sides; - let d = (x * x + y * y).sqrt() * ((a.rem_euclid(seg) - seg * 0.5).cos()) / (seg * 0.5).cos(); - let e = 1.0 - d / sc; - if grad <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / grad).clamp(0.0, 1.0) } - })]) -} - -fn scratches(ctx: &Ctx) -> CookResult { - let count = ctx.i("count").clamp(0, 5000) as u32; - let (len, width, ang, ar, s) = (ctx.f("length"), ctx.f("width") / ctx.w as f32, ctx.f("angle"), ctx.f("angle_random"), ctx.seed); - let segs: Vec<([f32; 2], [f32; 2], f32)> = (0..count) - .map(|i| { - let p = [rand1(i * 4, s), rand1(i * 4 + 1, s)]; - let a = (ang + (rand1(i * 4 + 2, s) - 0.5) * ar) * TAU; - let l = len * (0.5 + 0.5 * rand1(i * 4 + 3, s)); - ([p[0], p[1]], [a.cos() * l, -a.sin() * l], 0.4 + 0.6 * rand1(i * 7 + 5, s)) - }) - .collect(); - // Bin segments by their bounding boxes on a coarse grid so each pixel tests only nearby ones. - const G: usize = 16; - let mut bins: Vec<Vec<usize>> = vec![Vec::new(); G * G]; - for (k, (p, d, _)) in segs.iter().enumerate() { - let (x0, x1) = (p[0].min(p[0] + d[0]) - width, p[0].max(p[0] + d[0]) + width); - let (y0, y1) = (p[1].min(p[1] + d[1]) - width, p[1].max(p[1] + d[1]) + width); - for gy in (y0 * G as f32).floor() as i32..=(y1 * G as f32).floor() as i32 { - for gx in (x0 * G as f32).floor() as i32..=(x1 * G as f32).floor() as i32 { - if let Some(b) = bins.get_mut(gy.rem_euclid(G as i32) as usize * G + gx.rem_euclid(G as i32) as usize) { - b.push(k); - } - } - } - } - Ok(vec![ctx.gen_gray(|u, v| { - let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)]; - let mut best: f32 = 0.0; - for k in bin { - let (p, d, lum) = segs[*k]; - for (ox, oy) in [(0.0, 0.0), (1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] { - let (qx, qy) = (u - p[0] + ox, v - p[1] + oy); - let t = ((qx * d[0] + qy * d[1]) / (d[0] * d[0] + d[1] * d[1]).max(1e-9)).clamp(0.0, 1.0); - let (ex, ey) = (qx - d[0] * t, qy - d[1] * t); - let dist = (ex * ex + ey * ey).sqrt(); - if dist < width { - best = best.max((1.0 - dist / width) * lum * (1.0 - (t * 2.0 - 1.0).abs().powi(4))); - } - } - } - best - })]) -} - -fn shape_node(ctx: &Ctx) -> CookResult { - let (k, n, size, sxy, ang) = (ctx.i("pattern"), ctx.i("tiling").max(1) as f32, ctx.f("size").max(1e-3), ctx.v2("size_xy"), ctx.f("angle")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, n); - let (x, y) = rot(x, y, ang); - shape(k, x / (size * sxy[0].max(1e-3)), y / (size * sxy[1].max(1e-3))) - })]) -} - -fn splatter(ctx: &Ctx) -> CookResult { - let count = ctx.i("count").clamp(1, 20000) as u32; - let (k, size, sr, lr, s) = (ctx.i("pattern"), ctx.f("size"), ctx.f("size_random"), ctx.f("lum_random"), ctx.seed); - let items: Vec<([f32; 2], f32, f32, f32)> = (0..count) - .map(|i| ([rand1(i * 5, s), rand1(i * 5 + 1, s)], size * (1.0 - sr * rand1(i * 5 + 2, s)), 1.0 - lr * rand1(i * 5 + 3, s), rand1(i * 5 + 4, s))) - .collect(); - let base = Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]); - Ok(vec![stamp(ctx, base, &items, |x, y, _| shape(k, x, y), |a, b| a.max(b))]) -} - -/// Splat `items` (center, radius, luminance, rotation turns) onto `base` with `f` combining. -fn stamp( - ctx: &Ctx, - base: Image, - items: &[([f32; 2], f32, f32, f32)], - sh: impl Fn(f32, f32, usize) -> f32 + Sync, - combine: impl Fn(f32, f32) -> f32 + Sync, -) -> Image { - const G: usize = 32; - let mut bins: Vec<Vec<usize>> = vec![Vec::new(); G * G]; - for (i, (c, r, _, _)) in items.iter().enumerate() { - let r = r * 1.42; - for gy in ((c[1] - r) * G as f32).floor() as i32..=((c[1] + r) * G as f32).floor() as i32 { - for gx in ((c[0] - r) * G as f32).floor() as i32..=((c[0] + r) * G as f32).floor() as i32 { - if let Some(b) = bins.get_mut(gy.rem_euclid(G as i32) as usize * G + gx.rem_euclid(G as i32) as usize) - && !b.contains(&i) - { - b.push(i); - } - } - } - } - let tile = ctx.tile; - Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let mut acc = base.sample_nearest(u, v, false)[0]; - let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)]; - for i in bin { - let (c, r, lum, rt) = items[*i]; - if r <= 0.0 { - continue; - } - let mut dx = u - c[0]; - let mut dy = v - c[1]; - if tile { - dx -= dx.round(); - dy -= dy.round(); - } - let (x, y) = rot(dx / r, dy / r, rt); - if x.abs() <= 1.0 && y.abs() <= 1.0 { - acc = combine(acc, sh(x, y, *i) * lum); - } - } - [acc, 0.0, 0.0, 0.0] - }) -} - -fn star(ctx: &Ctx) -> CookResult { - let pts = ctx.i("points").clamp(2, 64) as f32; - let (inner, sc, n) = (ctx.f("inner"), ctx.f("scale").max(1e-3), ctx.i("tiling").max(1) as f32); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, n); - let a = y.atan2(x) + PI / 2.0; - let seg = TAU / pts; - let t = ((a.rem_euclid(seg) / seg) * 2.0 - 1.0).abs(); - let rad = sc * (inner + (1.0 - inner) * t); - ((x * x + y * y).sqrt() <= rad) as i32 as f32 - })]) -} - -fn stripes(ctx: &Ctx) -> CookResult { - let n = ctx.i("count").max(1) as f32; - let (w, soft, ang) = (ctx.f("width"), ctx.f("softness").max(1e-3), ctx.f("angle")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, _) = rot(u - 0.5, v - 0.5, ang); - let f = (x * n).rem_euclid(1.0); - let d = (f - 0.5).abs() * 2.0; - ((w - d) / soft + 0.5).clamp(0.0, 1.0) - })]) -} - -fn tile_params(ctx: &Ctx) -> (f32, f32, f32, f32, f32, f32, f32, f32, u32) { - ( - ctx.i("x_amount").max(1) as f32, - ctx.i("y_amount").max(1) as f32, - ctx.f("scale"), - ctx.f("scale_random"), - ctx.f("offset"), - ctx.f("position_random"), - ctx.f("rotation_random"), - ctx.f("lum_random"), - ctx.seed, - ) -} - -fn tile_generator(ctx: &Ctx) -> CookResult { - let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx); - let (k, sxy, mr) = (ctx.i("pattern"), ctx.v2("size_xy"), ctx.f("mask_random")); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * ny).floor(); - let mut best: f32 = 0.0; - // Shapes may reach into neighbouring cells (scale > 1, position jitter): check 3×3. - for dj in -1..=1 { - for di in -1..=1 { - let r = row + dj as f32; - let x = u * nx + off * r; - let col = x.floor() + di as f32; - let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32)); - if mr > 0.0 && rand2(ci, ri, s ^ 0x55) < mr { - continue; - } - let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr; - let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr; - let size = sc * (1.0 - sr * rand2(ci, ri, s ^ 3)); - if size <= 0.0 { - continue; - } - let (lx, ly) = ((x - col - 0.5 - jx) * 2.0, (v * ny - r - 0.5 - jy) * 2.0); - let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr); - let val = shape(k, lx / (size * sxy[0].max(1e-3)), ly / (size * sxy[1].max(1e-3))); - best = best.max(val * (1.0 - lr * rand2(ci, ri, s ^ 5))); - } - } - best - })]) -} - -fn tile_sampler(ctx: &Ctx) -> CookResult { - let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx); - let pattern = - ctx.input(0).map(|p| p.to_gray()).unwrap_or_else(|| Image::generate_uv(64, 64, Kind::Gray, |u, v| [shape(3, u * 2.0 - 1.0, v * 2.0 - 1.0); 4])); - let smap = ctx.input(1).map(|p| p.to_gray()); - let add = ctx.i("blend") == 1; - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * ny).floor(); - let mut acc: f32 = 0.0; - for dj in -1..=1 { - for di in -1..=1 { - let r = row + dj as f32; - let x = u * nx + off * r; - let col = x.floor() + di as f32; - let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32)); - let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr; - let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr; - let mapk = smap.as_ref().map_or(1.0, |m| m.sample_gray((col + 0.5) / nx, (r + 0.5) / ny, true)); - let size = sc * mapk * (1.0 - sr * rand2(ci, ri, s ^ 3)); - if size <= 0.0 { - continue; - } - let (lx, ly) = ((x - col - 0.5 - jx) / size, (v * ny - r - 0.5 - jy) / size); - let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr); - if lx.abs() > 0.5 || ly.abs() > 0.5 { - continue; - } - let val = pattern.sample_gray(lx + 0.5, ly + 0.5, false) * (1.0 - lr * rand2(ci, ri, s ^ 5)); - acc = if add { acc + val } else { acc.max(val) }; - } - } - acc.min(1.0) - })]) -} - -fn weave(ctx: &Ctx) -> CookResult { - let n = ctx.i("tiling").max(1) as f32; - let w = ctx.f("width").clamp(0.01, 1.0); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = (u * n, v * n); - let (cx, cy) = (x.floor() as i32, y.floor() as i32); - let (fx, fy) = (x.fract(), y.fract()); - // Horizontal thread across the cell row, vertical thread down the column; which is on - // top alternates in a checker. - let hthread = ((fy - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fy - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt(); - let vthread = ((fx - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fx - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt(); - let h_top = (cx + cy) & 1 == 0; - // The thread on top bulges along its length. - let hb = hthread * (0.6 + 0.4 * (fx * PI).sin()); - let vb = vthread * (0.6 + 0.4 * (fy * PI).sin()); - if h_top { hb.max(vb * 0.6) } else { vb.max(hb * 0.6) } - })]) -} - -fn waveform(ctx: &Ctx) -> CookResult { - let n = ctx.i("count").max(1) as f32; - let (amp, ang) = (ctx.f("amplitude"), ctx.f("angle")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = rot(u - 0.5, v - 0.5, ang); - let w = (y * TAU * 2.0).sin() * amp * 0.1; - ((x + w) * TAU * n).sin() * 0.5 + 0.5 - })]) -} diff --git a/crates/nodes/src/patterns_more.rs b/crates/nodes/src/patterns_more.rs deleted file mode 100644 index f1178e97..00000000 --- a/crates/nodes/src/patterns_more.rs +++ /dev/null @@ -1,532 +0,0 @@ -//! More Texture generators › Patterns: tilings (herringbone, basketweave, planks, scales, -//! triangles, octagons, tread plate), grids, shapes and gradients. Tile patterns share gap, bevel -//! and luminance-random parameters; every tiling repeats a whole number of times per image. - -use std::f32::consts::{SQRT_2, TAU}; - -use crate::catalog::{B, CookResult, Ctx, NodeDef, node}; -use crate::noise::rand2; -use crate::patterns::PATTERNS; - -/// Rotate `(x, y)` by `turns`. -#[inline] -fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) { - let (s, c) = (turns * TAU).sin_cos(); - (x * c - y * s, x * s + y * c) -} - -/// Coverage from a signed inside distance `e`: hard when `soft` is 0, else a ramp of width `soft`. -#[inline] -fn fill(e: f32, soft: f32) -> f32 { - if soft <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / soft).clamp(0.0, 1.0) } -} - -/// A beveled tile from the distance `e` to its edge: `gap` eats the edge, `bevel` ramps up. -#[inline] -fn tile_height(e: f32, t: &TileLook, rnd: f32) -> f32 { - let e = e - t.gap * 0.5; - if e <= 0.0 { 0.0 } else { (e / t.bevel).min(1.0) * (1.0 - t.lum_random * rnd) } -} - -/// Soft bands around integer + 0.5 of `t`: `width` 0..1 of each period, `soft` edge. -#[inline] -fn band(t: f32, width: f32, soft: f32) -> f32 { - let d = (t.rem_euclid(1.0) - 0.5).abs() * 2.0; - ((width - d) / soft.max(1e-3) + 0.5).clamp(0.0, 1.0) -} - -/// Local coordinates -1..1 in an `n`×`n` repetition. -#[inline] -fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) { - ((u * n).rem_euclid(1.0) * 2.0 - 1.0, (v * n).rem_euclid(1.0) * 2.0 - 1.0) -} - -struct TileLook { - gap: f32, - bevel: f32, - lum_random: f32, - seed: u32, -} - -fn look(ctx: &Ctx) -> TileLook { - TileLook { gap: ctx.f("gap"), bevel: ctx.f("bevel").max(1e-4), lum_random: ctx.f("lum_random"), seed: ctx.seed } -} - -/// The gap, bevel and luminance-random parameters of tile patterns. -fn with_look(b: B, gap: f32, bevel: f32) -> B { - b.float("gap", "Gap", gap, 0.0, 0.5).float("bevel", "Bevel", bevel, 0.0, 1.0).float("lum_random", "Luminance random", 0.3, 0.0, 1.0) -} - -fn n(ctx: &Ctx, id: &str) -> f32 { - ctx.i(id).max(1) as f32 -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let p = |id, label| node(id, label, PATTERNS).generator(); - vec![ - p("grid_lines", "Grid Lines") - .desc("A grid of lines.") - .int("tiling", "Tiling", 8, 1, 128) - .float("width", "Line width", 0.06, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 0.5) - .gray_out() - .cook(grid_lines), - p("dots_grid", "Dots Grid") - .desc("Round dots on a grid (perforated metal, polka dots).") - .int("tiling", "Tiling", 8, 1, 128) - .float("radius", "Diameter", 0.6, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 0.5) - .boolean("staggered", "Staggered rows", true) - .gray_out() - .cook(dots_grid), - with_look(p("diamond_grid", "Diamond Grid").desc("Beveled diamond (45°) tiles.").int("tiling", "Tiling", 4, 1, 64), 0.05, 0.15) - .gray_out() - .cook(diamond_grid), - with_look( - p("herringbone", "Herringbone").desc("Planks laid in a herringbone pattern.").int("tiling", "Tiling", 2, 1, 32).int( - "length", - "Plank length", - 3, - 2, - 8, - ), - 0.08, - 0.2, - ) - .gray_out() - .cook(herringbone), - with_look( - p("basketweave", "Basketweave").desc("Squares of parallel planks alternating direction.").int("tiling", "Tiling", 4, 1, 64).int( - "strips", - "Planks per square", - 3, - 1, - 16, - ), - 0.08, - 0.2, - ) - .gray_out() - .cook(basketweave), - p("chevron", "Chevron") - .desc("Zigzag bands.") - .int("count", "Bands", 8, 1, 128) - .int("zigs", "Zigzags", 4, 1, 64) - .float("height", "Zig height", 1.0, 0.0, 8.0) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.1, 0.0, 1.0) - .gray_out() - .cook(chevron), - p("fish_scales", "Fish Scales") - .desc("Overlapping rows of round scales (height).") - .int("tiling", "Tiling", 6, 1, 64) - .float("radius", "Radius", 0.65, 0.5, 1.0) - .float("lum_random", "Luminance random", 0.2, 0.0, 1.0) - .gray_out() - .cook(fish_scales), - with_look(p("triangle_grid", "Triangle Grid").desc("Beveled triangle tiles.").int("tiling", "Tiling", 6, 1, 64), 0.04, 0.12) - .gray_out() - .cook(triangle_grid), - p("spiral", "Spiral") - .desc("An Archimedean spiral.") - .float("turns", "Turns", 6.0, 0.0, 64.0) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.3, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(spiral), - p("concentric_rings", "Concentric Rings") - .desc("Rings around the center.") - .float("count", "Rings", 8.0, 0.0, 64.0) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.3, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(concentric_rings), - p("gradient_axial", "Gradient Axial") - .desc("A ramp from point 1 (black) to point 2 (white).") - .float2("point_1", "Point 1", [0.2, 0.5], 0.0, 1.0) - .float2("point_2", "Point 2", [0.8, 0.5], 0.0, 1.0) - .gray_out() - .cook(gradient_axial), - p("gradient_circular", "Gradient Circular") - .desc("A ramp around the center (by angle).") - .angle("angle", "Start angle", 0.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(gradient_circular), - p("cross", "Cross") - .desc("A plus-shaped cross.") - .float("length", "Arm length", 0.8, 0.0, 1.0) - .float("thickness", "Thickness", 0.25, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .int("tiling", "Tiling", 1, 1, 32) - .gray_out() - .cook(cross), - p("rounded_rectangle", "Rounded Rectangle") - .desc("A rectangle with rounded corners.") - .float2("size", "Size", [0.8, 0.6], 0.0, 1.0) - .float("radius", "Corner radius", 0.2, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .int("tiling", "Tiling", 1, 1, 32) - .gray_out() - .cook(rounded_rectangle), - p("ring", "Ring") - .desc("A circular ring.") - .float("radius", "Radius", 0.6, 0.0, 1.0) - .float("width", "Width", 0.15, 0.0, 1.0) - .float("softness", "Softness", 0.05, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 32) - .gray_out() - .cook(ring), - with_look( - p("arc_pavement", "Arc Pavement") - .desc("Cobblestones laid in overlapping fan-shaped arcs.") - .int("tiling", "Tiling", 3, 1, 32) - .int("bands", "Rows per arc", 4, 1, 16) - .int("stones", "Stones in outer row", 7, 1, 32), - 0.08, - 0.25, - ) - .gray_out() - .cook(arc_pavement), - with_look(p("octagon_tiles", "Octagon Tiles").desc("Octagons with small square tiles between them.").int("tiling", "Tiling", 4, 1, 64), 0.03, 0.08) - .gray_out() - .cook(octagon_tiles), - with_look( - p("planks", "Planks") - .desc("Rows of floor boards of random length, staggered.") - .int("rows", "Rows", 8, 1, 64) - .float("length", "Plank length", 0.33, 0.02, 1.0) - .float("length_random", "Length random", 0.5, 0.0, 1.0), - 0.06, - 0.15, - ) - .gray_out() - .cook(planks), - p("tread_plate", "Tread Plate") - .desc("Raised diagonal bars alternating direction, like metal floor plates (height).") - .int("tiling", "Tiling", 6, 1, 64) - .float("length", "Bar length", 1.0, 0.0, 1.4) - .float("width", "Bar width", 0.3, 0.01, 1.0) - .gray_out() - .cook(tread_plate), - ] -} - -fn grid_lines(ctx: &Ctx) -> CookResult { - let (t, w, soft) = (n(ctx, "tiling"), ctx.f("width"), ctx.f("softness")); - Ok(vec![ctx.gen_gray(|u, v| { - let d = |a: f32| { - let f = (a * t).rem_euclid(1.0); - f.min(1.0 - f) - }; - fill(w * 0.5 - d(u).min(d(v)), soft) - })]) -} - -fn dots_grid(ctx: &Ctx) -> CookResult { - let (t, r, soft, stag) = (n(ctx, "tiling"), ctx.f("radius"), ctx.f("softness"), ctx.b("staggered")); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * t).floor(); - // A parity shift (not row × offset) keeps the pattern seamless for any row count. - let shift = if stag && (row as i32) & 1 == 1 { 0.5 } else { 0.0 }; - let (x, y) = ((u * t + shift).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5); - fill(r * 0.5 - (x * x + y * y).sqrt(), soft * 0.5) - })]) -} - -fn diamond_grid(ctx: &Ctx) -> CookResult { - let (t, l) = (n(ctx, "tiling"), look(ctx)); - let ti = t as i32; - Ok(vec![ctx.gen_gray(|u, v| { - let (a, b) = ((u + v) * t, (u - v) * t); - let (fa, fb) = (a.rem_euclid(1.0), b.rem_euclid(1.0)); - let e = fa.min(1.0 - fa).min(fb).min(1.0 - fb); - // Canonical diamond index: (A, B) ~ (A + t, B ± t). - let (ia, ib) = (a.floor() as i32, b.floor() as i32); - let k = ib.div_euclid(ti); - tile_height(e, &l, rand2((ia - k * ti).rem_euclid(2 * ti), ib - k * ti, l.seed)) - })]) -} - -fn herringbone(ctx: &Ctx) -> CookResult { - let (t, len, lk) = (n(ctx, "tiling") as i32, ctx.i("length").clamp(2, 8), look(ctx)); - let lf = len as f32; - let span = (t * 2 * len) as f32; - // 1 × L planks: a horizontal plank [0, L)×[0, 1) and a vertical one [L, L+1)×[1-L, 1) repeat - // on the lattice m·(1, 1) + n·(L, -L), which has period 2L on both axes. - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = (u * span, v * span); - let (m0, n0) = (((x + y) * 0.5).floor() as i32, ((x - y) / (2.0 * lf)).floor() as i32); - for dm in -(len / 2 + 2)..=1 { - for dn in -2..=1 { - let (m, nn) = (m0 + dm, n0 + dn); - let (qx, qy) = (x - (m + nn * len) as f32, y - (m - nn * len) as f32); - let hit = if (0.0..lf).contains(&qx) && (0.0..1.0).contains(&qy) { - Some((qx.min(lf - qx).min(qy).min(1.0 - qy), 0)) - } else if (lf..lf + 1.0).contains(&qx) && (1.0 - lf..1.0).contains(&qy) { - Some(((qx - lf).min(lf + 1.0 - qx).min(qy - 1.0 + lf).min(1.0 - qy), 1)) - } else { - None - }; - if let Some((e, kind)) = hit { - let k = nn.div_euclid(t); - let (cm, cn) = ((m - k * len * t).rem_euclid(2 * len * t), nn - k * t); - return tile_height(e, &lk, rand2(cm * 2 + kind, cn, lk.seed)); - } - } - } - 0.0 - })]) -} - -fn basketweave(ctx: &Ctx) -> CookResult { - let (t, strips, l) = (n(ctx, "tiling"), n(ctx, "strips"), look(ctx)); - Ok(vec![ctx.gen_gray(|u, v| { - let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32); - let (fx, fy) = ((u * t).rem_euclid(1.0), (v * t).rem_euclid(1.0)); - let horizontal = (cx + cy) & 1 == 0; - let (across, along) = if horizontal { (fy * strips, fx * strips) } else { (fx * strips, fy * strips) }; - let fa = across.rem_euclid(1.0); - let e = fa.min(1.0 - fa).min(along).min(strips - along); - let id = (cy.rem_euclid(t as i32) * t as i32 + cx.rem_euclid(t as i32)) * 16 + across.floor() as i32; - tile_height(e, &l, rand2(id, 0, l.seed)) - })]) -} - -fn chevron(ctx: &Ctx) -> CookResult { - let (c, z, hgt, w, soft) = (n(ctx, "count"), n(ctx, "zigs"), ctx.f("height"), ctx.f("width"), ctx.f("softness")); - Ok(vec![ctx.gen_gray(|u, v| { - let zig = ((u * z).rem_euclid(1.0) - 0.5).abs() * 2.0; - band(v * c + zig * hgt, w, soft) - })]) -} - -/// The topmost scale over `(x, y)` (in cells) of a staggered scale layout: rows 0.5 apart, odd -/// rows shifted by half a cell, earlier rows on top. Returns (column, row, dx, dy, d / r). -fn scale_hit(x: f32, y: f32, r: f32) -> Option<(i32, i32, f32, f32, f32)> { - let j0 = ((y - r) * 2.0).floor() as i32; - let j1 = ((y + r) * 2.0).ceil() as i32; - for j in j0..=j1 { - let shift = if j & 1 == 1 { 0.5 } else { 0.0 }; - let i = (x - shift).round() as i32; - let (dx, dy) = (x - (i as f32 + shift), y - j as f32 * 0.5); - let d = (dx * dx + dy * dy).sqrt(); - if d < r { - return Some((i, j, dx, dy, d / r)); - } - } - None -} - -fn fish_scales(ctx: &Ctx) -> CookResult { - let (t, r, lr, s) = (n(ctx, "tiling"), ctx.f("radius").clamp(0.5, 1.0), ctx.f("lum_random"), ctx.seed); - let ti = t as i32; - Ok(vec![ctx.gen_gray(|u, v| { - let Some((i, j, _, _, d)) = scale_hit(u * t, v * t, r) else { - return 0.0; - }; - (1.0 - d * d).sqrt() * (1.0 - lr * rand2(i.rem_euclid(ti), j.rem_euclid(2 * ti), s)) - })]) -} - -fn triangle_grid(ctx: &Ctx) -> CookResult { - let (t, l) = (n(ctx, "tiling"), look(ctx)); - // Rows of near-equilateral triangles; an even row count keeps the half-cell row shift seamless. - let rows = (2.0 * (t * 0.577).round()).max(2.0); - let (ti, ri) = (t as i32, rows as i32); - let k = 2.0 / 5f32.sqrt(); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * rows).floor() as i32; - let fy = (v * rows).rem_euclid(1.0); - let x = u * t + if row & 1 == 1 { 0.5 } else { 0.0 }; - let col = x.floor() as i32; - let dx = x.rem_euclid(1.0) - 0.5; - let (e, id) = if dx.abs() <= fy * 0.5 { - ((1.0 - fy).min((fy * 0.5 - dx.abs()) * k), col * 2) - } else { - // A down-pointing triangle centered on the nearer whole column. - let (c, ddx) = if dx < 0.0 { (col, dx + 0.5) } else { (col + 1, dx - 0.5) }; - (fy.min(((1.0 - fy) * 0.5 - ddx.abs()) * k), c * 2 + 1) - }; - tile_height(e, &l, rand2(id.rem_euclid(2 * ti), row.rem_euclid(ri), l.seed)) - })]) -} - -fn spiral(ctx: &Ctx) -> CookResult { - let (turns, w, soft, t) = (ctx.f("turns"), ctx.f("width"), ctx.f("softness"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - let r = (x * x + y * y).sqrt(); - if r > 1.0 { - return 0.0; - } - band(r * turns - y.atan2(x) / TAU, w, soft) - })]) -} - -fn concentric_rings(ctx: &Ctx) -> CookResult { - let (c, w, soft, t) = (ctx.f("count"), ctx.f("width"), ctx.f("softness"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - band((x * x + y * y).sqrt() * c, w, soft) - })]) -} - -fn gradient_axial(ctx: &Ctx) -> CookResult { - let (a, b) = (ctx.v2("point_1"), ctx.v2("point_2")); - let (dx, dy) = (b[0] - a[0], b[1] - a[1]); - let len2 = (dx * dx + dy * dy).max(1e-8); - Ok(vec![ctx.gen_gray(|u, v| (((u - a[0]) * dx + (v - a[1]) * dy) / len2).clamp(0.0, 1.0))]) -} - -fn gradient_circular(ctx: &Ctx) -> CookResult { - let (a, t) = (ctx.f("angle"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - ((-y).atan2(x) / TAU - a).rem_euclid(1.0) - })]) -} - -fn cross(ctx: &Ctx) -> CookResult { - let (len, th, soft, a, t) = (ctx.f("length"), ctx.f("thickness") * 0.5, ctx.f("softness"), ctx.f("angle"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - let (x, y) = rot(x, y, a); - let arm = |p: f32, q: f32| (len - p.abs()).min(th - q.abs()); - fill(arm(x, y).max(arm(y, x)), soft) - })]) -} - -fn rounded_rectangle(ctx: &Ctx) -> CookResult { - let (sz, rad, soft, a, t) = (ctx.v2("size"), ctx.f("radius"), ctx.f("softness"), ctx.f("angle"), n(ctx, "tiling")); - let r = rad.min(sz[0]).min(sz[1]).max(0.0); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - let (x, y) = rot(x, y, a); - // Signed distance to a rounded box (negative inside). - let (qx, qy) = (x.abs() - sz[0] + r, y.abs() - sz[1] + r); - let d = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r; - fill(-d, soft) - })]) -} - -fn ring(ctx: &Ctx) -> CookResult { - let (rad, w, soft, t) = (ctx.f("radius"), ctx.f("width") * 0.5, ctx.f("softness"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - fill(w - ((x * x + y * y).sqrt() - rad).abs(), soft) - })]) -} - -fn arc_pavement(ctx: &Ctx) -> CookResult { - let (t, bands, stones, l) = (n(ctx, "tiling"), n(ctx, "bands"), n(ctx, "stones"), look(ctx)); - let ti = t as i32; - let r = 0.75; - Ok(vec![ctx.gen_gray(|u, v| { - let Some((i, j, dx, dy, rr)) = scale_hit(u * t, v * t, r) else { - return 0.0; - }; - let band_f = rr * bands; - let k = band_f.floor(); - let count = (stones * (k + 0.5) / bands).round().max(1.0); - let a = (dy.atan2(dx) / TAU + 0.5) * count; - let fr = band_f.rem_euclid(1.0); - let fa = a.rem_euclid(1.0); - // Distances in band-width units: radial, and along the arc at this radius. - let e = fr.min(1.0 - fr).min(fa.min(1.0 - fa) * TAU * band_f.max(0.5) / count); - let id = ((j.rem_euclid(2 * ti) * ti + i.rem_euclid(ti)) * 32 + k as i32) * 64 + a.floor() as i32; - tile_height(e, &l, rand2(id, 7, l.seed)) - })]) -} - -fn octagon_tiles(ctx: &Ctx) -> CookResult { - let (t, l) = (n(ctx, "tiling"), look(ctx)); - let ti = t as i32; - // A regular octagon in a unit cell: its corner cuts lie on |x| + |y| = 0.5 + side / 2. - let cut = 0.5 + 0.5 / (1.0 + SQRT_2); - Ok(vec![ctx.gen_gray(|u, v| { - let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32); - let (x, y) = ((u * t).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5); - let (ax, ay) = (x.abs(), y.abs()); - if ax + ay <= cut { - let e = (0.5 - ax.max(ay)).min((cut - ax - ay) / SQRT_2); - tile_height(e, &l, rand2(cx.rem_euclid(ti), cy.rem_euclid(ti), l.seed)) - } else { - // The small square around the nearest cell corner. - let e = (ax + ay - cut) / SQRT_2; - let (kx, ky) = (cx + (x > 0.0) as i32, cy + (y > 0.0) as i32); - tile_height(e, &l, rand2(kx.rem_euclid(ti), ky.rem_euclid(ti), l.seed ^ 0x6d)) - } - })]) -} - -fn planks(ctx: &Ctx) -> CookResult { - let (rows, l) = (n(ctx, "rows"), look(ctx)); - let count = (1.0 / ctx.f("length").max(0.02)).round().clamp(1.0, 64.0); - let (ci, ri) = (count as i32, rows as i32); - let jit = ctx.f("length_random").clamp(0.0, 1.0) * 0.4; - let s = ctx.seed; - Ok(vec![ctx.gen_gray(|u, v| { - let row = ((v * rows).floor() as i32).rem_euclid(ri); - let fy = (v * rows).rem_euclid(1.0); - let t = u * count + rand2(row, 0, s ^ 0x11) * count; - // Plank ends: one per whole step of `t`, jittered; indices wrap so each row tiles. - let cut = |j: i32| j as f32 + (rand2(j.rem_euclid(ci), row, s) - 0.5) * 2.0 * jit; - let j = t.floor() as i32; - let j = if t < cut(j) { - j - 1 - } else if t >= cut(j + 1) { - j + 1 - } else { - j - }; - let along = (t - cut(j)).min(cut(j + 1) - t) / count * rows; - let e = along.min(fy).min(1.0 - fy); - tile_height(e, &l, rand2(j.rem_euclid(ci), row, s ^ 0x22)) - })]) -} - -fn tread_plate(ctx: &Ctx) -> CookResult { - let (t, len, w) = (n(ctx, "tiling"), ctx.f("length") * 0.5, ctx.f("width").max(0.01) * 0.5); - Ok(vec![ctx.gen_gray(|u, v| { - let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32); - let (x, y) = ((u * t).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5); - let turn = if (cx + cy) & 1 == 0 { 0.125 } else { -0.125 }; - let (x, y) = rot(x, y, turn); - // An elongated lens with a flat top and rounded flanks. - let d = ((x / len.max(1e-3)).powi(2) + (y / w).powi(2)).sqrt(); - (1.0 - d.powi(4)).max(0.0).sqrt() - })]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use crate::{Ctx, find, resolve_params}; - - #[test] - fn tilings_wrap_seamlessly() { - for id in ["herringbone", "planks", "triangle_grid", "fish_scales", "arc_pavement", "diamond_grid", "octagon_tiles"] { - let def = find(id).unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: 128, h: 128, seed: 5, tile: true, inputs: &[], params: ¶ms, resource: &no_res, vars: &vars }; - let img = &(def.cook)(&ctx).unwrap()[0]; - // Sampling the pattern one period further along either axis gives the same image: the - // last column/row continues into the first like any interior neighbour. - let (mut seam, mut inner) = (0.0f32, 0.0f32); - for k in 0..128 { - seam += (img.get(127, k, false)[0] - img.get(0, k, false)[0]).abs() + (img.get(k, 127, false)[0] - img.get(k, 0, false)[0]).abs(); - inner += (img.get(63, k, false)[0] - img.get(64, k, false)[0]).abs() + (img.get(k, 63, false)[0] - img.get(k, 64, false)[0]).abs(); - } - assert!(seam <= inner * 3.0 + 1.0, "{id}: seam {seam} vs inner {inner}"); - assert!(img.mean()[0] > 0.05, "{id} is empty"); - } - } -} diff --git a/crates/nodes/src/port_definition.rs b/crates/nodes/src/port_definition.rs new file mode 100644 index 00000000..bf04636c --- /dev/null +++ b/crates/nodes/src/port_definition.rs @@ -0,0 +1,8 @@ +use crate::PortKind; + +#[derive(Clone, Debug)] +pub struct PortDefinition { + pub id: &'static str, + pub label: &'static str, + pub kind: PortKind, +} diff --git a/crates/nodes/src/port_kind.rs b/crates/nodes/src/port_kind.rs new file mode 100644 index 00000000..3ed49ec9 --- /dev/null +++ b/crates/nodes/src/port_kind.rs @@ -0,0 +1,9 @@ +/// What a port carries +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PortKind { + Gray, + Color, + /// Either; outputs of this kind follow the main input + Any, + Value, +} diff --git a/crates/nodes/src/random.rs b/crates/nodes/src/random.rs new file mode 100644 index 00000000..2f675584 --- /dev/null +++ b/crates/nodes/src/random.rs @@ -0,0 +1,10 @@ +// Lowbias32 integer hash by Chris Wellons, public domain +#[inline] +pub fn hash(mut x: u32) -> u32 { + x ^= x >> 16; + x = x.wrapping_mul(0x7feb_352d); + x ^= x >> 15; + x = x.wrapping_mul(0x846c_a68b); + x ^= x >> 16; + x +} diff --git a/crates/nodes/src/raster/capsule_raster.rs b/crates/nodes/src/raster/capsule_raster.rs new file mode 100644 index 00000000..2c2eaa0e --- /dev/null +++ b/crates/nodes/src/raster/capsule_raster.rs @@ -0,0 +1,62 @@ +use super::capsule_segment::CapsuleSegment; + +pub(crate) struct CapsuleRaster { + segments: Vec<CapsuleSegment>, + radius: f32, + grid_side: usize, + cell_size: [f32; 2], + bins: Vec<Vec<u32>>, + image_size: [f32; 2], + tile: bool, +} + +impl CapsuleRaster { + pub fn new(segments: Vec<CapsuleSegment>, radius: f32, w: u32, h: u32, tile: bool) -> CapsuleRaster { + let radius = if radius.is_finite() { radius.max(0.0) } else { 0.0 }; + let reach = radius + 1.0; + let grid_side = ((w.max(h) as f32 / (reach * 4.0).max(8.0)) as usize).clamp(1, 128); + let cell_size = [w as f32 / grid_side as f32, h as f32 / grid_side as f32]; + let mut bins: Vec<Vec<u32>> = vec![Vec::new(); grid_side * grid_side]; + for (index, segment) in segments.iter().enumerate() { + if !segment.start.iter().chain(&segment.end).all(|v| v.is_finite()) { + continue; + } + let span = |start: f32, end: f32, cell: f32| { + let first = ((start.min(end) - reach) / cell).floor() as i64; + (first, (((start.max(end) + reach) / cell).floor() as i64).min(first + grid_side as i64 - 1)) + }; + + let ((x0, x1), (y0, y1)) = (span(segment.start[0], segment.end[0], cell_size[0]), span(segment.start[1], segment.end[1], cell_size[1])); + for gy in y0..=y1 { + for gx in x0..=x1 { + if !tile && (gx < 0 || gy < 0 || gx >= grid_side as i64 || gy >= grid_side as i64) { + continue; + } + if let Some(b) = bins.get_mut(gy.rem_euclid(grid_side as i64) as usize * grid_side + gx.rem_euclid(grid_side as i64) as usize) { + b.push(index as u32); + } + } + } + } + CapsuleRaster { segments, radius, grid_side, cell_size, bins, image_size: [w as f32, h as f32], tile } + } + + /// Coverage (0..1, the strongest segment's weight) at pixel coordinates `(x, y)` + pub fn coverage(&self, x: f32, y: f32) -> f32 { + let (gx, gy) = (((x / self.cell_size[0]) as usize).min(self.grid_side - 1), ((y / self.cell_size[1]) as usize).min(self.grid_side - 1)); + let mut best = 0.0f32; + for &index in self.bins.get(gy * self.grid_side + gx).into_iter().flatten() { + let Some(segment) = self.segments.get(index as usize) else { continue }; + let (mut px, mut py) = (x - segment.start[0], y - segment.start[1]); + if self.tile { + px -= (px / self.image_size[0]).round() * self.image_size[0]; + py -= (py / self.image_size[1]).round() * self.image_size[1]; + } + let (dx, dy) = (segment.end[0] - segment.start[0], segment.end[1] - segment.start[1]); + let t = ((px * dx + py * dy) / (dx * dx + dy * dy).max(1e-12)).clamp(0.0, 1.0); + let d = ((px - dx * t).powi(2) + (py - dy * t).powi(2)).sqrt(); + best = best.max((self.radius - d + 0.5).clamp(0.0, 1.0) * segment.weight); + } + best + } +} diff --git a/crates/nodes/src/raster/capsule_segment.rs b/crates/nodes/src/raster/capsule_segment.rs new file mode 100644 index 00000000..a58f6390 --- /dev/null +++ b/crates/nodes/src/raster/capsule_segment.rs @@ -0,0 +1,6 @@ +#[derive(Clone, Copy, Debug)] +pub(crate) struct CapsuleSegment { + pub start: [f32; 2], + pub end: [f32; 2], + pub weight: f32, +} diff --git a/crates/nodes/src/raster/composite.rs b/crates/nodes/src/raster/composite.rs new file mode 100644 index 00000000..c22ef2a3 --- /dev/null +++ b/crates/nodes/src/raster/composite.rs @@ -0,0 +1,22 @@ +use materialcraft_image::{Image, Kind}; + +use crate::CookContext; + +pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { + let background = context.any_or(0, Kind::Color, context.v4("background")); + let image = Image::generate(context.w, context.h, Kind::Color, |x, y| { + let foreground = foreground(x, y); + let background = background.get(i64::from(x), i64::from(y), false); + let foreground_alpha = foreground[3].clamp(0.0, 1.0); + let background_alpha = background[3].clamp(0.0, 1.0) * (1.0 - foreground_alpha); + let alpha = foreground_alpha + background_alpha; + if alpha <= 0.0 { + return [0.0; 4]; + } + + let channel = |index: usize| (foreground[index] * foreground_alpha + background[index] * background_alpha) / alpha; + [channel(0), channel(1), channel(2), alpha] + }); + + if context.b("color_mode") { image } else { image.to_gray() } +} diff --git a/crates/nodes/src/raster/mod.rs b/crates/nodes/src/raster/mod.rs new file mode 100644 index 00000000..f33956be --- /dev/null +++ b/crates/nodes/src/raster/mod.rs @@ -0,0 +1,7 @@ +mod capsule_raster; +mod capsule_segment; +mod composite; + +pub(crate) use capsule_raster::CapsuleRaster; +pub(crate) use capsule_segment::CapsuleSegment; +pub(crate) use composite::composite; diff --git a/crates/nodes/src/svg.rs b/crates/nodes/src/svg.rs deleted file mode 100644 index 564477b6..00000000 --- a/crates/nodes/src/svg.rs +++ /dev/null @@ -1,487 +0,0 @@ -//! Atomic › SVG: rasterizes SVG path data (the `d` attribute: M L H V C S Q T Z, absolute and -//! relative) with an even-odd or non-zero fill and an optional stroke. Fill coverage is exact -//! horizontally over four sub-scanlines per pixel. Also the shared capsule (thick line) -//! rasterizer used by the stroke, the Text node and the scratches. - -use materialcraft_image::{Image, Kind}; -use rayon::prelude::*; - -use crate::atomic::ATOMIC; -use crate::catalog::{CookResult, Ctx, NodeDef, node}; - -/// A leaf with a midrib slit, in 0..100 units. -const DEFAULT_PATH: &str = "M50 4 C80 20 94 55 52 96 L50 90 L48 96 C6 55 20 20 50 4 Z M49 22 Q46 55 50 84 Q54 55 51 22 Z"; - -/// Most points a path may flatten to (an allocation cap for hostile input). -const MAX_POINTS: usize = 400_000; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("svg", "SVG", ATOMIC) - .desc("Draws SVG path data (M L H V C S Q T Z, absolute and relative; y points down) filled and optionally stroked, anti-aliased.") - .atomic() - .generator() - .text("path", "Path data", DEFAULT_PATH) - .choice("units", "Units", &["0..1", "0..100"], 1) - .color("fill", "Fill color", [1.0, 1.0, 1.0, 1.0]) - .choice("fill_rule", "Fill rule", &["Even-odd", "Non-zero"], 1) - .float("stroke_width", "Stroke width", 0.0, 0.0, 64.0) - .color("stroke", "Stroke color", [0.5, 0.5, 0.5, 1.0]) - .color_out() - .cook(svg), - ] -} - -/// A flattened subpath in path units; `closed` after Z. -#[derive(Clone, Debug, PartialEq)] -pub struct Poly { - pub pts: Vec<[f32; 2]>, - pub closed: bool, -} - -struct Lexer<'a> { - s: &'a [u8], - i: usize, -} - -impl Lexer<'_> { - fn skip(&mut self) { - while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') { - self.i += 1; - } - } - - fn peek(&mut self) -> Option<u8> { - self.skip(); - self.s.get(self.i).copied() - } - - fn at_number(&mut self) -> bool { - self.peek().is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.')) - } - - fn number(&mut self) -> Result<f32, String> { - self.skip(); - let (start, s) = (self.i, self.s); - let digit = |j: usize| s.get(j).is_some_and(u8::is_ascii_digit); - let mut j = start + matches!(s.get(start), Some(b'+' | b'-')) as usize; - let mut digits = 0; - while digit(j) { - j += 1; - digits += 1; - } - if s.get(j) == Some(&b'.') { - j += 1; - while digit(j) { - j += 1; - digits += 1; - } - } - if digits == 0 { - return Err(format!("expected a number at byte {start}")); - } - if matches!(s.get(j), Some(b'e' | b'E')) { - let mut k = j + 1 + matches!(s.get(j + 1), Some(b'+' | b'-')) as usize; - let k0 = k; - while digit(k) { - k += 1; - } - if k > k0 { - j = k; - } - } - let txt = s.get(start..j).and_then(|b| std::str::from_utf8(b).ok()).unwrap_or(""); - let v: f32 = txt.parse().map_err(|_| format!("bad number '{txt}' at byte {start}"))?; - if !v.is_finite() { - return Err(format!("number out of range at byte {start}")); - } - self.i = j; - Ok(v) - } - - fn pair(&mut self) -> Result<[f32; 2], String> { - Ok([self.number()?, self.number()?]) - } -} - -/// Builds flattened subpaths while parsing. -struct Pen { - polys: Vec<Poly>, - cur: [f32; 2], - start: [f32; 2], - /// The previous segment's last control point and whether it was cubic (for S and T). - ctrl: Option<([f32; 2], bool)>, - steps_per_unit: f32, - points: usize, -} - -impl Pen { - fn push(&mut self, p: [f32; 2]) -> Result<(), String> { - self.points += 1; - if self.points > MAX_POINTS { - return Err(format!("path too complex (over {MAX_POINTS} points)")); - } - match self.polys.last_mut() { - Some(poly) if !poly.closed => poly.pts.push(p), - // Drawing after Z starts a new subpath at the closed one's start. - _ => self.polys.push(Poly { pts: vec![self.start, p], closed: false }), - } - self.cur = p; - Ok(()) - } - - fn move_to(&mut self, p: [f32; 2]) { - self.polys.push(Poly { pts: vec![p], closed: false }); - (self.cur, self.start) = (p, p); - } - - /// A Bézier through `ctrl` (2 or 3 points after the current one), flattened in steps of - /// about 1 / `steps_per_unit` along its control polygon. - fn curve(&mut self, ctrl: &[[f32; 2]]) -> Result<(), String> { - let mut pts = vec![self.cur]; - pts.extend_from_slice(ctrl); - let len: f32 = pts.windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum(); - let n = (len * self.steps_per_unit).ceil().clamp(2.0, 256.0) as usize; - for k in 1..=n { - let t = k as f32 / n as f32; - // De Casteljau. - let mut q = pts.clone(); - while q.len() > 1 { - q = q.windows(2).map(|w| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t]).collect(); - } - self.push(q.first().copied().unwrap_or(self.cur))?; - } - Ok(()) - } - - fn reflect(&self, cubic: bool) -> [f32; 2] { - match self.ctrl { - Some((c, was_cubic)) if was_cubic == cubic => [2.0 * self.cur[0] - c[0], 2.0 * self.cur[1] - c[1]], - _ => self.cur, - } - } -} - -/// Parses SVG path data into flattened subpaths. Curves get about `steps_per_unit` segments per -/// unit of control-polygon length (2..256 per curve). Bad input is an error, never a panic. -pub fn parse_path(d: &str, steps_per_unit: f32) -> Result<Vec<Poly>, String> { - let mut lx = Lexer { s: d.as_bytes(), i: 0 }; - let steps_per_unit = if steps_per_unit.is_finite() { steps_per_unit.max(0.0) } else { 0.0 }; - let mut pen = Pen { polys: Vec::new(), cur: [0.0; 2], start: [0.0; 2], ctrl: None, steps_per_unit, points: 0 }; - let mut prev: Option<u8> = None; - while let Some(c) = lx.peek() { - let op = if c.is_ascii_alphabetic() { - lx.i += 1; - c - } else if lx.at_number() { - // Repeated arguments repeat the command; extra pairs after a move are lines. - match prev { - Some(b'M') => b'L', - Some(b'm') => b'l', - Some(p) if !matches!(p, b'Z' | b'z') => p, - _ => return Err(format!("number without a command at byte {}", lx.i)), - } - } else { - return Err(format!("unexpected '{}' at byte {}", c as char, lx.i)); - }; - if prev.is_none() && !matches!(op, b'M' | b'm') { - return Err("path data must start with a move (M)".into()); - } - let rel = op.is_ascii_lowercase(); - let o = if rel { pen.cur } else { [0.0; 2] }; - let at = |p: [f32; 2]| [p[0] + o[0], p[1] + o[1]]; - let mut ctrl = None; - match op.to_ascii_uppercase() { - b'M' => pen.move_to(at(lx.pair()?)), - b'L' => pen.push(at(lx.pair()?))?, - b'H' => pen.push([lx.number()? + o[0], pen.cur[1]])?, - b'V' => pen.push([pen.cur[0], lx.number()? + o[1]])?, - b'C' => { - let (c1, c2, p) = (at(lx.pair()?), at(lx.pair()?), at(lx.pair()?)); - pen.curve(&[c1, c2, p])?; - ctrl = Some((c2, true)); - } - b'S' => { - let c1 = pen.reflect(true); - let (c2, p) = (at(lx.pair()?), at(lx.pair()?)); - pen.curve(&[c1, c2, p])?; - ctrl = Some((c2, true)); - } - b'Q' => { - let (c1, p) = (at(lx.pair()?), at(lx.pair()?)); - pen.curve(&[c1, p])?; - ctrl = Some((c1, false)); - } - b'T' => { - let c1 = pen.reflect(false); - pen.curve(&[c1, at(lx.pair()?)])?; - ctrl = Some((c1, false)); - } - b'Z' => { - if let Some(p) = pen.polys.last_mut() { - p.closed = true; - } - pen.cur = pen.start; - } - b'A' => return Err("arc commands (A) are not supported; use curves".into()), - _ => return Err(format!("unknown command '{}'", op as char)), - } - pen.ctrl = ctrl; - prev = Some(op); - } - Ok(pen.polys) -} - -/// Fill coverage (0..1 per pixel, row-major) of polygons in pixel coordinates (each implicitly -/// closed): exact horizontal span coverage on four sub-scanlines per pixel row. -pub(crate) fn fill(w: u32, h: u32, polys: &[Vec<[f32; 2]>], even_odd: bool) -> Vec<f32> { - // Edges as (x0, y0, x1, y1, winding) with y0 < y1. - let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new(); - for p in polys { - for (k, a) in p.iter().enumerate() { - let b = p.get(k + 1).or(p.first()).copied().unwrap_or(*a); - if a[1] < b[1] { - edges.push((a[0], a[1], b[0], b[1], 1)); - } else if b[1] < a[1] { - edges.push((b[0], b[1], a[0], a[1], -1)); - } - } - } - let wu = w as usize; - let rows: Vec<Vec<f32>> = (0..h) - .into_par_iter() - .map(|y| { - let mut row = vec![0.0f32; wu]; - let mut xs: Vec<(f32, i32)> = Vec::new(); - for s in 0..4 { - let sy = y as f32 + (s as f32 + 0.5) * 0.25; - xs.clear(); - xs.extend(edges.iter().filter(|e| e.1 <= sy && sy < e.3).map(|e| (e.0 + (sy - e.1) * (e.2 - e.0) / (e.3 - e.1), e.4))); - xs.sort_by(|a, b| a.0.total_cmp(&b.0)); - let mut wind = 0; - for k in 0..xs.len() { - wind += xs[k].1; - let inside = if even_odd { wind & 1 != 0 } else { wind != 0 }; - if let (true, Some(next)) = (inside, xs.get(k + 1)) { - add_span(&mut row, xs[k].0, next.0, 0.25); - } - } - } - row - }) - .collect(); - rows.concat() -} - -/// Adds `wt` × the overlap of `[a, b)` with each pixel of `row`. -fn add_span(row: &mut [f32], a: f32, b: f32, wt: f32) { - let n = row.len() as f32; - let (a, b) = (a.clamp(0.0, n), b.clamp(0.0, n)); - if b <= a { - return; - } - for px in a.floor() as usize..(b.ceil() as usize).min(row.len()) { - let ov = b.min(px as f32 + 1.0) - a.max(px as f32); - if let Some(v) = row.get_mut(px) { - *v += ov.max(0.0) * wt; - } - } -} - -/// A line segment with a weight (its peak coverage). -#[derive(Clone, Copy, Debug)] -pub(crate) struct Seg { - pub a: [f32; 2], - pub b: [f32; 2], - pub wt: f32, -} - -/// Thick line segments ("capsules") of radius `r` in pixel space, binned on a grid for fast -/// lookups. Coverage ramps over one pixel at the border (anti-aliased); with `tile` it wraps. -pub(crate) struct Capsules { - segs: Vec<Seg>, - r: f32, - g: usize, - cell: [f32; 2], - bins: Vec<Vec<u32>>, - size: [f32; 2], - tile: bool, -} - -impl Capsules { - pub fn new(segs: Vec<Seg>, r: f32, w: u32, h: u32, tile: bool) -> Capsules { - let r = if r.is_finite() { r.max(0.0) } else { 0.0 }; - let reach = r + 1.0; - let g = ((w.max(h) as f32 / (reach * 4.0).max(8.0)) as usize).clamp(1, 128); - let cell = [w as f32 / g as f32, h as f32 / g as f32]; - let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g]; - for (i, s) in segs.iter().enumerate() { - if !s.a.iter().chain(&s.b).all(|v| v.is_finite()) { - continue; - } - let span = |a: f32, b: f32, c: f32| { - let lo = ((a.min(b) - reach) / c).floor() as i64; - (lo, (((a.max(b) + reach) / c).floor() as i64).min(lo + g as i64 - 1)) - }; - let ((x0, x1), (y0, y1)) = (span(s.a[0], s.b[0], cell[0]), span(s.a[1], s.b[1], cell[1])); - for gy in y0..=y1 { - for gx in x0..=x1 { - if !tile && (gx < 0 || gy < 0 || gx >= g as i64 || gy >= g as i64) { - continue; - } - if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) { - b.push(i as u32); - } - } - } - } - Capsules { segs, r, g, cell, bins, size: [w as f32, h as f32], tile } - } - - /// Coverage (0..1, the strongest segment's weight) at pixel coordinates `(x, y)`. - pub fn coverage(&self, x: f32, y: f32) -> f32 { - let (gx, gy) = (((x / self.cell[0]) as usize).min(self.g - 1), ((y / self.cell[1]) as usize).min(self.g - 1)); - let mut best = 0.0f32; - for &i in self.bins.get(gy * self.g + gx).into_iter().flatten() { - let Some(s) = self.segs.get(i as usize) else { continue }; - let (mut px, mut py) = (x - s.a[0], y - s.a[1]); - if self.tile { - px -= (px / self.size[0]).round() * self.size[0]; - py -= (py / self.size[1]).round() * self.size[1]; - } - let (dx, dy) = (s.b[0] - s.a[0], s.b[1] - s.a[1]); - let t = ((px * dx + py * dy) / (dx * dx + dy * dy).max(1e-12)).clamp(0.0, 1.0); - let d = ((px - dx * t).powi(2) + (py - dy * t).powi(2)).sqrt(); - best = best.max((self.r - d + 0.5).clamp(0.0, 1.0) * s.wt); - } - best - } -} - -/// A color image from fill and stroke coverage over transparent black (premultiplied). -pub(crate) fn composite( - w: u32, - h: u32, - fill: [f32; 4], - cover: impl Fn(u32, u32) -> f32 + Sync, - stroke: [f32; 4], - stroke_cover: impl Fn(u32, u32) -> f32 + Sync, -) -> Image { - Image::generate(w, h, Kind::Color, |x, y| { - let f = cover(x, y).clamp(0.0, 1.0) * fill[3]; - let s = stroke_cover(x, y).clamp(0.0, 1.0) * stroke[3]; - let k = f * (1.0 - s); - [fill[0] * k + stroke[0] * s, fill[1] * k + stroke[1] * s, fill[2] * k + stroke[2] * s, k + s] - }) -} - -fn svg(ctx: &Ctx) -> CookResult { - let unit = if ctx.i("units") == 1 { 100.0 } else { 1.0 }; - let (sx, sy) = (ctx.w as f32 / unit, ctx.h as f32 / unit); - // About one curve segment per 3 pixels. - let polys = parse_path(ctx.text("path"), sx.max(sy) / 3.0)?; - let rings: Vec<Vec<[f32; 2]>> = polys.iter().map(|p| p.pts.iter().map(|q| [q[0] * sx, q[1] * sy]).collect()).collect(); - let cov = fill(ctx.w, ctx.h, &rings, ctx.i("fill_rule") == 0); - let sw = ctx.f("stroke_width").max(0.0) * ctx.w as f32 / 256.0; - let caps = (sw > 0.0).then(|| { - let mut segs = Vec::new(); - for (p, ring) in polys.iter().zip(&rings) { - segs.extend(ring.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 })); - if let (true, Some(a), Some(b)) = (p.closed, ring.last(), ring.first()) { - segs.push(Seg { a: *a, b: *b, wt: 1.0 }); - } - if ring.len() == 1 { - segs.extend(ring.first().map(|a| Seg { a: *a, b: *a, wt: 1.0 })); - } - } - Capsules::new(segs, sw * 0.5, ctx.w, ctx.h, false) - }); - let w = ctx.w as usize; - Ok(vec![composite( - ctx.w, - ctx.h, - ctx.v4("fill"), - |x, y| cov.get(y as usize * w + x as usize).copied().unwrap_or(0.0), - ctx.v4("stroke"), - |x, y| caps.as_ref().map_or(0.0, |c| c.coverage(x as f32 + 0.5, y as f32 + 0.5)), - )]) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn pts(d: &str) -> Vec<Vec<[f32; 2]>> { - parse_path(d, 1.0).unwrap().into_iter().map(|p| p.pts).collect() - } - - #[test] - fn parses_lines_absolute_and_relative() { - assert_eq!(pts("M0 0 L10 0 L10 10 Z"), vec![vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]]); - assert_eq!(pts("m1,1 l2,0 0,2 h-2 v-1"), vec![vec![[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0], [1.0, 2.0]]]); - // Extra pairs after M are lines; compact number syntax. - assert_eq!(pts("M0 0 1 1 2-2"), vec![vec![[0.0, 0.0], [1.0, 1.0], [2.0, -2.0]]]); - assert_eq!(pts("M.5.5L1e1-1E0"), vec![vec![[0.5, 0.5], [10.0, -1.0]]]); - assert_eq!(pts("M0 0H5V5H0z M8 8 L9 9").len(), 2); - } - - #[test] - fn parses_curves_to_their_endpoints() { - for d in - ["M0 0 C0 10 10 10 10 0", "M0 0 c0 10 10 10 10 0", "M0 0 Q5 10 10 0", "M0 0 q5 10 10 0", "M0 0 Q5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 S10 -5 10 0"] - { - let p = pts(d); - let last = *p[0].last().unwrap(); - assert!((last[0] - 10.0).abs() < 1e-4 && last[1].abs() < 1e-4, "{d}: {last:?}"); - assert!(p[0].len() > 3, "{d} is flattened"); - } - // The cubic's midpoint bulges to 7.5. - let p = parse_path("M0 0 C0 10 10 10 10 0", 0.0).unwrap(); - assert_eq!(p[0].pts.len(), 3); - assert!((p[0].pts[1][1] - 7.5).abs() < 1e-4); - } - - #[test] - fn bad_paths_are_errors() { - for d in ["L0 0", "M0", "M0 0 L1", "M0 0 X1 1", "M0 0 L1 1e99", "M0 0 A1 1 0 0 1 2 2", "5 5", "M0 0 Z 3 4", "M 0 0 L - 1"] { - assert!(parse_path(d, 1.0).is_err(), "{d}"); - } - assert!(parse_path("", 1.0).unwrap().is_empty()); - assert!(parse_path("M0 0 C1 1 2 2 3 3", f32::NAN).is_ok()); - } - - #[test] - fn fill_rules_and_coverage() { - let sq = |a: f32, b: f32, ccw: bool| { - let mut v = vec![[a, a], [b, a], [b, b], [a, b]]; - if ccw { - v.reverse(); - } - v - }; - // Square of 4..12 on a 16×16 grid: area 64; a half-pixel edge gives half coverage. - let c = fill(16, 16, &[sq(4.0, 12.0, false)], false); - assert!((c.iter().sum::<f32>() - 64.0).abs() < 1e-3); - let c = fill(16, 16, &[sq(4.5, 12.0, false)], false); - assert!((c[8 * 16 + 4] - 0.5).abs() < 1e-4); - // A hole: even-odd always; non-zero only with opposite winding. - let eo = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], true); - let nz_same = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], false); - let nz_opp = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, true)], false); - let center = 8 * 16 + 8; - assert_eq!((eo[center], nz_same[center], nz_opp[center]), (0.0, 1.0, 0.0)); - } - - #[test] - fn default_svg_draws_the_leaf() { - let def = crate::catalog::find("svg").unwrap(); - let p = crate::catalog::resolve_params(def, &Default::default()); - let no_res = |_: &str| None; - let vars = Default::default(); - let ctx = Ctx { w: 64, h: 64, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; - let img = &svg(&ctx).unwrap()[0]; - let a = img.mean()[3]; - assert!(a > 0.2 && a < 0.7, "{a}"); - assert!(img.get(20, 32, false)[3] > 0.9 && img.get(2, 2, false)[3] == 0.0); - } -} diff --git a/crates/nodes/src/tests.rs b/crates/nodes/src/tests.rs new file mode 100644 index 00000000..9c77e463 --- /dev/null +++ b/crates/nodes/src/tests.rs @@ -0,0 +1,112 @@ +use std::collections::BTreeMap; + +use materialcraft_core::Value; +use materialcraft_image::{Image, Kind}; + +use super::*; + +fn cook(def: &NodeDefinition, inputs: &[Option<Image>], size: u32) -> CookResult { + let params = resolve_params(def, &BTreeMap::new()); + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let ctx = CookContext { w: size, h: size, seed: 7, tile: true, inputs, params: ¶ms, resource: &no_res, vars: &vars }; + (def.cook)(&ctx) +} + +/// Every node cooks with no inputs and with hostile-sized inputs, returns as many images as it has outputs, at the requested size, with finite values +#[test] +fn every_node_cooks() { + let ids: Vec<&str> = catalog().iter().map(|d| d.id).collect(); + let mut seen = std::collections::BTreeSet::new(); + for id in &ids { + assert!(seen.insert(*id), "duplicate node id {id}"); + } + let odd = Image::generate(5, 3, Kind::Color, |x, y| [x as f32 / 4.0, y as f32 / 2.0, 0.5, 1.0]); + for def in catalog() { + if matches!(def.id, "graph_instance" | "value_processor" | "input_value") { + continue; + } + for inputs in [vec![None; def.inputs.len()], vec![Some(odd.clone()); def.inputs.len()]] { + let out = cook(def, &inputs, 32).unwrap_or_else(|e| panic!("{}: {e}", def.id)); + assert_eq!(out.len(), def.outputs.len().max(1), "{}", def.id); + for img in &out { + assert_eq!((img.w, img.h), (32, 32), "{}", def.id); + assert!(img.data.iter().all(|v| v.is_finite()), "{} produced a non-finite value", def.id); + } + } + } + assert_eq!(catalog().len(), 30); +} + +/// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN): the hard limits keep the cook bounded, finite and the right size +#[test] +fn every_node_survives_hostile_params() { + use std::time::{Duration, Instant}; + + let mut slow: Vec<(String, Duration)> = Vec::new(); + let total = Instant::now(); + for def in catalog() { + if matches!(def.id, "graph_instance" | "value_processor" | "input_value") { + continue; + } + for p in &def.params { + for h in [1e30_f32, -1e30, f32::NAN] { + let v = match p.default { + Value::Float(_) => Value::Float(h), + Value::Int(_) => Value::Int(h as i32), + Value::Float2(_) => Value::Float2([h, h]), + Value::Enum(_) => Value::Enum(h as u32), + _ => continue, + }; + + let mut params = resolve_params(def, &BTreeMap::from([(p.id.to_string(), v)])); + clamp_params(def, &mut params); + let inputs = vec![None; def.inputs.len()]; + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let ctx = CookContext { w: 16, h: 16, seed: 7, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + let t = Instant::now(); + let out = (def.cook)(&ctx).unwrap_or_else(|e| panic!("{}.{}={h}: {e}", def.id, p.id)); + let dt = t.elapsed(); + assert!(dt < Duration::from_secs(2), "{}.{}={h} took {dt:?}", def.id, p.id); + if dt > Duration::from_millis(250) { + slow.push((format!("{}.{}={h}", def.id, p.id), dt)); + } + 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); + } + } + } + } + eprintln!("hostile params: total {:?}; cooks over 250 ms: {slow:?}", total.elapsed()); +} + +#[test] +fn blend_and_levels_math() { + let fg = Image::filled(4, 4, Kind::Gray, [0.25; 4]); + let bg = Image::filled(4, 4, Kind::Gray, [0.5; 4]); + let def = find("blend").unwrap(); + let mut params = resolve_params(def, &BTreeMap::new()); + params.insert("mode".into(), materialcraft_core::Value::Enum(3)); + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let inputs = [Some(fg), Some(bg), None]; + let ctx = CookContext { w: 4, h: 4, seed: 0, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + let out = (def.cook)(&ctx).unwrap(); + 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); +} + +#[test] +fn dynamic_gradient_preserves_the_gradient_image_type() { + let definition = find("gradient_dynamic").unwrap(); + for kind in [Kind::Gray, Kind::Color] { + 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].get(0, 0, false), gradient.get(0, 0, false)); + } +} diff --git a/crates/nodes/src/weathering.rs b/crates/nodes/src/weathering.rs deleted file mode 100644 index 4c1cfa47..00000000 --- a/crates/nodes/src/weathering.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! Wear and weathering: cracks, paint strokes, scratches along a direction field, rust, moss and -//! lichen, leaks (drips running down from a mask) and chipped edges. The generators tile. - -use std::f32::consts::{PI, TAU}; - -use materialcraft_image::{Image, Kind}; -use rayon::prelude::*; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::fx_map::{BLENDS, Inst, splat}; -use crate::generators::NOISES; -use crate::noise::{cellular, fbm, rand1, value}; -use crate::noises_more::smoothstep; -use crate::ops; -use crate::patterns::PATTERNS; -use crate::svg::{Capsules, Seg}; - -const WEATHER: &str = "Material filters/Weathering"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("cracks", "Cracks", NOISES) - .desc("A connected network of thin cracks along warped cell borders, with finer branching cracks. White = crack.") - .generator() - .float("scale", "Scale", 5.0, 1.0, 32.0) - .float("width", "Width", 1.5, 0.0, 16.0) - .float("warp", "Warp", 0.5, 0.0, 1.0) - .float("branches", "Branches", 0.5, 0.0, 1.0) - .gray_out() - .cook(cracks), - node("paint_strokes", "Paint Strokes", PATTERNS) - .desc("Overlapping brush strokes with bristle streaks and ragged ends.") - .generator() - .int("count", "Count", 150, 1, 5000) - .float("length", "Length", 0.35, 0.0, 1.0) - .float("width", "Width", 0.07, 0.0, 0.5) - .angle("angle", "Angle", 0.0) - .float("angle_random", "Angle random", 0.08, 0.0, 1.0) - .int("bristles", "Bristles", 20, 1, 256) - .float("luminance_random", "Luminance random", 0.5, 0.0, 1.0) - .choice("blending", "Blending", BLENDS, 2) - .gray_out() - .cook(paint_strokes), - node("scratches_generator", "Scratches Generator", PATTERNS) - .desc("Thin tapered scratches that bend along a direction field (gray = angle in turns) and land where the mask is bright.") - .generator() - .gray_in("direction", "Direction field") - .gray_in("mask", "Mask") - .int("count", "Count", 200, 0, 5000) - .float("length", "Length", 0.25, 0.0, 1.0) - .float("width", "Width", 1.0, 0.1, 16.0) - .angle("angle", "Angle", 0.0) - .float("angle_random", "Angle random", 0.15, 0.0, 1.0) - .float("curvature", "Curvature", 0.1, 0.0, 1.0) - .float("field_intensity", "Field intensity", 0.25, 0.0, 1.0) - .float("luminance_random", "Luminance random", 0.6, 0.0, 1.0) - .gray_out() - .cook(scratches_generator), - node("rust", "Rust", WEATHER) - .desc("A mask of rust blotches and pitting; with a mask input it grows out from the mask (edges, cavities).") - .generator() - .gray_in("mask", "Mask (optional)") - .float("amount", "Amount", 0.45, 0.0, 1.0) - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("spread", "Spread", 12.0, 0.0, 128.0) - .float("pitting", "Pitting", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.7, 0.0, 1.0) - .gray_out() - .cook(rust), - node("moss", "Moss / Lichen", WEATHER) - .desc("Fuzzy moss clumps (gathering in low areas) or round lichen rosettes (on high areas) of an optional height map.") - .generator() - .gray_in("height", "Height (optional)") - .choice("style", "Style", &["Moss", "Lichen"], 0) - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("height_bias", "Height bias", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.6, 0.0, 1.0) - .gray_out() - .cook(moss), - node("leaks", "Leaks", WEATHER) - .desc("Streaky drips running down from a mask (unconnected: random stains), fading with length and meandering.") - .gray_in("mask", "Mask") - .float("length", "Length", 0.35, 0.0, 1.0) - .float("length_random", "Length random", 0.7, 0.0, 1.0) - .float("streaks", "Streaks", 32.0, 1.0, 256.0) - .float("wobble", "Wobble", 0.3, 0.0, 1.0) - .gray_out() - .cook(leaks), - node("edge_damage", "Edge Damage", WEATHER) - .desc("Chips the edges of a height mask (white = material) in chunky, ragged bites; also outputs the damage mask.") - .gray_in("height", "Height") - .float("width", "Width", 8.0, 0.0, 64.0) - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("scale", "Chip scale", 12.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("depth", "Depth", 1.0, 0.0, 1.0) - .gray_out() - .output("mask", "Damage mask", PortKind::Gray) - .cook(edge_damage), - ] -} - -/// `v` pixels at 256 px, at the output size. -fn px(ctx: &Ctx, v: f32) -> f32 { - v * ctx.w as f32 / 256.0 -} - -fn whole(ctx: &Ctx, id: &str) -> f32 { - ctx.f(id).max(1.0).round() -} - -/// A soft threshold: 1 where `v` is above `1 - amount`; `contrast` 1 is hard, 0 soft. -fn thresh(v: f32, amount: f32, contrast: f32) -> f32 { - let soft = (1.0 - contrast.clamp(0.0, 1.0)) * 0.25 + 0.005; - smoothstep(1.0 - amount - soft, 1.0 - amount + soft, v) -} - -/// A gray image from `f(pixel index, u, v)`. -fn gen_px(ctx: &Ctx, f: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image { - let (w, h) = (ctx.w.max(1), ctx.h.max(1)); - Image::generate(w, h, Kind::Gray, |x, y| [f(y as usize * w as usize + x as usize, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32), 0.0, 0.0, 0.0]) -} - -fn cracks(ctx: &Ctx) -> CookResult { - let (s, wpx, warp, br, seed) = (whole(ctx, "scale"), px(ctx, ctx.f("width")), ctx.f("warp"), ctx.f("branches"), ctx.seed); - let cell_px = ctx.w as f32 / s; - Ok(vec![ctx.gen_gray(|u, v| { - // Broad bends plus fine jaggedness, both in cell units. - let k = warp / s; - let wu = u + (fbm(u, v, 4.0, 4, 0.5, seed ^ 11) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 14) - 0.5) * 0.3 * k; - let wv = v + (fbm(u, v, 4.0, 4, 0.5, seed ^ 12) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 15) - 0.5) * 0.3 * k; - let line = |m: f32, sd: u32, half: f32| { - let c = cellular(wu * s * m, wv * s * m, (s * m) as i32, 1.0, 0, sd); - 1.0 - smoothstep(half, half + 1.0, (c.f2 - c.f1) * 0.5 * cell_px / m) - }; - let main = line(1.0, seed, wpx * 0.5); - if br <= 0.0 { - return main; - } - let keep = smoothstep(1.0 - br, 1.0 - br + 0.2, fbm(u, v, s, 3, 0.5, seed ^ 13)); - main.max(line(3.0, seed ^ 7, wpx * 0.3) * keep * 0.8) - })]) -} - -fn paint_strokes(ctx: &Ctx) -> CookResult { - let (len, wid, ang, ar, lr, s) = (ctx.f("length"), ctx.f("width"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("luminance_random"), ctx.seed); - let bristles = ctx.i("bristles").clamp(1, 256) as f32; - let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 5000) as u32) - .map(|i| { - let r = |k: u32| rand1(i * 8 + k, s); - Inst { - c: [r(0), r(1)], - r: [len * 0.5 * (0.7 + 0.3 * r(2)), wid * 0.5 * (0.8 + 0.4 * r(3))], - rot: ang + (r(4) - 0.5) * ar, - lum: 1.0 - lr * r(5), - pat: 0, - } - }) - .collect(); - Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| { - let sd = s ^ (i as u32).wrapping_mul(0x9e37_79b9); - // Bristle density across the stroke; the ends are ragged per bristle. - let b = value(y * bristles + 0.5, 0.5, 0, sd); - let ragged = value(y * bristles * 0.5 + 3.1, x * 2.0, 0, sd ^ 1); - let end = 1.0 - smoothstep(0.55 + 0.4 * ragged, 1.0, x.abs()); - let edge = 1.0 - smoothstep(0.7, 1.0, y.abs()); - end * edge * (0.45 + 0.55 * b) - })]) -} - -fn scratches_generator(ctx: &Ctx) -> CookResult { - const STEPS: u32 = 12; - let (len, ang, ar, curv, fi, lr, s) = - (ctx.f("length"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("curvature"), ctx.f("field_intensity"), ctx.f("luminance_random"), ctx.seed); - let (field, mask) = (ctx.input(0), ctx.input(1)); - let (w, h) = (ctx.w as f32, ctx.h as f32); - let mut segs = Vec::new(); - for i in 0..ctx.i("count").clamp(0, 5000) as u32 { - let r = |k: u32| rand1(i * 8 + k, s); - let mut p = [r(0), r(1)]; - if mask.is_some_and(|m| r(2) >= m.sample_gray(p[0], p[1], ctx.tile)) { - continue; - } - let (base, bend, lum) = (ang + (r(3) - 0.5) * ar, (r(4) - 0.5) * curv, 1.0 - lr * r(6)); - let step = len * (0.4 + 0.6 * r(5)) / STEPS as f32; - for k in 0..STEPS { - let t = k as f32 / STEPS as f32; - let a = (base + bend * t + field.map_or(0.0, |f| f.sample_gray(p[0], p[1], ctx.tile) * fi)) * TAU; - let q = [p[0] + a.cos() * step, p[1] - a.sin() * step]; - let taper = ((t + 0.5 / STEPS as f32) * PI).sin().sqrt(); - segs.push(Seg { a: [p[0] * w, p[1] * h], b: [q[0] * w, q[1] * h], wt: lum * taper }); - p = q; - } - } - let caps = Capsules::new(segs, px(ctx, ctx.f("width")) * 0.5, ctx.w, ctx.h, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| [caps.coverage(x as f32 + 0.5, y as f32 + 0.5), 0.0, 0.0, 0.0])]) -} - -fn rust(ctx: &Ctx) -> CookResult { - let (amt, s, pit, con, seed) = (ctx.f("amount"), whole(ctx, "scale"), ctx.f("pitting"), ctx.f("contrast"), ctx.seed); - let grow = ctx.sized(0).map(|m| ops::gaussian(&m.to_gray(), px(ctx, ctx.f("spread")), ctx.tile)); - Ok(vec![gen_px(ctx, |i, u, v| { - let blotch = fbm(u, v, s, 6, 0.55, seed); - let base = match &grow { - Some(g) => 0.5 * blotch + 0.6 * g.data.get(i).copied().unwrap_or(0.0), - None => blotch, - }; - let c = cellular(u * s * 8.0, v * s * 8.0, (s * 8.0) as i32, 1.0, 0, seed ^ 3); - let pits = (1.0 - smoothstep(0.05, 0.4, c.f1)) * (c.id < pit) as i32 as f32; - // Pits speckle the surroundings of the blotches only. - thresh(base + pits * 0.2 * smoothstep(0.3, 0.5, base), amt, con) * (0.7 + 0.3 * fbm(u, v, s * 16.0, 3, 0.6, seed ^ 5)) - })]) -} - -fn moss(ctx: &Ctx) -> CookResult { - let (lichen, amt, s, bias, con, seed) = (ctx.i("style") == 1, ctx.f("amount"), whole(ctx, "scale"), ctx.f("height_bias"), ctx.f("contrast"), ctx.seed); - let hgt = ctx.sized(0).map(|h| h.to_gray()); - Ok(vec![gen_px(ctx, |i, u, v| { - let hb = hgt.as_ref().map_or(0.0, |h| (h.data.get(i).copied().unwrap_or(0.5) - 0.5) * bias); - let fine = |m: f32, sd: u32| value(u * s * m, v * s * m, (s * m) as i32, seed ^ sd); - if !lichen { - // Fuzzy clumps, thicker in low areas. - let clump = fbm(u, v, s, 5, 0.6, seed) - hb + (fine(24.0, 9) - 0.5) * 0.25; - return thresh(clump, amt, con) * (0.55 + 0.45 * fine(48.0, 10)); - } - // Round rosettes with brighter rims, on high areas. - let c = cellular(u * s, v * s, s as i32, 0.9, 0, seed); - if c.id >= amt * 1.4 + hb { - return 0.0; - } - let rad = (0.25 + 0.35 * (c.id * 7.31).fract()) * (0.8 + 0.4 * fbm(u, v, s * 8.0, 3, 0.5, seed ^ 4)); - let soft = 0.01 + (1.0 - con) * 0.06; - (1.0 - smoothstep(rad - soft, rad, c.f1)) * (0.55 + 0.45 * smoothstep(rad * 0.4, rad, c.f1)) * (0.8 + 0.2 * fine(32.0, 6)) - })]) -} - -fn leaks(ctx: &Ctx) -> CookResult { - let (w, h, seed) = (ctx.w as usize, ctx.h as usize, ctx.seed); - let src = match ctx.sized(0) { - Some(m) => m.to_gray(), - None => ctx.gen_gray(|u, v| smoothstep(0.62, 0.7, fbm(u, v, 4.0, 4, 0.5, seed ^ 21))), - }; - let (len, lr, streaks, wob) = (ctx.f("length").max(0.0) * h as f32, ctx.f("length_random"), whole(ctx, "streaks"), ctx.f("wobble")); - // Each column carries its value down, fading over a length that varies across columns. - let cols: Vec<Vec<f32>> = (0..w) - .into_par_iter() - .map(|x| { - let u = (x as f32 + 0.5) / w as f32; - let r = 0.6 * value(u * streaks, 0.5, streaks as i32, seed ^ 23) + 0.4 * value(u * streaks * 4.0, 0.5, (streaks * 4.0) as i32, seed ^ 24); - let decay = (-3.0 / (len * (1.0 - lr * r)).max(1.0)).exp(); - let mut col = vec![0.0f32; h]; - let mut acc = 0.0f32; - // Tiling: a second pass carries drips over the bottom edge to the top. - let passes = if ctx.tile { 2 } else { 1 }; - for pass in 0..passes { - for (y, out) in col.iter_mut().enumerate() { - acc = src.data.get(y * w + x).copied().unwrap_or(0.0).max(acc * decay); - if pass + 1 == passes { - *out = acc; - } - } - } - col - }) - .collect(); - let run = Image::gray(ctx.w, ctx.h, |x, y| cols.get(x as usize).and_then(|c| c.get(y as usize)).copied().unwrap_or(0.0)); - Ok(vec![ctx.gen_gray(|u, v| { - let dx = (fbm(u, v, 8.0, 3, 0.5, seed ^ 22) - 0.5) * wob * 0.04; - run.sample_gray(u + dx, v, ctx.tile) * (0.75 + 0.25 * value(u * streaks * 2.0, v * 3.0, (streaks * 2.0) as i32, seed ^ 25)) - })]) -} - -fn edge_damage(ctx: &Ctx) -> CookResult { - let hgt = ctx.gray_or(0, 0.0); - let data = hgt.data.clone(); - let solid = |i: usize| data.get(i).is_some_and(|v| *v > 0.5); - let dist = ops::distance_sq(ctx.w, ctx.h, |i| !solid(i), ctx.tile); - let (wpx, amt, s, rough, depth, seed) = (px(ctx, ctx.f("width")), ctx.f("amount"), whole(ctx, "scale"), ctx.f("roughness"), ctx.f("depth"), ctx.seed); - let mask = gen_px(ctx, |i, u, v| { - if !solid(i) { - return 0.0; - } - let d = dist.get(i).map_or(0.0, |d| d.sqrt()); - // Chunky bites per cell, made ragged by noise. - let c = cellular(u * s, v * s, s as i32, 1.0, 0, seed); - let r = c.id * (1.0 - rough * 0.5) + (fbm(u, v, s * 2.0, 4, 0.5, seed ^ 3) - 0.5) * rough * 1.5; - let reach = wpx * 2.0 * amt * r.max(0.0); - 1.0 - smoothstep(reach - 0.75, reach + 0.75, d) - }); - let out = Image::gray(ctx.w, ctx.h, |x, y| { - let i = (y * ctx.w + x) as usize; - data.get(i).copied().unwrap_or(0.0) * (1.0 - depth * mask.data.get(i).copied().unwrap_or(0.0)) - }); - Ok(vec![out, mask]) -} diff --git a/crates/ui-egui/src/annotation/comment_properties.rs b/crates/ui-egui/src/annotation/comment_properties.rs new file mode 100644 index 00000000..a073e422 --- /dev/null +++ b/crates/ui-egui/src/annotation/comment_properties.rs @@ -0,0 +1,19 @@ +use crate::{MaterialCraftApp, i18n::tr}; +use egui::Ui; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) { + let Some(mut text) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)).map(|comment| comment.text.clone()) + else { + return; + }; + + crate::properties::section(ui, "comment-parameters", tr("Parameters"), |ui| { + ui.label(tr("Description")); + let description = ui.add(egui::TextEdit::multiline(&mut text).desired_rows(8).desired_width(f32::INFINITY)); + crate::widgets::name(&description, egui::Role::TextInput, "Comment description"); + if description.changed() { + app.run("graph.comment.edit", json!({"id": id, "text": text})); + } + }); +} diff --git a/crates/ui-egui/src/annotation/frame_properties.rs b/crates/ui-egui/src/annotation/frame_properties.rs new file mode 100644 index 00000000..7cc12e97 --- /dev/null +++ b/crates/ui-egui/src/annotation/frame_properties.rs @@ -0,0 +1,38 @@ +use crate::{MaterialCraftApp, i18n::tr}; +use egui::Ui; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) { + let Some(mut frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)).cloned() else { + return; + }; + + crate::properties::section(ui, "frame-parameters", tr("Parameters"), |ui| { + if ui.checkbox(&mut frame.title_visible, tr("Title Visible")).changed() { + app.run("graph.frame.edit", json!({"id": id, "titleVisible": frame.title_visible})); + } + + ui.label(tr("Title")); + let title = ui.text_edit_singleline(&mut frame.title); + crate::widgets::name(&title, egui::Role::TextInput, "Frame title"); + if title.changed() { + app.run("graph.frame.edit", json!({"id": id, "title": frame.title})); + } + + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(tr("Frame Color")); + if ui.color_edit_button_rgba_unmultiplied(&mut frame.color).changed() { + app.run("graph.frame.edit", json!({"id": id, "color": frame.color})); + } + }); + + ui.add_space(8.0); + ui.label(tr("Description")); + let description = ui.add(egui::TextEdit::multiline(&mut frame.description).desired_rows(8).desired_width(f32::INFINITY)); + crate::widgets::name(&description, egui::Role::TextInput, "Frame description"); + if description.changed() { + app.run("graph.frame.edit", json!({"id": id, "description": frame.description})); + } + }); +} diff --git a/crates/ui-egui/src/annotation/mod.rs b/crates/ui-egui/src/annotation/mod.rs new file mode 100644 index 00000000..3068951f --- /dev/null +++ b/crates/ui-egui/src/annotation/mod.rs @@ -0,0 +1,13 @@ +mod comment_properties; +mod frame_properties; + +use crate::MaterialCraftApp; +use egui::Ui; +use materialcraft_engine::AnnotationSelection; + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, selection: AnnotationSelection) { + match selection { + AnnotationSelection::Frame(id) => frame_properties::show(app, ui, id), + AnnotationSelection::Comment(id) => comment_properties::show(app, ui, id), + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 39708774..2a0b8f66 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -226,7 +226,10 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") }; let params = p.get("params").cloned().unwrap_or(Value::Null); match materialcraft_engine::execute(&mut app.session, id, ¶ms) { - Ok(v) => ok(v), + Ok(v) => { + app.close_subgraph_after(id); + ok(v) + } Err(e) => err(e), } } @@ -240,8 +243,23 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: ok(json!({ "state": app.ui, "graphView": rect(app.graph.view), + "selection": app.session.selection, + "inspectedNode": app.graph.inspected_node, + "subgraph": app.pattern_editor.as_ref().filter(|_| crate::pattern::active(app)) + .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})) + .or_else(|| app.function_editor.as_ref().filter(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_))) + .map(|editor| json!({"kind": "function", "graph": app.session.graph, "selection": editor.selection, "inspectedNode": editor.inspected_node}))), + "annotationSelection": app.session.annotation_selection, + "frames": app.graph.frames.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), + "comments": app.graph.comments.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), "nodes": app.graph.rects.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(), - "ports": app.graph.ports.iter().map(|h| json!({"node": h.node.0, "port": h.port, "output": h.output, "pos": [h.pos.x, h.pos.y]})).collect::<Vec<_>>(), + "ports": app.graph.ports.iter().map(|port| json!({ + "node": port.node.0, + "port": port.port, + "label": port.label, + "output": port.output, + "pos": [port.pos.x, port.pos.y], + })).collect::<Vec<_>>(), "fps": app.fps, "uiMs": app.ui_ms, "cooking": app.cooker.busy(), diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 0349e8c2..3e0128da 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -318,7 +318,7 @@ impl DockContent<Panel> for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { let app = &mut *self.app; match panel { - Panel::Graph => crate::graph_view::show(app, ui), + Panel::Graph => crate::graph::show(app, ui), Panel::View3d => crate::view3d::show(app, ui), Panel::View2d => crate::view2d::show(app, ui), _ => { diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 547cbb7e..8c565f60 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -1,6 +1,8 @@ -//! The explorer: the open package, its graphs and its bitmap resources. +//! The package tree, its graphs, named outputs and resources -use egui::{RichText, Sense, Ui, vec2}; +use egui::{RichText, Ui}; + +mod tree_row; use egui_phosphor::regular as icon; use serde_json::json; @@ -34,44 +36,77 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong)); let mut open: Option<usize> = None; let mut action: Option<(&str, usize)> = None; - for (i, g) in app.session.pkg.graphs.iter().enumerate() { - let on = i == app.session.graph; - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); - crate::widgets::name(&resp, egui::Role::TreeItem, &g.name); - if on { - ui.painter().rect_filled(r, 4.0, tk.row_selected); - ui.painter().rect_stroke(r, 4.0, egui::Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } else if resp.hovered() { - ui.painter().rect_filled(r, 4.0, tk.row_hover); - } - ui.painter().text( - r.left_center() + vec2(18.0, 0.0), - egui::Align2::LEFT_CENTER, - format!("{} {}", icon::TREE_STRUCTURE, g.name), - egui::FontId::proportional(12.0), - if on { tk.text_strong } else { tk.text }, - ); - if resp.clicked() { - open = Some(i); - } - resp.context_menu(|ui| { - for (label, a) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { - if ui.button(tr(label)).clicked() { - action = Some((a, i)); - ui.close(); - } + let mut output = None; + for (index, graph) in app.session.pkg.graphs.iter().enumerate() { + let active = index == app.session.graph; + let function = graph.function.is_some(); + let mut header = |ui: &mut Ui| { + let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE }; + let response = tree_row::show(ui, &graph.name, symbol, active); + if response.clicked() { + open = Some(index); } + response.context_menu(|ui| { + for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { + if ui.button(tr(label)).clicked() { + action = Some((command, index)); + ui.close(); + } + } + }); + }; + + if function { + ui.horizontal(|ui| { + ui.add_space(ui.spacing().indent); + header(ui); + }); + continue; + } + + let id = ui.make_persistent_id(("graph", index, &graph.name)); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true).show_header(ui, header).body(|ui| { + ui.indent("outputs", |ui| { + for node in graph.nodes.iter().filter(|node| node.def == "output") { + ui.push_id(node.id, |ui| { + let name = materialcraft_engine::eval::identifier(node); + let selected = active && app.session.selection.contains(&node.id); + let response = tree_row::show(ui, &name, icon::IMAGE, selected); + + if response.clicked() || response.double_clicked() { + output = Some((index, node.id, response.double_clicked())); + } + }); + } + }); }); } if let Some(i) = open { app.run("graph.open", json!({"graph": i})); } + if let Some((index, node, preview)) = output { + if index != app.session.graph && app.run("graph.open", json!({"graph": index})).is_none() { + return; + } + + app.pattern_editor = None; + app.function_editor = None; + app.run("graph.annotation.select", json!({})); + app.run("graph.select", json!({"ids": [node.0]})); + app.graph.inspected_node = Some(node); + app.ui.dock.focus(crate::docking::Panel::Properties); + if preview { + app.run("view.2d", json!({"node": node.0})); + app.ui.dock.focus(crate::docking::Panel::View2d); + } + } + match action { Some(("open", i)) => { app.run("graph.open", json!({"graph": i})); } Some(("export", i)) => { - // The export window works on the open graph. + // The export window works on the open graph if app.run("graph.open", json!({"graph": i})).is_some() { app.ui.windows.export = true; } diff --git a/crates/ui-egui/src/explorer/tree_row.rs b/crates/ui-egui/src/explorer/tree_row.rs new file mode 100644 index 00000000..6002b56a --- /dev/null +++ b/crates/ui-egui/src/explorer/tree_row.rs @@ -0,0 +1,24 @@ +use egui::{Align2, FontId, Response, Sense, Stroke, StrokeKind, Ui, vec2}; + +use crate::{theme::Tokens, widgets}; + +pub(super) fn show(ui: &mut Ui, name: &str, icon: &str, selected: bool) -> Response { + let theme = Tokens::get(ui.ctx()); + let (bounds, response) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + widgets::name(&response, egui::Role::TreeItem, name); + if selected { + ui.painter().rect_filled(bounds, 4.0, theme.row_selected); + ui.painter().rect_stroke(bounds, 4.0, Stroke::new(1.0, theme.accent), StrokeKind::Inside); + } else if response.hovered() { + ui.painter().rect_filled(bounds, 4.0, theme.row_hover); + } + + ui.painter().text( + bounds.left_center() + vec2(4.0, 0.0), + Align2::LEFT_CENTER, + format!("{icon} {name}"), + FontId::proportional(12.0), + if selected { theme.text_strong } else { theme.text }, + ); + response +} diff --git a/crates/ui-egui/src/function/canvas.rs b/crates/ui-egui/src/function/canvas.rs new file mode 100644 index 00000000..8b39ce18 --- /dev/null +++ b/crates/ui-egui/src/function/canvas.rs @@ -0,0 +1,572 @@ +//! Function canvas edits are committed through engine commands + +use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::Value; +use materialcraft_engine::core::{FunctionGraph, FunctionNode}; +use materialcraft_engine::nodes::function::FUNCTIONS; +use serde_json::json; + +use crate::MaterialCraftApp; +use crate::graph::node_card; +use crate::i18n::tr; +use crate::theme::Tokens; + +use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; + +fn arity(op: &str) -> usize { + FUNCTIONS.iter().find(|o| o.id == op).map_or(0, |o| o.inputs.len()) +} + +fn label(op: &str) -> &'static str { + FUNCTIONS.iter().find(|o| o.id == op).map_or("?", |o| o.label) +} + +fn category_color(op: &str) -> Color32 { + match FUNCTIONS.iter().find(|o| o.id == op).map_or("", |o| o.category) { + "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), + "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), + "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), + "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), + "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), + "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), + _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), + } +} + +fn visible_inputs(node: &FunctionNode) -> usize { + let count = arity(&node.op); + crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1) +} + +fn node_rect(node: &FunctionNode, previews: bool) -> Rect { + node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough") +} + +fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { + node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough") +} + +fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { + node_card::port(bounds, 0, 1, true, node.op == "passthrough") +} + +pub(super) fn current(app: &MaterialCraftApp, editor: &FunctionEditor) -> Option<FunctionGraph> { + if let FunctionTarget::Graph(index) = editor.target { + return app.session.pkg.graphs.get(index)?.function.clone(); + } + + let node = app.session.graph().ok()?.node(editor.node?).ok()?; + let value = match &editor.target { + FunctionTarget::Graph(_) => return None, + FunctionTarget::Dynamic(parameter) => return node.functions.get(parameter).cloned(), + FunctionTarget::Parameter(parameter) => { + node.params.get(parameter).or_else(|| materialcraft_engine::nodes::find(&node.def)?.param(parameter).map(|parameter| ¶meter.default))? + } + FunctionTarget::Pattern { node: id, parameter } => { + let Value::PatternGraph(graph) = node.params.get("pattern")? else { return None }; + graph.nodes.iter().find(|node| node.id == *id)?.parameters.get(parameter)? + } + }; + + match value { + Value::Function(function) => Some((**function).clone()), + _ => None, + } +} + +pub(super) fn commit(app: &mut MaterialCraftApp, editor: &FunctionEditor, graph: &FunctionGraph) { + match &editor.target { + FunctionTarget::Graph(_) => { + app.run("graph.function.set", json!({"function": graph})); + } + FunctionTarget::Dynamic(parameter) => { + app.run("graph.node.function", json!({"id": editor.node.map(|node| node.0), "param": parameter, "function": graph})); + } + FunctionTarget::Parameter(parameter) => { + let value = Value::Function(Box::new(graph.clone())); + app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": parameter, "value": value})); + } + FunctionTarget::Pattern { node: id, parameter } => { + let Some(mut pattern) = + app.session.graph().ok().and_then(|graph| graph.node(editor.node?).ok()).and_then(|node| node.params.get("pattern")).cloned() + else { + return; + }; + + if let Value::PatternGraph(pattern) = &mut pattern + && let Some(node) = pattern.nodes.iter_mut().find(|node| node.id == *id) + { + node.parameters.insert(parameter.clone(), Value::Function(Box::new(graph.clone()))); + } + app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": "pattern", "value": pattern})); + } + } +} + +/// Draw the editor window when one is open +pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph(_))) { + return; + } + + let Some(mut e) = app.function_editor.take() else { return }; + let Some(mut g) = current(app, &e) else { return }; + let title = app.session.graph().ok().and_then(|gr| gr.node(e.node?).ok()).map(crate::graph::node_label).unwrap_or_default(); + let mut open = true; + let mut changed = false; + let what = if e.target.parameter() == "function" { tr("Function").to_string() } else { format!("{} {}", tr("Function"), e.target.parameter()) }; + egui::Window::new(format!("{title} - {what}")) + .id(egui::Id::unique(("fn-editor", e.node, &e.target))) + .open(&mut open) + .default_size(vec2(760.0, 460.0)) + .resizable(true) + .show(ctx, |ui| { + let tk = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label( + egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.")) + .size(11.0) + .color(tk.text_dim), + ); + }); + changed = canvas(app, &mut e, &mut g, ui); + }); + if changed { + commit(app, &e, &g); + } + if open { + app.function_editor = Some(e); + } +} + +pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) { + let index = app.session.graph; + let mut editor = + app.function_editor.take().filter(|editor| editor.target == FunctionTarget::Graph(index)).unwrap_or_else(|| FunctionEditor::standalone(index)); + let Some(mut graph) = current(app, &editor) else { return }; + + ui.horizontal(|ui| { + if ui.button(tr("Frame all")).clicked() { + editor.framed = false; + } + ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid")); + if graph.output.is_none() { + ui.label(tr("Set a node as the output")); + } + }); + if canvas(app, &mut editor, &mut graph, ui) { + commit(app, &editor, &graph); + } + app.function_editor = Some(editor); +} + +fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool) -> Rect { + let mut bounds = node_rect(node, app.ui.prefs.thumbnails); + if let Some(FunctionDrag::Node(d, delta)) = &editor.drag + && (*d == node.id || editor.selection.contains(&node.id)) + { + let position = materialcraft_engine::graph_grid::snap_position([node.pos[0] + delta.x, node.pos[1] + delta.y], snap); + bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); + } + if matches!(editor.target, FunctionTarget::Graph(_)) { + bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id))); + } + bounds +} + +fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool { + editor.selection.retain(|id| graph.node(*id).is_some()); + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); + let snap = app.ui.prefs.snap_to_grid; + let standalone = matches!(editor.target, FunctionTarget::Graph(_)); + let tokens = Tokens::get(ui.ctx()); + let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Function Graph"); + let painter = ui.painter_at(canvas_bounds); + painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); + if standalone { + app.graph.view = canvas_bounds; + app.graph.rects.clear(); + app.graph.ports.clear(); + app.graph.wires.clear(); + } + + if !editor.framed || (standalone && app.ui.frame_all) { + if standalone { + app.ui.frame_all = false; + } + + editor.framed = true; + let mut destination = + graph.nodes.iter().map(|node| node_rect(node, app.ui.prefs.thumbnails)).fold(Rect::NOTHING, |combined, bounds| combined.union(bounds)); + if standalone && let Ok(document) = app.session.graph() { + for frame in &document.frames { + destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0))); + } + } + if destination.is_finite() && destination.width() > 0.0 { + let destination = destination.expand(30.0); + editor.zoom = (canvas_bounds.width() / destination.width()).min(canvas_bounds.height() / destination.height()).clamp(0.3, 1.2); + editor.pan = destination.center().to_vec2() - canvas_bounds.size() * 0.5 / editor.zoom; + } + } + + let to_screen = |position: Pos2, editor: &FunctionEditor| canvas_bounds.min + (position.to_vec2() - editor.pan) * editor.zoom; + let to_graph = |source: Pos2, editor: &FunctionEditor| ((source - canvas_bounds.min) / editor.zoom + editor.pan).to_pos2(); + let mut changed = false; + let pointer = ui.input(|input| input.pointer.hover_pos()); + + // Zoom and pan + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); + if scroll.abs() > 0.0 + && let Some(pointer_position) = pointer + { + let before = to_graph(pointer_position, editor); + editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5); + editor.pan = before.to_vec2() - (pointer_position - canvas_bounds.min) / editor.zoom; + } + } + + let camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; + let document = standalone.then(|| app.session.graph().ok().cloned()).flatten(); + let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, graph, &camera)).unwrap_or_default(); + if standalone { + app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect(); + } + crate::graph::canvas::grid(&painter, &camera, canvas_bounds); + + // Wires + for node in &graph.nodes { + let bounds = preview_rect(app, editor, node, snap); + for (input_index, source_id) in node.inputs.iter().enumerate() { + if let Some(source) = source_id.and_then(|source| graph.node(source)) { + let source_position = to_screen(out_port(source, preview_rect(app, editor, source, snap)), editor); + let destination = to_screen(in_port(node, bounds, input_index), editor); + let control_offset = ((destination.x - source_position.x).abs() * 0.5).max(24.0); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke( + [source_position, source_position + vec2(control_offset, 0.0), destination - vec2(control_offset, 0.0), destination], + false, + Color32::TRANSPARENT, + Stroke::new(2.0, Color32::from_gray(0xb4)), + )); + } + } + } + + // Nodes + let font = FontId::proportional((11.0 * editor.zoom).min(16.0)); + let mut remove: Option<u32> = None; + let mut set_output: Option<u32> = None; + let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new(); + let ids: Vec<u32> = graph.nodes.iter().map(|node| node.id).collect(); + for id in ids { + let Some(node_index) = graph.nodes.iter().position(|node| node.id == id) else { continue }; + + let node = &graph.nodes[node_index]; + let bounds = preview_rect(app, editor, node, snap); + let screen_rect = Rect::from_min_max(to_screen(bounds.min, editor), to_screen(bounds.max, editor)); + if standalone { + app.graph.rects.push((materialcraft_engine::core::NodeId(u64::from(id)), screen_rect)); + } + + let dot = node.op == "passthrough"; + let show_labels = crate::graph::port_label::visible(ui, screen_rect); + let is_output = graph.output == Some(id); + let selected = editor.selection.contains(&id); + let outline = if selected { + tokens.accent + } else if dot { + Color32::from_gray(0xb4) + } else { + Color32::from_gray(0x10) + }; + + if dot { + node_card::paint_dot(&painter, screen_rect, outline); + } else { + node_card::paint(&painter, screen_rect, editor.zoom, label(&node.op), category_color(&node.op)); + node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); + let body = node_card::body(screen_rect, editor.zoom); + if node.value.is_none() { + painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); + } + if is_output { + let header = node_card::header(screen_rect, editor.zoom); + painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD); + } + } + + let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0); + let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value); + if let Some(definition) = materialcraft_engine::nodes::function::definition(&node.op) { + for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() { + let position = to_screen(in_port(node, bounds, input_index), editor); + painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); + if show_labels { + crate::graph::port_label::paint( + &painter, + position - vec2(10.0, 0.0), + Align2::RIGHT_CENTER, + port_label(identifier), + editor.zoom, + tokens.text_strong, + ); + } + ports.push((id, Some(input_index), position)); + } + } + + let output_position = to_screen(out_port(node, bounds), editor); + painter.circle(output_position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); + if show_labels { + crate::graph::port_label::paint( + &painter, + output_position + vec2(10.0, 0.0), + Align2::LEFT_CENTER, + port_label("output"), + editor.zoom, + tokens.text_strong, + ); + } + ports.push((id, None, output_position)); + + let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); + crate::widgets::name(&body, egui::Role::Button, label(&graph.nodes[node_index].op)); + + if !dot && node.value.is_some() { + let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); + child.set_clip_rect(content.intersect(canvas_bounds)); + if let Some(value) = graph.nodes[node_index].value.as_mut() { + changed |= crate::value_editor::show(&mut child, value); + } + } + + if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed())) || body.secondary_clicked() { + let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) }; + crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); + if standalone && app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", json!({})); + } + } + + if body.drag_started() && editor.selection.contains(&id) && editor.drag.is_none() && !app.graph.is_dragging() { + editor.drag = Some(FunctionDrag::Node(id, Vec2::ZERO)); + } + + body.context_menu(|ui| { + changed |= super::context_menu::show(app, editor, graph, ui); + ui.separator(); + if ui.button(format!("{} {}", icon::STAR, tr("Set as output node"))).clicked() { + set_output = Some(id); + ui.close(); + } + if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() { + remove = Some(id); + ui.close(); + } + }); + } + + if let Some(id) = set_output { + graph.output = Some(id); + changed = true; + } + + if let Some(id) = remove { + graph.nodes.retain(|node| node.id != id); + for node in &mut graph.nodes { + for source in &mut node.inputs { + if *source == Some(id) { + *source = None; + } + } + } + if graph.output == Some(id) { + graph.output = None; + } + changed = true; + } + + if standalone { + app.graph.ports = ports + .iter() + .map(|(id, input, position)| { + let identifier = input + .and_then(|slot| { + let node = graph.node(*id)?; + materialcraft_engine::nodes::function::definition(&node.op)?.inputs.get(slot).copied() + }) + .unwrap_or(if input.is_some() { "input" } else { "output" }); + + crate::graph::PortHit { + node: materialcraft_engine::core::NodeId(u64::from(*id)), + port: input.map_or_else(|| "output".into(), |slot| slot.to_string()), + label: port_label(identifier).into(), + output: input.is_none(), + kind: materialcraft_engine::nodes::PortKind::Value, + pos: *position, + } + }) + .collect(); + app.ui.graph_camera.pan = [editor.pan.x, editor.pan.y]; + app.ui.graph_camera.zoom = editor.zoom; + } + + // Gestures: wires from output dots, panning + let near = |pointer_position: Pos2| { + ports + .iter() + .filter(|(id, _, position)| { + let dot = graph.node(*id).is_some_and(|node| node.op == "passthrough"); + let radius = if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }; + position.distance(pointer_position) < radius + }) + .min_by(|first, second| first.2.distance(pointer_position).total_cmp(&second.2.distance(pointer_position))) + .cloned() + }; + if response.drag_started_by(egui::PointerButton::Middle) || (response.drag_started() && ui.input(|input| input.modifiers.alt)) { + editor.drag = Some(FunctionDrag::Pan); + } else if ui.input(|input| input.pointer.primary_pressed()) + && editor.drag.is_none() + && !app.graph.is_dragging() + && let Some(pointer_position) = pointer + && canvas_bounds.contains(pointer_position) + && let Some((id, None, _)) = near(pointer_position) + { + editor.drag = Some(FunctionDrag::Wire(id)); + } + + let delta = ui.input(|input| input.pointer.delta()); + match &mut editor.drag { + Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom, + Some(FunctionDrag::Pan) => editor.pan -= delta / editor.zoom, + Some(FunctionDrag::Wire(id)) => { + if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|(node, source, _)| node == id && source.is_none())) { + painter.line_segment([source_id.2, pointer_position], Stroke::new(2.0, tokens.accent)); + } + } + None => {} + } + + if ui.input(|input| input.pointer.any_released()) { + match editor.drag.take() { + Some(FunctionDrag::Node(id, offset)) => { + if offset.length() > 0.5 { + for node in graph.nodes.iter_mut().filter(|node| node.id == id || editor.selection.contains(&node.id)) { + node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset.x, node.pos[1] + offset.y], snap); + } + changed = true; + } + } + Some(FunctionDrag::Wire(source_id)) => { + if let Some(pointer_position) = pointer + && let Some((destination_id, Some(slot), _)) = near(pointer_position) + && destination_id != source_id + && !reaches(graph, destination_id, source_id) + && let Some(node) = graph.nodes.iter_mut().find(|node| node.id == destination_id) + { + if node.inputs.len() <= slot { + node.inputs.resize(slot + 1, None); + } + node.inputs[slot] = Some(source_id); + changed = true; + } + } + _ => {} + } + } + + if response.clicked() { + crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers)); + } + + // Adding operations + if response.secondary_clicked() + && let Some(pointer_position) = pointer + { + editor.menu_at = to_graph(pointer_position, editor); + } + if response.hovered() + && ui.input(|input| input.key_pressed(egui::Key::Space)) + && let Some(pointer_position) = pointer + { + editor.menu_at = to_graph(pointer_position, editor); + egui::Popup::open_id(ui.ctx(), response.id.with("menu")); + } + response.context_menu(|ui| { + changed |= super::context_menu::show(app, editor, graph, ui); + }); + + if let Some(document) = &document { + let comments = crate::graph::annotation_canvas::comments(app, ui, document, &camera); + app.graph.comments = comments.clone(); + crate::graph::annotation_canvas::pins(app, ui, document, &camera); + if editor.drag.is_none() { + crate::graph::annotation_input::handle(app, ui, &camera, &frame_hits, &comments); + if app.session.annotation_selection.is_some() { + editor.selection.clear(); + } + } + } + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.node(*id).is_some()); + changed +} + +// Wiring b into a is invalid when a already feeds b +fn reaches(g: &FunctionGraph, a: u32, b: u32) -> bool { + let mut stack = vec![b]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(n) = stack.pop() { + if n == a { + return true; + } + if !seen.insert(n) { + continue; + } + if let Some(node) = g.node(n) { + stack.extend(node.inputs.iter().flatten()); + } + } + false +} + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { + if app.session.annotation_selection.is_some() || !app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + return None; + } + super::selection::enabled(app.function_editor.as_ref()?, command) +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + if enabled(app, command).is_none() { + return false; + } + let Some(mut editor) = app.function_editor.take() else { return false }; + if let Some(mut graph) = current(app, &editor) + && super::selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid) + { + commit(app, &editor, &graph); + } + app.function_editor = Some(editor); + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cycles_are_detected() { + let mut g = FunctionGraph::default(); + let a = g.add("get_float2", &[], Some(Value::Text("$pos".into()))); + let b = g.add("swizzle1", &[a], Some(Value::Int(0))); + // a feeds b: wiring b into a would loop + assert!(reaches(&g, a, b)); + assert!(!reaches(&g, b, a)); + assert_eq!(arity("add"), 2); + assert!(materialcraft_engine::nodes::function::default_value("const_float1").is_some()); + } +} diff --git a/crates/ui-egui/src/function/context_menu.rs b/crates/ui-egui/src/function/context_menu.rs new file mode 100644 index 00000000..1f8430d3 --- /dev/null +++ b/crates/ui-egui/src/function/context_menu.rs @@ -0,0 +1,98 @@ +use super::{FunctionEditor, FunctionTarget, selection}; +use crate::{MaterialCraftApp, i18n::tr, menus}; +use egui::Ui; +use materialcraft_engine::{ + core::{FunctionGraph, FunctionNode}, + nodes::function::{FUNCTIONS, default_value}, +}; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool { + let mut changed = false; + let mut add = None; + let standalone = matches!(editor.target, FunctionTarget::Graph(_)); + ui.set_min_width(290.0); + ui.menu_button(tr("Add node"), |ui| { + let entries = FUNCTIONS.iter().filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, operation.category)); + add = crate::graph::add_node_menu::show(ui, entries); + }); + + if standalone { + for (label, command, parameters) in [ + ("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), + ("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})), + ("Add Navigation pin", "graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), + ] { + if ui.button(tr(label)).clicked() { + app.run(command, parameters); + editor.selection.clear(); + ui.close(); + } + } + } + if ui.button(tr("Add Dot node")).clicked() { + add = Some("passthrough"); + ui.close(); + } + ui.separator(); + + if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() { + menus::invoke(app, ui.ctx(), "file.save"); + ui.close(); + } + for (label, command) in [ + ("Paste", "edit.paste"), + ("Paste without link", "edit.pasteWithoutLinks"), + ("Select all", "edit.selectAll"), + ("Previous pin", "ui.graph.previousPin"), + ("Next pin", "ui.graph.nextPin"), + ("Copy selection", "edit.copy"), + ("Delete selection", "edit.delete"), + ("Delete and relink", "edit.deleteRelink"), + ("Duplicate selection", "edit.duplicate"), + ("Duplicate selection without link", "edit.duplicateWithoutLinks"), + ("Select upstream nodes", "graph.selectUpstream"), + ("Select downstream nodes", "graph.selectDownstream"), + ("Disable selection", "graph.node.disable"), + ] { + if command == "edit.copy" { + ui.separator(); + } + let annotation = standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink"); + let enabled = if annotation { true } else { selection::enabled(editor, command).unwrap_or_else(|| standalone && menus::enabled(app, command)) }; + let mut button = egui::Button::new(tr(label)); + if let Some(shortcut) = menus::shortcut_of(command) { + button = button.shortcut_text(shortcut); + } + if ui.add_enabled(enabled, button).clicked() { + if annotation { + app.run(command, json!({})); + } else if command.starts_with("ui.") { + menus::invoke(app, ui.ctx(), command); + editor.pan = app.ui.graph_camera.pan.into(); + } else { + changed |= selection::run(editor, graph, command, app.ui.prefs.snap_to_grid); + } + ui.close(); + } + } + + if let Some(operation) = add { + let id = graph.next_id(); + let inputs = FUNCTIONS.iter().find(|definition| definition.id == operation).map_or(0, |definition| definition.inputs.len()); + graph.nodes.push(FunctionNode { + id, + type_code: 0, + op: operation.into(), + inputs: vec![None; inputs], + value: default_value(operation), + pos: materialcraft_engine::graph_grid::snap_position([editor.menu_at.x, editor.menu_at.y], app.ui.prefs.snap_to_grid), + }); + editor.selection = vec![id]; + if graph.output.is_none() { + graph.output = Some(id); + } + changed = true; + } + changed +} diff --git a/crates/ui-egui/src/function/function_drag.rs b/crates/ui-egui/src/function/function_drag.rs new file mode 100644 index 00000000..4d38ae50 --- /dev/null +++ b/crates/ui-egui/src/function/function_drag.rs @@ -0,0 +1,7 @@ +use egui::Vec2; + +pub(super) enum FunctionDrag { + Node(u32, Vec2), + Wire(u32), + Pan, +} diff --git a/crates/ui-egui/src/function/function_editor.rs b/crates/ui-egui/src/function/function_editor.rs new file mode 100644 index 00000000..fe8f39a8 --- /dev/null +++ b/crates/ui-egui/src/function/function_editor.rs @@ -0,0 +1,49 @@ +use egui::{Pos2, Vec2, vec2}; +use materialcraft_engine::core::NodeId; + +use super::{FunctionDrag, FunctionTarget}; + +pub struct FunctionEditor { + pub node: Option<NodeId>, + pub(crate) selection: Vec<u32>, + pub(crate) inspected_node: Option<u32>, + pub(super) clipboard: Vec<materialcraft_engine::core::FunctionNode>, + pub target: FunctionTarget, + pub(super) pan: Vec2, + pub(super) zoom: f32, + pub(super) drag: Option<FunctionDrag>, + pub(super) menu_at: Pos2, + pub(super) framed: bool, +} + +impl FunctionEditor { + pub fn standalone(graph: usize) -> Self { + Self { + node: None, + target: FunctionTarget::Graph(graph), + selection: Vec::new(), + inspected_node: None, + clipboard: Vec::new(), + pan: vec2(-40.0, -40.0), + zoom: 1.0, + drag: None, + menu_at: Pos2::ZERO, + framed: false, + } + } + + pub fn new(node: NodeId, target: FunctionTarget) -> FunctionEditor { + FunctionEditor { + node: Some(node), + selection: Vec::new(), + inspected_node: None, + clipboard: Vec::new(), + target, + pan: vec2(-40.0, -40.0), + zoom: 1.0, + drag: None, + menu_at: Pos2::ZERO, + framed: false, + } + } +} diff --git a/crates/ui-egui/src/function/function_target.rs b/crates/ui-egui/src/function/function_target.rs new file mode 100644 index 00000000..4f83a487 --- /dev/null +++ b/crates/ui-egui/src/function/function_target.rs @@ -0,0 +1,16 @@ +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum FunctionTarget { + Graph(usize), + Parameter(String), + Dynamic(String), + Pattern { node: u32, parameter: String }, +} + +impl FunctionTarget { + pub fn parameter(&self) -> &str { + match self { + Self::Graph(_) => "", + Self::Parameter(parameter) | Self::Dynamic(parameter) | Self::Pattern { parameter, .. } => parameter, + } + } +} diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs new file mode 100644 index 00000000..b41437bc --- /dev/null +++ b/crates/ui-egui/src/function/library.rs @@ -0,0 +1,25 @@ +use crate::{MaterialCraftApp, i18n::tr}; +use egui::Ui; +use materialcraft_engine::nodes::function::{FUNCTIONS, default_value}; +use serde_json::json; + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions"))); + let search = app.ui.library_search.to_ascii_lowercase(); + egui::ScrollArea::vertical().show(ui, |ui| { + for definition in FUNCTIONS.iter().filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { + if ui.selectable_label(false, tr(definition.label)).double_clicked() + && let Some(mut graph) = app.session.graph().ok().and_then(|graph| graph.function.clone()) + { + let id = graph.add(definition.id, &[], default_value(definition.id)); + if graph.output.is_none() { + graph.output = Some(id); + } + if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) { + node.pos = materialcraft_engine::graph_grid::snap_position(node.pos, app.ui.prefs.snap_to_grid); + } + app.run("graph.function.set", json!({"function": graph})); + } + } + }); +} diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs new file mode 100644 index 00000000..b8a0181e --- /dev/null +++ b/crates/ui-egui/src/function/mod.rs @@ -0,0 +1,14 @@ +mod canvas; +mod context_menu; +mod function_drag; +mod function_editor; +mod function_target; +pub(crate) mod library; +mod port_label; +pub(crate) mod properties; +mod selection; + +pub(crate) use canvas::{enabled, invoke, show, show_graph}; +use function_drag::FunctionDrag; +pub use function_editor::FunctionEditor; +pub use function_target::FunctionTarget; diff --git a/crates/ui-egui/src/function/port_label.rs b/crates/ui-egui/src/function/port_label.rs new file mode 100644 index 00000000..c41b250d --- /dev/null +++ b/crates/ui-egui/src/function/port_label.rs @@ -0,0 +1,26 @@ +pub(super) fn port_label(identifier: &str) -> &str { + match identifier { + "a" => "A", + "b" => "B", + "x" => "Factor", + "scalar" => "Scalar", + "rho" => "Radius", + "theta" => "Angle", + "componentsin" => "Components", + "componentslast" => "Last Component", + "vector" => "Vector", + "value" => "Value", + "pos" => "Position", + "condition" => "Condition", + "ifpath" => "If", + "elsepath" => "Else", + "seqin" => "First", + "seqlast" => "Last", + "init" => "Initial Value", + "cond" => "Exit Condition", + "loop" => "Loop", + "input" => "Input", + "output" => "Output", + _ => identifier, + } +} diff --git a/crates/ui-egui/src/function/properties.rs b/crates/ui-egui/src/function/properties.rs new file mode 100644 index 00000000..7a6eea13 --- /dev/null +++ b/crates/ui-egui/src/function/properties.rs @@ -0,0 +1,43 @@ +use egui::Ui; +use materialcraft_engine::{core::FunctionGraph, nodes::function::definition}; + +use super::{FunctionTarget, canvas}; +use crate::{MaterialCraftApp, graph::node_selection, i18n::tr}; + +fn current(app: &MaterialCraftApp) -> Option<(&FunctionGraph, u32)> { + let editor = app.function_editor.as_ref()?; + if editor.target != FunctionTarget::Graph(app.session.graph) { + return None; + } + + let graph = app.session.graph().ok()?.function.as_ref()?; + let id = node_selection::inspected(&editor.selection, editor.inspected_node)?; + graph.node(id)?; + Some((graph, id)) +} + +pub(crate) fn title(app: &MaterialCraftApp) -> Option<String> { + let (graph, id) = current(app)?; + let node = graph.node(id)?; + let label = definition(&node.op).map_or(node.op.as_str(), |definition| definition.label); + Some(format!("{label} - {}", tr("Properties"))) +} + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { + let Some((graph, id)) = current(app) else { return false }; + let mut graph = graph.clone(); + let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) else { return false }; + + let label = definition(&node.op).map_or(node.op.as_str(), |definition| definition.label); + ui.heading(tr(label)); + if graph.output == Some(id) { + ui.label(tr("Output node")); + } + + let changed = node.value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)); + if changed && let Some(editor) = app.function_editor.take() { + canvas::commit(app, &editor, &graph); + app.function_editor = Some(editor); + } + true +} diff --git a/crates/ui-egui/src/function/selection.rs b/crates/ui-egui/src/function/selection.rs new file mode 100644 index 00000000..baf41e3d --- /dev/null +++ b/crates/ui-egui/src/function/selection.rs @@ -0,0 +1,104 @@ +use super::FunctionEditor; +use materialcraft_engine::core::{FunctionGraph, FunctionNode}; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn enabled(editor: &FunctionEditor, command: &str) -> Option<bool> { + Some(match command { + "edit.selectAll" | "edit.selectNone" => true, + "edit.paste" | "edit.pasteWithoutLinks" => !editor.clipboard.is_empty(), + "edit.copy" + | "edit.cut" + | "edit.delete" + | "edit.deleteRelink" + | "edit.duplicate" + | "edit.duplicateWithoutLinks" + | "graph.selectUpstream" + | "graph.selectDownstream" => !editor.selection.is_empty(), + "graph.node.disable" => false, + _ => return None, + }) +} + +pub(super) fn run(editor: &mut FunctionEditor, graph: &mut FunctionGraph, command: &str, snap: bool) -> bool { + match command { + "edit.selectAll" => editor.selection = graph.nodes.iter().map(|node| node.id).collect(), + "edit.selectNone" => editor.selection.clear(), + "edit.copy" | "edit.cut" => { + editor.clipboard = graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect(); + if command == "edit.cut" { + return remove(editor, graph, false); + } + } + "edit.delete" | "edit.deleteRelink" => return remove(editor, graph, command == "edit.deleteRelink"), + "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { + let duplicate = command.starts_with("edit.duplicate"); + let nodes: Vec<FunctionNode> = + if duplicate { graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect() } else { editor.clipboard.clone() }; + let anchor = nodes.first().map_or([0.0; 2], |node| node.pos); + let offset = if duplicate { [32.0; 2] } else { [editor.menu_at.x - anchor[0], editor.menu_at.y - anchor[1]] }; + let mut ids = BTreeMap::new(); + for mut node in nodes { + let source = node.id; + node.id = graph.next_id(); + node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset[0], node.pos[1] + offset[1]], snap); + ids.insert(source, node.id); + graph.nodes.push(node); + } + editor.selection = ids.values().copied().collect(); + for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { + for input in &mut node.inputs { + *input = input.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks")).then_some(id))); + } + } + return !ids.is_empty(); + } + "graph.selectUpstream" | "graph.selectDownstream" => { + let upstream = command == "graph.selectUpstream"; + let mut visited = BTreeSet::new(); + let mut pending = editor.selection.clone(); + while let Some(id) = pending.pop() { + if !visited.insert(id) { + continue; + } + if upstream { + if let Some(node) = graph.node(id) { + pending.extend(node.inputs.iter().flatten()); + } + } else { + pending.extend(graph.nodes.iter().filter(|node| node.inputs.contains(&Some(id))).map(|node| node.id)); + } + } + editor.selection = visited.into_iter().collect(); + } + _ => {} + } + false +} + +fn remove(editor: &mut FunctionEditor, graph: &mut FunctionGraph, relink: bool) -> bool { + let replacements: BTreeMap<_, _> = graph + .nodes + .iter() + .filter(|node| editor.selection.contains(&node.id)) + .map(|node| (node.id, if relink { node.inputs.first().copied().flatten() } else { None })) + .collect(); + graph.nodes.retain(|node| !editor.selection.contains(&node.id)); + for node in &mut graph.nodes { + for input in &mut node.inputs { + let mut seen = BTreeSet::new(); + while let Some(id) = *input { + let Some(replacement) = replacements.get(&id) else { break }; + if !seen.insert(id) { + *input = None; + break; + } + *input = *replacement; + } + } + } + if graph.output.is_some_and(|id| editor.selection.contains(&id)) { + graph.output = None; + } + editor.selection.clear(); + !replacements.is_empty() +} diff --git a/crates/ui-egui/src/function_editor.rs b/crates/ui-egui/src/function_editor.rs deleted file mode 100644 index 40b39a38..00000000 --- a/crates/ui-egui/src/function_editor.rs +++ /dev/null @@ -1,438 +0,0 @@ -//! The function graph editor: a window with a small node canvas for a pixel or value -//! processor's function. Right-click (or Space) adds operations by category, dragging from an -//! output to an input wires them, the starred node is the result. Each change commits the whole -//! function through `graph.node.param`. - -use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::NodeId; -use materialcraft_engine::core::Value; -use materialcraft_engine::core::function::{FnGraph, FnNode}; -use materialcraft_engine::nodes::function::FN_OPS; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -const W: f32 = 130.0; -const HEADER: f32 = 18.0; -const ROW: f32 = 18.0; - -/// The open editor: which node's parameter, and the canvas camera. -pub struct FnEditor { - pub node: NodeId, - pub param: String, - pan: Vec2, - zoom: f32, - drag: Option<FnDrag>, - menu_at: Pos2, - /// The camera has been fitted to the nodes. - framed: bool, -} - -enum FnDrag { - Node(u32, Vec2), - Wire(u32), - Pan, -} - -impl FnEditor { - pub fn new(node: NodeId, param: &str) -> FnEditor { - FnEditor { node, param: param.into(), pan: vec2(-40.0, -40.0), zoom: 1.0, drag: None, menu_at: Pos2::ZERO, framed: false } - } -} - -fn arity(op: &str) -> usize { - FN_OPS.iter().find(|o| o.0 == op).map_or(0, |o| o.2) -} - -fn label(op: &str) -> &'static str { - FN_OPS.iter().find(|o| o.0 == op).map_or("?", |o| o.1) -} - -fn category_color(op: &str) -> Color32 { - match FN_OPS.iter().find(|o| o.0 == op).map_or("", |o| o.3) { - "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), - "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), - "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), - "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), - "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), - } -} - -/// The value a new node of `op` starts with. -fn default_value(op: &str) -> Option<Value> { - Some(match op { - "const_float" => Value::Float(0.5), - "const_float2" => Value::Float2([0.5, 0.5]), - "const_float3" => Value::Float3([0.5, 0.5, 0.5]), - "const_float4" => Value::Float4([0.5, 0.5, 0.5, 1.0]), - "const_int" => Value::Int(1), - "const_bool" => Value::Bool(true), - "get_var" => Value::Text(String::new()), - "sample_gray" | "sample_color" => Value::Int(0), - "swizzle" => Value::Text("x".into()), - _ => return None, - }) -} - -fn node_rect(n: &FnNode) -> Rect { - let rows = arity(&n.op).max(1) as f32 + if n.value.is_some() { 1.0 } else { 0.0 }; - Rect::from_min_size(pos2(n.pos[0], n.pos[1]), vec2(W, HEADER + rows * ROW + 6.0)) -} - -fn in_port(r: Rect, i: usize) -> Pos2 { - pos2(r.left(), r.top() + HEADER + ROW * (i as f32 + 0.5)) -} - -fn out_port(r: Rect) -> Pos2 { - pos2(r.right(), r.top() + HEADER + ROW * 0.5) -} - -/// The function currently stored on the node: a function parameter, or (`fn:<param>`) the -/// function driving a dynamic parameter. -fn current(app: &MaterialCraftApp, e: &FnEditor) -> Option<FnGraph> { - let n = app.session.graph().ok()?.node(e.node).ok()?; - if let Some(p) = e.param.strip_prefix("fn:") { - return n.functions.get(p).cloned(); - } - match n.params.get(&e.param) { - Some(Value::Function(f)) => Some((**f).clone()), - _ => materialcraft_engine::nodes::find(&n.def)?.param(&e.param).and_then(|p| match &p.default { - Value::Function(f) => Some((**f).clone()), - _ => None, - }), - } -} - -fn commit(app: &mut MaterialCraftApp, node: NodeId, param: &str, g: &FnGraph) { - if let Some(p) = param.strip_prefix("fn:") { - app.run("graph.node.function", json!({"id": node.0, "param": p, "function": g})); - return; - } - let v = serde_json::to_value(Value::Function(Box::new(g.clone()))).unwrap_or(serde_json::Value::Null); - app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v})); -} - -/// Draw the editor window when one is open. -pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let Some(mut e) = app.fn_editor.take() else { return }; - let Some(mut g) = current(app, &e) else { return }; - let title = app.session.graph().ok().and_then(|gr| gr.node(e.node).ok()).map(crate::graph_view::node_label).unwrap_or_default(); - let mut open = true; - let mut changed = false; - let what = e.param.strip_prefix("fn:").map_or_else(|| tr("Function graph").to_string(), |p| format!("{} {p}", tr("Function of"))); - egui::Window::new(format!("{title} - {what}")) - .id(egui::Id::unique(("fn-editor", e.node.0, e.param.as_str()))) - .open(&mut open) - .default_size(vec2(760.0, 460.0)) - .resizable(true) - .show(ctx, |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label( - egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.")) - .size(11.0) - .color(tk.text_dim), - ); - }); - changed = canvas(&mut e, &mut g, ui); - }); - if changed { - commit(app, e.node, &e.param, &g); - } - if open { - app.fn_editor = Some(e); - } -} - -fn canvas(e: &mut FnEditor, g: &mut FnGraph, ui: &mut Ui) -> bool { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Function graph"); - let p = ui.painter_at(rect); - p.rect_filled(rect, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); - if !e.framed { - e.framed = true; - let b = g.nodes.iter().map(node_rect).fold(Rect::NOTHING, |a, r| a.union(r)); - if b.is_finite() && b.width() > 0.0 { - let b = b.expand(30.0); - e.zoom = (rect.width() / b.width()).min(rect.height() / b.height()).clamp(0.3, 1.2); - e.pan = b.center().to_vec2() - rect.size() * 0.5 / e.zoom; - } - } - let to_s = |q: Pos2, e: &FnEditor| rect.min + (q.to_vec2() - e.pan) * e.zoom; - let to_g = |s: Pos2, e: &FnEditor| ((s - rect.min) / e.zoom + e.pan).to_pos2(); - let mut changed = false; - let pointer = ui.input(|i| i.pointer.hover_pos()); - - // Zoom and pan. - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); - if scroll.abs() > 0.0 - && let Some(ptr) = pointer - { - let before = to_g(ptr, e); - e.zoom = (e.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5); - e.pan = before.to_vec2() - (ptr - rect.min) / e.zoom; - } - } - - // Wires. - for n in &g.nodes { - let r = node_rect(n); - for (i, src) in n.inputs.iter().enumerate() { - if let Some(s) = src.and_then(|s| g.node(s)) { - let a = to_s(out_port(node_rect(s)), e); - let b = to_s(in_port(r, i), e); - let dx = ((b.x - a.x).abs() * 0.5).max(24.0); - p.add(egui::epaint::CubicBezierShape::from_points_stroke( - [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b], - false, - Color32::TRANSPARENT, - Stroke::new(2.0, Color32::from_gray(0xb4)), - )); - } - } - } - - // Nodes. - let font = FontId::proportional((11.0 * e.zoom).clamp(7.0, 16.0)); - let mut remove: Option<u32> = None; - let mut set_output: Option<u32> = None; - let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new(); - let ids: Vec<u32> = g.nodes.iter().map(|n| n.id).collect(); - for id in ids { - let Some(idx) = g.nodes.iter().position(|n| n.id == id) else { continue }; - let mut r = node_rect(&g.nodes[idx]); - if let Some(FnDrag::Node(d, delta)) = &e.drag - && *d == id - { - r = r.translate(*delta); - } - let sr = Rect::from_min_max(to_s(r.min, e), to_s(r.max, e)); - let n = &g.nodes[idx]; - let is_out = g.output == Some(id); - p.rect_filled(sr, 5.0, Color32::from_rgb(0x1e, 0x20, 0x24)); - let header = Rect::from_min_size(sr.min, vec2(sr.width(), HEADER * e.zoom)); - p.rect_filled(header, egui::CornerRadius { nw: 5, ne: 5, sw: 0, se: 0 }, category_color(&n.op)); - let star = if is_out { format!("{} ", icon::STAR) } else { String::new() }; - p.text(header.left_center() + vec2(5.0, 0.0), Align2::LEFT_CENTER, format!("{star}{}", label(&n.op)), font.clone(), Color32::WHITE); - p.rect_stroke(sr, 5.0, Stroke::new(if is_out { 2.0 } else { 1.0 }, if is_out { tk.accent } else { Color32::from_gray(0x10) }), StrokeKind::Outside); - for i in 0..arity(&n.op) { - let pos = to_s(in_port(r, i), e); - p.circle(pos, 4.5, Color32::from_gray(0xc8), Stroke::new(1.0, Color32::from_gray(0x18))); - ports.push((id, Some(i), pos)); - } - let op = to_s(out_port(r), e); - p.circle(op, 4.5, Color32::from_rgb(0xe8, 0xa9, 0x3c), Stroke::new(1.0, Color32::from_gray(0x18))); - ports.push((id, None, op)); - // Inline value editor. - if n.value.is_some() { - let row = Rect::from_min_size( - to_s(pos2(r.left() + 6.0, r.top() + HEADER + arity(&n.op).max(1) as f32 * ROW + 2.0), e), - vec2((W - 12.0) * e.zoom, (ROW - 2.0) * e.zoom), - ); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(row)); - if let Some(v) = g.nodes[idx].value.as_mut() { - changed |= value_editor(&mut child, v); - } - } - let body = ui.interact(sr, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); - crate::widgets::name(&body, egui::Role::Button, label(&g.nodes[idx].op)); - if body.drag_started() && e.drag.is_none() { - e.drag = Some(FnDrag::Node(id, Vec2::ZERO)); - } - body.context_menu(|ui| { - if ui.button(format!("{} {}", icon::STAR, tr("Use as result"))).clicked() { - set_output = Some(id); - ui.close(); - } - if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() { - remove = Some(id); - ui.close(); - } - }); - } - if let Some(id) = set_output { - g.output = Some(id); - changed = true; - } - if let Some(id) = remove { - g.nodes.retain(|n| n.id != id); - for n in &mut g.nodes { - for i in &mut n.inputs { - if *i == Some(id) { - *i = None; - } - } - } - if g.output == Some(id) { - g.output = None; - } - changed = true; - } - - // Gestures: wires from output dots, panning. - let near = |ptr: Pos2| ports.iter().filter(|(_, _, q)| q.distance(ptr) < 9.0).min_by(|a, b| a.2.distance(ptr).total_cmp(&b.2.distance(ptr))).cloned(); - if resp.drag_started_by(egui::PointerButton::Middle) || (resp.drag_started() && ui.input(|i| i.modifiers.alt)) { - e.drag = Some(FnDrag::Pan); - } else if ui.input(|i| i.pointer.primary_pressed()) - && e.drag.is_none() - && let Some(ptr) = pointer - && rect.contains(ptr) - && let Some((id, None, _)) = near(ptr) - { - e.drag = Some(FnDrag::Wire(id)); - } - let delta = ui.input(|i| i.pointer.delta()); - match &mut e.drag { - Some(FnDrag::Node(_, d)) => *d += delta / e.zoom, - Some(FnDrag::Pan) => e.pan -= delta / e.zoom, - Some(FnDrag::Wire(id)) => { - if let (Some(ptr), Some(src)) = (pointer, ports.iter().find(|(n, s, _)| n == id && s.is_none())) { - p.line_segment([src.2, ptr], Stroke::new(2.0, tk.accent)); - } - } - None => {} - } - if ui.input(|i| i.pointer.any_released()) { - match e.drag.take() { - Some(FnDrag::Node(id, d)) => { - if let Some(n) = g.nodes.iter_mut().find(|n| n.id == id) - && d.length() > 0.5 - { - n.pos = [n.pos[0] + d.x, n.pos[1] + d.y]; - changed = true; - } - } - Some(FnDrag::Wire(src)) => { - if let Some(ptr) = pointer - && let Some((dst, Some(slot), _)) = near(ptr) - && dst != src - && !reaches(g, dst, src) - && let Some(n) = g.nodes.iter_mut().find(|n| n.id == dst) - { - if n.inputs.len() <= slot { - n.inputs.resize(slot + 1, None); - } - n.inputs[slot] = Some(src); - changed = true; - } - } - _ => {} - } - } - - // Adding operations. - if resp.secondary_clicked() - && let Some(ptr) = pointer - { - e.menu_at = to_g(ptr, e); - } - if resp.hovered() - && ui.input(|i| i.key_pressed(egui::Key::Space)) - && let Some(ptr) = pointer - { - e.menu_at = to_g(ptr, e); - egui::Popup::open_id(ui.ctx(), resp.id.with("menu")); - } - let at = e.menu_at; - let mut add: Option<&'static str> = None; - resp.context_menu(|ui| { - let mut cats: Vec<&str> = FN_OPS.iter().map(|o| o.3).collect(); - cats.dedup(); - for c in cats { - ui.menu_button(tr(c), |ui| { - for o in FN_OPS.iter().filter(|o| o.3 == c) { - if ui.button(tr(o.1)).clicked() { - add = Some(o.0); - ui.close(); - } - } - }); - } - }); - if let Some(op) = add { - let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1); - g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [at.x, at.y] }); - if g.output.is_none() { - g.output = Some(id); - } - changed = true; - } - changed -} - -/// Whether `a` feeds `b` (directly or through other nodes, or is `b`): then `b` may not feed `a`. -fn reaches(g: &FnGraph, a: u32, b: u32) -> bool { - let mut stack = vec![b]; - let mut seen = std::collections::BTreeSet::new(); - while let Some(n) = stack.pop() { - if n == a { - return true; - } - if !seen.insert(n) { - continue; - } - if let Some(node) = g.node(n) { - stack.extend(node.inputs.iter().flatten()); - } - } - false -} - -/// A compact editor for a function node's value. Returns true when it changed. -fn value_editor(ui: &mut Ui, v: &mut Value) -> bool { - let drag = |ui: &mut Ui, f: &mut f32| ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(3)).changed(); - ui.horizontal(|ui| match v { - Value::Float(f) => drag(ui, f), - Value::Float2(a) => { - let x = drag(ui, &mut a[0]); - drag(ui, &mut a[1]) || x - } - Value::Float3(a) => { - let mut c = false; - for f in a.iter_mut() { - c |= drag(ui, f); - } - c - } - Value::Float4(a) | Value::Color(a) => { - let mut c = false; - for f in a.iter_mut() { - c |= ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(2)).changed(); - } - c - } - Value::Int(i) => ui.add(egui::DragValue::new(i).speed(0.1)).changed(), - Value::Bool(b) => ui.checkbox(b, "").changed(), - Value::Text(t) => { - let r = ui.add(egui::TextEdit::singleline(t).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, "Value"); - r.changed() - } - _ => false, - }) - .inner -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cycles_are_detected() { - let mut g = FnGraph::default(); - let a = g.add("get_pos", &[], None); - let b = g.add("swizzle", &[a], Some(Value::Text("x".into()))); - // a feeds b: wiring b into a would loop. - assert!(reaches(&g, a, b)); - assert!(!reaches(&g, b, a)); - assert_eq!(arity("add"), 2); - assert!(default_value("const_float").is_some()); - } -} diff --git a/crates/ui-egui/src/graph/actions.rs b/crates/ui-egui/src/graph/actions.rs new file mode 100644 index 00000000..84d38eed --- /dev/null +++ b/crates/ui-egui/src/graph/actions.rs @@ -0,0 +1,71 @@ +use crate::{MaterialCraftApp, docking::Panel}; + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { + match command { + "ui.graph.previousPin" | "ui.graph.nextPin" => Some(app.session.graph().is_ok_and(|graph| !graph.pins.is_empty())), + command if command.starts_with("ui.graph.") => Some(app.session.graph().is_ok()), + _ => None, + } +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + match command { + "graph.node.edit" => { + if !crate::menus::enabled(app, command) { + return true; + } + + let Some(result) = app.run(command, serde_json::Value::Null) else { return true }; + let Some(node) = result.get("node").and_then(serde_json::Value::as_u64) else { return true }; + + app.function_editor = None; + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, materialcraft_engine::core::NodeId(node))); + app.ui.dock.focus(Panel::Graph); + } + "ui.graph.snapToGrid" => app.ui.prefs.snap_to_grid = !app.ui.prefs.snap_to_grid, + "ui.graph.viewOutputs" | "ui.graph.resetViewOutputs" => { + if command == "ui.graph.resetViewOutputs" { + app.run("view.3d.reset", serde_json::Value::Null); + } + + app.ui.dock.focus(Panel::View3d); + app.session.dirty = true; + } + "ui.graph.computeThumbnails" => { + app.graph.thumbnails_cleared = false; + app.ui.prefs.thumbnails = true; + app.session.dirty = true; + } + "ui.graph.clearThumbnails" => { + app.thumbs.clear_nodes(); + app.graph.thumbnails_cleared = true; + } + "ui.graph.previousPin" => navigate_pin(app, false), + "ui.graph.nextPin" => navigate_pin(app, true), + _ => return false, + } + + true +} + +fn navigate_pin(app: &mut MaterialCraftApp, forward: bool) { + let Ok(graph) = app.session.graph() else { return }; + if graph.pins.is_empty() { + return; + } + + let camera = &mut app.ui.graph_camera; + let zoom = camera.zoom.clamp(0.08, 4.0); + let center = [camera.pan[0] + app.graph.view.width() * 0.5 / zoom, camera.pan[1] + app.graph.view.height() * 0.5 / zoom]; + let current = graph.pins.iter().position(|pin| (pin.pos[0] - center[0]).abs() < 0.1 && (pin.pos[1] - center[1]).abs() < 0.1); + let count = graph.pins.len(); + let index = match current { + Some(index) if forward => (index + 1) % count, + Some(index) => (index + count - 1) % count, + None if forward => 0, + None => count - 1, + }; + let Some(pin) = graph.pins.get(index) else { return }; + + camera.pan = [pin.pos[0] - app.graph.view.width() * 0.5 / zoom, pin.pos[1] - app.graph.view.height() * 0.5 / zoom]; +} diff --git a/crates/ui-egui/src/graph/add_node_menu.rs b/crates/ui-egui/src/graph/add_node_menu.rs new file mode 100644 index 00000000..e1f783e0 --- /dev/null +++ b/crates/ui-egui/src/graph/add_node_menu.rs @@ -0,0 +1,105 @@ +use egui::{Button, Event, Key, Ui}; + +use crate::i18n::tr; + +pub(crate) fn show(ui: &mut Ui, entries: impl IntoIterator<Item = (&'static str, &'static str, &'static str)>) -> Option<&'static str> { + let filter_id = ui.make_persistent_id("add-node-filter"); + let frame = ui.ctx().cumulative_frame_nr(); + let previous = ui.ctx().data_mut(|data| data.get_temp::<(u64, Option<char>)>(filter_id)); + let mut filter = previous.filter(|(last_frame, _)| frame <= last_frame.saturating_add(1)).and_then(|(_, letter)| letter); + + ui.input(|input| { + for event in &input.events { + let Event::Key { key, pressed: true, modifiers, .. } = event else { continue }; + if modifiers.ctrl || modifiers.alt || modifiers.command { + continue; + } + + if *key == Key::Backspace { + filter = None; + } else if key.name().len() == 1 { + filter = key.name().chars().next().map(|letter| letter.to_ascii_lowercase()); + } + } + }); + + let mut entries: Vec<_> = entries.into_iter().collect(); + entries.sort_by_key(|(_, label, category)| (*category, *label)); + let mut selected = None; + let enter = filter.is_some() && ui.input(|input| input.key_pressed(Key::Enter)); + ui.set_min_width(220.0); + let height = (ui.ctx().content_rect().height() - 16.0).max(100.0); + ui.set_max_height(height); + egui::ScrollArea::vertical().max_height(height).show(ui, |ui| { + let mut previous_category = None; + for (id, label, category) in entries { + if previous_category != Some(category) { + if previous_category.is_some() { + ui.separator(); + } + previous_category = Some(category); + } + + let label = tr(label); + let enabled = filter.is_none_or(|letter| label.chars().next().is_some_and(|first| first.eq_ignore_ascii_case(&letter))); + if ui.add_enabled(enabled, Button::new(label)).clicked() || (enter && enabled && selected.is_none()) { + selected = Some(id); + } + } + }); + + if selected.is_some() { + ui.ctx().data_mut(|data| data.remove::<(u64, Option<char>)>(filter_id)); + ui.close(); + } else { + ui.ctx().data_mut(|data| data.insert_temp(filter_id, (frame, filter))); + } + selected +} + +#[cfg(test)] +mod tests { + use egui_kittest::{ + Harness, + kittest::{By, NodeT, Queryable}, + }; + + #[test] + fn letters_disable_other_initials_without_removing_entries() { + let mut harness = Harness::builder().build_ui_state( + |ui, selected: &mut Option<&'static str>| { + if let Some(id) = super::show( + ui, + [("svg", "SVG", "Atomic nodes"), ("sharpen", "Sharpen", "Atomic nodes"), ("grayscale", "Grayscale conversion", "Atomic nodes")], + ) { + *selected = Some(id); + } + }, + None, + ); + harness.run_steps(3); + harness.key_press(egui::Key::S); + harness.run_steps(3); + + let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); + assert!(!harness.get(button("SVG")).accesskit_node().is_disabled()); + assert!(!harness.get(button("Sharpen")).accesskit_node().is_disabled()); + assert!(harness.get(button("Grayscale conversion")).accesskit_node().is_disabled()); + + harness.key_press(egui::Key::G); + harness.run_steps(3); + assert!(harness.get(button("SVG")).accesskit_node().is_disabled()); + assert!(!harness.get(button("Grayscale conversion")).accesskit_node().is_disabled()); + + harness.key_press(egui::Key::Backspace); + harness.run_steps(3); + for label in ["SVG", "Sharpen", "Grayscale conversion"] { + assert!(!harness.get(button(label)).accesskit_node().is_disabled()); + } + + harness.key_press(egui::Key::S); + harness.key_press(egui::Key::Enter); + harness.step(); + assert_eq!(*harness.state(), Some("svg")); + } +} diff --git a/crates/ui-egui/src/graph/annotation_canvas.rs b/crates/ui-egui/src/graph/annotation_canvas.rs new file mode 100644 index 00000000..0071f915 --- /dev/null +++ b/crates/ui-egui/src/graph/annotation_canvas.rs @@ -0,0 +1,104 @@ +use egui::{Align2, Color32, FontId, Rect, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::{AnnotationSelection, core::Graph}; + +use super::{GraphCamera, GraphDrag, frame_hit::FrameHit}; +use crate::{MaterialCraftApp, theme::Tokens}; + +pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) -> Vec<FrameHit> { + let painter = ui.painter_at(app.graph.view); + let theme = Tokens::get(ui.ctx()); + let mut hits = Vec::with_capacity(graph.frames.len()); + + let mut frames: Vec<_> = graph.frames.iter().collect(); + frames.sort_by(|first, second| (second.rect[2] * second.rect[3]).total_cmp(&(first.rect[2] * first.rect[3]))); + + for frame in frames { + let mut rect = Rect::from_min_size(pos2(frame.rect[0], frame.rect[1]), vec2(frame.rect[2], frame.rect[3])); + rect = rect.translate(offset(app, |contents| contents.frames.contains(&frame.id))); + + if let Some(GraphDrag::Frame { id, delta, resize: true, .. }) = &app.graph.drag + && *id == frame.id + { + rect.max = rect.min + (rect.size() + *delta).max(Vec2::splat(10.0)); + } + + let rect = Rect::from_min_max(camera.to_screen(rect.min), camera.to_screen(rect.max)); + let color = frame.color; + let channel = |value| (materialcraft_engine::core::linear_to_srgb(value) * 255.0).round() as u8; + let fill = Color32::from_rgba_unmultiplied(channel(color[0]), channel(color[1]), channel(color[2]), (color[3] * 255.0).round() as u8); + let selected = app.session.annotation_selection == Some(AnnotationSelection::Frame(frame.id)); + let outline = if selected { Stroke::new(2.0, theme.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(180)) }; + painter.rect(rect, 0.0, fill, outline, StrokeKind::Outside); + + let title = if frame.title_visible { + painter.text( + rect.left_top() - vec2(0.0, 6.0 * camera.zoom), + Align2::LEFT_BOTTOM, + &frame.title, + FontId::proportional((24.0 * camera.zoom).clamp(8.0, 64.0)), + theme.text_strong, + ) + } else { + Rect::NOTHING + }; + + if !frame.description.is_empty() { + let content = rect.shrink(6.0 * camera.zoom); + let text = + painter.layout(frame.description.clone(), FontId::proportional((14.0 * camera.zoom).clamp(6.0, 36.0)), theme.text, content.width().max(1.0)); + painter.with_clip_rect(content.intersect(app.graph.view)).galley(content.min, text, theme.text); + } + + let grip = Rect::from_min_size(rect.max - vec2(12.0, 12.0), vec2(12.0, 12.0)); + painter.line_segment([grip.left_bottom(), grip.right_top()], Stroke::new(1.0, theme.text_dim)); + hits.push(FrameHit { id: frame.id, rect, title, grip }); + } + + hits +} + +pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) -> Vec<(u64, Rect)> { + let painter = ui.painter_at(app.graph.view); + let theme = Tokens::get(ui.ctx()); + let mut hits = Vec::with_capacity(graph.comments.len()); + + for comment in &graph.comments { + let mut position = pos2(comment.pos[0], comment.pos[1]) + offset(app, |contents| contents.comments.contains(&comment.id)); + if let Some(GraphDrag::Comment { id, delta }) = &app.graph.drag + && *id == comment.id + { + position += *delta; + } + + let selected = app.session.annotation_selection == Some(AnnotationSelection::Comment(comment.id)); + let color = if selected { theme.accent } else { theme.text }; + let text = painter.layout(comment.text.clone(), FontId::proportional((14.0 * camera.zoom).clamp(6.0, 36.0)), color, comment.size[0] * camera.zoom); + let rect = Rect::from_min_size(camera.to_screen(position), text.size().max(vec2(24.0, 16.0))); + painter.galley(rect.min, text, color); + hits.push((comment.id, rect)); + } + + hits +} + +pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) { + let painter = ui.painter_at(app.graph.view); + let theme = Tokens::get(ui.ctx()); + + for pin in &graph.pins { + let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); + let position = camera.to_screen(position); + painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent); + painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text); + } +} + +pub(crate) fn offset(app: &MaterialCraftApp, contains: impl FnOnce(&materialcraft_engine::FrameContents) -> bool) -> Vec2 { + match &app.graph.drag { + Some(GraphDrag::Frame { delta, resize: false, contents, .. }) if contains(contents) => { + materialcraft_engine::graph_grid::snap_position([delta.x, delta.y], app.ui.prefs.snap_to_grid).into() + } + _ => Vec2::ZERO, + } +} diff --git a/crates/ui-egui/src/graph/annotation_input.rs b/crates/ui-egui/src/graph/annotation_input.rs new file mode 100644 index 00000000..a6bae1ec --- /dev/null +++ b/crates/ui-egui/src/graph/annotation_input.rs @@ -0,0 +1,52 @@ +use super::{GraphCamera, GraphDrag, frame_hit::FrameHit}; +use crate::MaterialCraftApp; +use egui::{Rect, Ui, Vec2}; +use serde_json::json; + +pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, frames: &[FrameHit], comments: &[(u64, Rect)]) { + let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return }; + let pressed = ui.input(|input| input.pointer.primary_pressed()); + let motion = ui.input(|input| input.pointer.delta()) / camera.zoom; + + if pressed && app.graph.view.contains(pointer) && app.graph.drag.is_none() && !app.graph.rects.iter().any(|(_, rect)| rect.contains(pointer)) { + if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(pointer)) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + app.graph.drag = Some(GraphDrag::Comment { id: *id, delta: Vec2::ZERO }); + } else if let Some(hit) = frames.iter().rev().find(|hit| hit.contains(pointer)) { + let contents = app + .session + .graph() + .ok() + .and_then(|graph| graph.frames.iter().find(|frame| frame.id == hit.id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame))) + .unwrap_or_default(); + app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); + app.graph.drag = Some(GraphDrag::Frame { id: hit.id, delta: Vec2::ZERO, resize: hit.grip.contains(pointer), contents }); + } else { + app.run("graph.annotation.select", json!({})); + } + } else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. }) = &mut app.graph.drag { + *delta += motion; + } + + if ui.input(|input| input.pointer.primary_released()) { + match app.graph.drag.take() { + Some(GraphDrag::Frame { id, delta, resize, .. }) if delta.length() > 0.5 => { + if resize { + if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { + let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; + app.run("graph.frame.edit", json!({"id": id, "rect": rect})); + } + } else { + app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); + } + } + Some(GraphDrag::Comment { id, delta }) if delta.length() > 0.5 => { + if let Some(comment) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)) { + let position = [comment.pos[0] + delta.x, comment.pos[1] + delta.y]; + app.run("graph.comment.edit", json!({"id": id, "at": position})); + } + } + _ => {} + } + } +} diff --git a/crates/ui-egui/src/graph_view.rs b/crates/ui-egui/src/graph/canvas.rs similarity index 63% rename from crates/ui-egui/src/graph_view.rs rename to crates/ui-egui/src/graph/canvas.rs index d72724df..6efaf7a5 100644 --- a/crates/ui-egui/src/graph_view.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -1,17 +1,8 @@ -//! The graph editor: a pannable, zoomable canvas of node cards (colored header, live thumbnail, -//! size label), bezier wires between typed ports, frames, comments and navigation pins. -//! -//! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire -//! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route -//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to -//! zoom, click a node to show it in the 2D view (double-click a graph instance to open its graph), -//! Space, Tab or double-click the canvas for the node search, right-click for menus, drop library -//! items to add them. Click a wire to select it (Shift or Ctrl+click adds more; Delete removes them, X swaps -//! where they come from), drag a wire to pull a reroute dot out of it, double-click a wire to drop -//! a dot there, right-click a wire for its menu. Every edit is an -//! engine command; the gestures only draw previews until they commit. - -use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; +use super::node_card; +use super::node_card::port as port_pos; +use super::node_layout::NodeLayout; +use super::{GraphCamera, GraphDrag, LibraryDrag, NodeSearch, PortHit, WireRef}; +use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; use materialcraft_engine::core::{Node, NodeId, Value}; use materialcraft_engine::nodes::PortKind; @@ -21,133 +12,13 @@ use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::Tokens; -/// Node card metrics in graph units. -pub const NODE_W: f32 = 100.0; -const HEADER_H: f32 = 18.0; -const FOOTER_H: f32 = 14.0; -const PORT_GAP: f32 = 18.0; +pub const NODE_W: f32 = node_card::WIDTH; const PORT_R: f32 = 4.5; -const DOT_R: f32 = 7.0; -/// A library item being dragged onto the canvas. -#[derive(Clone, Debug)] -pub struct LibraryDrag(pub String); - -#[derive(Clone, Debug)] -enum Drag { - Nodes { - delta: Vec2, - }, - Box { - start: Pos2, - }, - Wire { - from: (NodeId, String), - detached: Option<(NodeId, String)>, - }, - /// Pressed on a wire: a click selects it, a drag pulls a reroute dot out of it. - WirePress { - wire: WireRef, - start: Pos2, - }, - Pan, - Frame { - id: u64, - delta: Vec2, - resize: bool, - nodes: Vec<NodeId>, - }, - Comment { - id: u64, - delta: Vec2, - }, -} - -/// A wire, named by the input it feeds: (node, input port). -pub type WireRef = (NodeId, String); - -/// Pointer distance (points) within which a wire is hit. +/// Pointer distance (points) within which a wire is hit const WIRE_HIT: f32 = 5.0; -/// The node search popup (Space or Tab). -#[derive(Clone, Debug)] -struct Search { - at: Pos2, - text: String, - sel: usize, - connect: Option<(NodeId, String)>, - focus: bool, -} - -/// One port as drawn this frame. -#[derive(Clone, Debug)] -pub struct PortHit { - pub node: NodeId, - pub output: bool, - pub port: String, - pub label: String, - pub pos: Pos2, - pub kind: PortKind, -} - -pub struct GraphView { - pub(crate) keyboard_was_focused: bool, - drag: Option<Drag>, - search: Option<Search>, - /// Comment being edited: id and text. - editing: Option<(u64, String)>, - /// Node rectangles on screen last frame (for `ui.inspect` and scripted input). - pub rects: Vec<(NodeId, Rect)>, - pub ports: Vec<PortHit>, - /// The canvas rectangle last frame. - pub view: Rect, - /// Graph point of the last right-click (context menu actions add things there). - menu_at: Pos2, - /// The graph the camera last framed. - framed_graph: Option<usize>, - /// The selected wires, in the order they were picked (Delete removes them, X swaps them). - pub selected_wires: Vec<WireRef>, - /// The wire the context menu is for (right-clicked on a wire). - menu_wire: Option<WireRef>, - /// Wires on screen last frame: the wire and its bezier control points. - pub wires: Vec<(WireRef, [Pos2; 4])>, -} - -impl Default for GraphView { - fn default() -> Self { - GraphView { - keyboard_was_focused: false, - drag: None, - search: None, - editing: None, - rects: Vec::new(), - ports: Vec::new(), - view: Rect::NOTHING, - menu_at: Pos2::ZERO, - framed_graph: None, - selected_wires: Vec::new(), - menu_wire: None, - wires: Vec::new(), - } - } -} - -struct Cam { - origin: Pos2, - pan: Vec2, - zoom: f32, -} - -impl Cam { - fn to_screen(&self, p: Pos2) -> Pos2 { - self.origin + (p.to_vec2() - self.pan) * self.zoom - } - fn to_graph(&self, s: Pos2) -> Pos2 { - ((s - self.origin) / self.zoom + self.pan).to_pos2() - } -} - -/// Header strip color of a node by its library category. +/// Header strip color of a node by its library category pub fn header_color(def: &str) -> Color32 { let cat = materialcraft_engine::nodes::find(def).map_or("", |d| d.category); match def { @@ -167,11 +38,12 @@ pub fn port_color(kind: PortKind) -> Color32 { match kind { PortKind::Gray => Color32::from_rgb(0xc8, 0xc8, 0xc8), PortKind::Color => Color32::from_rgb(0xe8, 0xa9, 0x3c), + PortKind::Value => Color32::from_rgb(0x8b, 0xc6, 0x74), PortKind::Any => Color32::from_rgb(0x8c, 0xb4, 0xe0), } } -/// A node's display label. +/// A node's display label pub fn node_label(n: &Node) -> String { if !n.label.is_empty() { return n.label.clone(); @@ -186,28 +58,11 @@ pub fn node_label(n: &Node) -> String { } } -/// Graph-space rectangle of a node card. -pub fn node_rect(n: &Node, n_in: usize, n_out: usize, thumbs: bool) -> Rect { - if n.def == "dot" { - return Rect::from_center_size(pos2(n.pos[0], n.pos[1]), vec2(DOT_R * 2.0, DOT_R * 2.0)); - } - let ports = n_in.max(n_out) as f32 * PORT_GAP + 8.0; - let body = if thumbs { NODE_W.max(ports) } else { ports.max(26.0) }; - Rect::from_min_size(pos2(n.pos[0], n.pos[1]), vec2(NODE_W, HEADER_H + body + FOOTER_H)) +/// Graph-space rectangle of a node card +pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect { + node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot") } -/// Graph-space port positions along a card side. -fn port_pos(r: Rect, i: usize, n: usize, output: bool, dot: bool) -> Pos2 { - if dot { - return pos2(if output { r.right() } else { r.left() }, r.center().y); - } - let top = r.top() + HEADER_H; - let body = r.height() - HEADER_H - FOOTER_H; - let start = top + (body - n as f32 * PORT_GAP) * 0.5 + PORT_GAP * 0.5; - pos2(if output { r.right() } else { r.left() }, start + i as f32 * PORT_GAP) -} - -/// Control points of the wire from output `a` to input `b` (screen space). fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { let dx = ((b.x - a.x).abs() * 0.5).max(30.0); [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b] @@ -217,14 +72,14 @@ fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke)); } -/// The point at `t` (0..1) along a cubic bezier. +/// The point at `t` (0..1) along a cubic bezier fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 { let u = 1.0 - t; let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum()) } -/// Distance from `p` to a cubic bezier (sampled as a polyline). +/// Distance from `p` to a cubic bezier (sampled as a polyline) fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { const N: usize = 32; let mut best = f32::INFINITY; @@ -239,7 +94,7 @@ fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { best } -/// The wire nearest `p` within [`WIRE_HIT`] points. +/// The wire nearest `p` within [`WIRE_HIT`] points fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { wires .iter() @@ -250,8 +105,22 @@ fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { .map(|(w, _)| w) } -/// The graph panel: toolbar row and canvas. +/// The graph panel: toolbar row and canvas pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + if crate::pattern::active(app) { + crate::pattern::show(app, ui); + return; + } + app.pattern_editor = None; + + if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + crate::function::show_graph(app, ui); + return; + } + if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_))) { + app.function_editor = None; + } + toolbar(app, ui); canvas(app, ui); } @@ -289,7 +158,11 @@ fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) { app.run("graph.pin.add", json!({"at": [c.x, c.y]})); } ui.separator(); - // Quick insert of the atomic nodes. + if crate::widgets::icon_button(ui, icon::GRID_FOUR, tr("Snap to grid"), app.ui.prefs.snap_to_grid, 22.0).clicked() { + crate::menus::invoke(app, ui.ctx(), "ui.graph.snapToGrid"); + } + + // Quick insert of the atomic nodes for (ic, def) in [ (icon::IMAGE, "bitmap"), (icon::PALETTE, "uniform"), @@ -329,7 +202,7 @@ fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) { }); } -/// "Parent size: [1024 ▾] × [1024 ▾]". +/// "Parent size: [1024 ▾] × [1024 ▾]" fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { let Ok(g) = app.session.graph() else { return }; let [w, h] = g.size; @@ -343,6 +216,7 @@ fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { }); crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); }; + combo(ui, "parent-h", &mut nh); ui.label("x"); combo(ui, "parent-w", &mut nw); @@ -358,7 +232,7 @@ fn view_center(app: &MaterialCraftApp) -> Pos2 { pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) } -/// Add `def` right of the last selected node (wired from it when it fits), else mid-view. +/// Add `def` right of the last selected node (wired from it when it fits), else mid-view pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { let sel = app.session.selection.last().copied(); let has_inputs = materialcraft_engine::nodes::find(def).is_some_and(|d| !d.inputs.is_empty()); @@ -369,10 +243,11 @@ pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { json!({"def": def, "at": [c.x - NODE_W * 0.5, c.y - 60.0]}) } }; + app.run("graph.node.add", params); } -/// Frame the graph (or the selection) in the view. +/// Frame the graph (or the selection) in the view fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { let thumbs = app.ui.prefs.thumbnails; let Ok(g) = app.session.graph() else { return }; @@ -381,12 +256,14 @@ fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { if only_selection && !app.session.selection.contains(&n.id) { continue; } - let (i, o) = materialcraft_engine::eval::ports(&app.session.pkg, n); - r = r.union(node_rect(n, i.len(), o.len(), thumbs)); + + let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); + let visible = super::input_visibility::count(inputs.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); + r = r.union(node_rect(n, visible, outputs.len(), thumbs)); } for f in &g.frames { if !only_selection { - r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2], f.rect[3]))); + r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1] - 32.0), vec2(f.rect[2], f.rect[3] + 32.0))); } } if !r.is_finite() || r.width() <= 0.0 { @@ -412,15 +289,15 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { frame(app, rect, false); } let painter = ui.painter_at(rect); - // Background and grid. + // Background and grid painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31)); - let cam = Cam { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; + let cam = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; grid(&painter, &cam, rect); let pointer = ctx.input(|i| i.pointer.hover_pos()); let hovered_canvas = pointer.is_some_and(|p| rect.contains(p)) && resp.hovered(); - // Zoom around the pointer. + // Zoom around the pointer if hovered_canvas || ui.rect_contains_pointer(rect) { let scroll = ctx.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0); if scroll.abs() > 0.0 @@ -433,43 +310,33 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; } } - let cam = Cam { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; + let cam = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; let thumbs_on = app.ui.prefs.thumbnails; let Ok(g) = app.session.graph() else { return }; let g = g.clone(); let selection = app.session.selection.clone(); let node_delta = match &app.graph.drag { - Some(Drag::Nodes { delta }) => *delta, + Some(GraphDrag::Nodes { delta }) => *delta, _ => Vec2::ZERO, }; - let frame_move = match &app.graph.drag { - Some(Drag::Frame { id, delta, resize: false, nodes }) => Some((*id, *delta, nodes.clone())), - _ => None, - }; - // Layout every node and its ports. - struct Laid { - id: NodeId, - rect: Rect, - ins: Vec<(String, String, PortKind, Pos2)>, - outs: Vec<(String, String, PortKind, Pos2)>, - } - let mut laid: Vec<Laid> = Vec::with_capacity(g.nodes.len()); + // Layout every node and its ports + + let mut laid: Vec<NodeLayout> = Vec::with_capacity(g.nodes.len()); for n in &g.nodes { - let (ins, outs) = materialcraft_engine::eval::ports(&app.session.pkg, n); + let (mut ins, outs) = materialcraft_engine::eval::ports(&app.session.pkg, &g, n); + let visible = super::input_visibility::count(ins.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); + ins.truncate(visible); let mut r = node_rect(n, ins.len(), outs.len(), thumbs_on); - if selection.contains(&n.id) { - r = r.translate(node_delta); - } - if let Some((_, d, nodes)) = &frame_move - && nodes.contains(&n.id) - { - r = r.translate(*d); + if selection.contains(&n.id) && node_delta.length() > 0.5 { + let position = materialcraft_engine::graph_grid::snap_position([n.pos[0] + node_delta.x, n.pos[1] + node_delta.y], app.ui.prefs.snap_to_grid); + r = r.translate(vec2(position[0] - n.pos[0], position[1] - n.pos[1])); } + r = r.translate(super::annotation_canvas::offset(app, |contents| contents.nodes.contains(&n.id))); let dot = n.def == "dot"; let pi = |i: usize, output: bool, total: usize| port_pos(r, i, total, output, dot); - laid.push(Laid { + laid.push(NodeLayout { id: n.id, rect: r, ins: ins.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, false, ins.len()))).collect(), @@ -504,39 +371,16 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { }) .collect(); - // Frames (behind everything). - let mut frame_hits: Vec<(u64, Rect, Rect)> = Vec::new(); - for f in &g.frames { - let mut r = Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2], f.rect[3])); - match &app.graph.drag { - Some(Drag::Frame { id, delta, resize: false, .. }) if *id == f.id => r = r.translate(*delta), - Some(Drag::Frame { id, delta, resize: true, .. }) if *id == f.id => r.max += *delta, - _ => {} - } - let sr = Rect::from_min_max(cam.to_screen(r.min), cam.to_screen(r.max)); - let c = f.color; - let fill = Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, (c[3].clamp(0.05, 0.9) * 255.0) as u8); - painter.rect_filled(sr, 4.0, fill); - let title = Rect::from_min_size(sr.min, vec2(sr.width(), (20.0 * cam.zoom).max(12.0))); - painter.rect_filled(title, CornerRadius { nw: 4, ne: 4, sw: 0, se: 0 }, fill.gamma_multiply(1.6)); - painter.text( - title.left_center() + vec2(6.0, 0.0), - Align2::LEFT_CENTER, - &f.title, - FontId::proportional((12.0 * cam.zoom).clamp(8.0, 18.0)), - tk.text_strong, - ); - let grip = Rect::from_min_size(sr.max - vec2(12.0, 12.0), vec2(12.0, 12.0)); - painter.line_segment([grip.left_bottom(), grip.right_top()], Stroke::new(1.0, tk.text_dim)); - frame_hits.push((f.id, title, grip)); - } + let frame_hits = super::annotation_canvas::frames(app, ui, &g, &cam); + app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect(); - // Wires. + // Wires let cooked = &app.session.cooked; let detached = match &app.graph.drag { - Some(Drag::Wire { detached: Some(d), .. }) => Some(d.clone()), + Some(GraphDrag::Wire { detached: Some(d), .. }) => Some(d.clone()), _ => None, }; + let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(g.connections.len()); for c in &g.connections { if detached.as_ref().is_some_and(|(n, p)| *n == c.to && *p == c.to_port) { @@ -548,13 +392,14 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { wires.push(((c.to, c.to_port.clone()), bezier_points(cam.to_screen(a.3), cam.to_screen(b.3)))); } } - // Hover: not where a node card or a port sits on top of the wire. + // Hover: not where a node card or a port sits on top of the wire let over_card = |p: Pos2| app.graph.rects.iter().any(|(_, r)| r.contains(p)) || nearest_port(&app.graph.ports, p, 9.0).is_some(); let wire_hover = match &app.graph.drag { None => pointer.filter(|p| rect.contains(*p) && !over_card(*p)).and_then(|p| wire_at(&wires, p)).cloned(), - Some(Drag::WirePress { wire, .. }) => Some(wire.clone()), + Some(GraphDrag::WirePress { wire, .. }) => Some(wire.clone()), Some(_) => None, }; + for (w, ctrl) in &wires { let Some(c) = g.input_of(w.0, &w.1) else { continue }; let hot = selection.contains(&c.from) || selection.contains(&c.to); @@ -568,11 +413,12 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { } else { Stroke::new(base, if hot { tk.accent } else { Color32::from_gray(0xb4) }) }; + painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke)); } app.graph.wires = wires; - // Nodes. + // Nodes let font = FontId::proportional((10.5 * cam.zoom).clamp(6.0, 16.0)); let small = FontId::proportional((9.0 * cam.zoom).clamp(5.5, 13.0)); let mut node_resps: Vec<(NodeId, egui::Response)> = Vec::new(); @@ -588,35 +434,34 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let resp = ui.interact(sr, ui.scope_id().with(("node", n.id.0)), Sense::click_and_drag()); crate::widgets::name(&resp, egui::Role::Button, &node_label(n)); if n.def == "dot" { - painter.circle( - sr.center(), - DOT_R * cam.zoom, - Color32::from_gray(0x50), - Stroke::new(1.5, if selected { tk.accent } else { Color32::from_gray(0xb4) }), - ); + node_card::paint_dot(&painter, sr, if selected { tk.accent } else { Color32::from_gray(0xb4) }); } else { - let header = Rect::from_min_size(sr.min, vec2(sr.width(), HEADER_H * cam.zoom)); - let r = (5.0 * cam.zoom).clamp(1.0, 6.0) as u8; - painter.rect_filled(sr, r, Color32::from_rgb(0x1e, 0x20, 0x24)); - painter.rect_filled(header, CornerRadius { nw: r, ne: r, sw: 0, se: 0 }, header_color(&n.def)); - let title = crate::widgets::elided(&painter, node_label(n), font.size, Color32::WHITE, header.width() - 8.0); - painter.galley(header.left_center() + vec2(4.0, -title.size().y * 0.5), title, Color32::WHITE); - // Thumbnail or compact body. - let body = Rect::from_min_max(pos2(sr.left(), header.bottom()), pos2(sr.right(), sr.bottom() - FOOTER_H * cam.zoom)); + node_card::paint(&painter, sr, cam.zoom, &node_label(n), header_color(&n.def)); + let header = node_card::header(sr, cam.zoom); + let body = node_card::body(sr, cam.zoom); if let Some(r0) = result - && let Some(img) = r0.outputs.first() + && let Some(img) = r0.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image) && thumbs_on + && !app.graph.thumbnails_cleared { let side = body.width().min(body.height()) - 6.0 * cam.zoom; let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); 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 n.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) { + let text = match value { + materialcraft_engine::core::Value::Float(value) => value.to_string(), + _ => serde_json::to_value(value).ok().and_then(|value| value.get("v").map(ToString::to_string)).unwrap_or_default(), + }; + + let text = crate::widgets::elided(&painter, text, font.size, tk.text, body.width() - 8.0); + painter.galley(body.center() - text.size() * 0.5, text, tk.text); } else if result.is_none() { painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), tk.text_dim); } - // Footer: size and format. + // Footer: size and format let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max); - if let Some(img) = result.and_then(|r| r.outputs.first()) { + if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }; let txt = format!("{}x{} - {}{}", img.w, img.h, if img.is_gray() { "L" } else { "C" }, bits); painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim); @@ -633,7 +478,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { } else { Stroke::new(1.0, Color32::from_gray(0x10)) }; - painter.rect_stroke(sr, r, outline, StrokeKind::Outside); + + node_card::outline(&painter, sr, cam.zoom, outline); if n.disabled { painter.line_segment([sr.left_top(), sr.right_bottom()], Stroke::new(1.5, tk.danger)); } @@ -644,36 +490,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { node_resps.push((n.id, resp)); } - // Comments. - let mut comment_hits: Vec<(u64, Rect)> = Vec::new(); - for c in &g.comments { - let mut p = pos2(c.pos[0], c.pos[1]); - if let Some(Drag::Comment { id, delta }) = &app.graph.drag - && *id == c.id - { - p += *delta; - } - let r = Rect::from_min_size(cam.to_screen(p), vec2(c.size[0], c.size[1]) * cam.zoom); - painter.rect_filled(r, 4.0, Color32::from_rgba_unmultiplied(0x5a, 0x54, 0x2e, 230)); - painter.rect_stroke(r, 4.0, Stroke::new(1.0, Color32::from_rgb(0x9a, 0x8c, 0x40)), StrokeKind::Inside); - if app.graph.editing.as_ref().is_some_and(|(id, _)| *id == c.id) { - comment_hits.push((c.id, r)); - continue; - } - let galley = - painter.layout(c.text.clone(), FontId::proportional((11.0 * cam.zoom).clamp(6.0, 18.0)), Color32::from_rgb(0xf3, 0xec, 0xc8), r.width() - 10.0); - painter.galley(r.min + vec2(5.0, 4.0), galley, Color32::WHITE); - comment_hits.push((c.id, r)); - } + let comment_hits = super::annotation_canvas::comments(app, ui, &g, &cam); + app.graph.comments = comment_hits.clone(); + super::annotation_canvas::pins(app, ui, &g, &cam); - // Pins. - for pin in &g.pins { - let p = cam.to_screen(pos2(pin.pos[0], pin.pos[1])); - painter.text(p, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), tk.accent); - painter.text(p + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), tk.text); - } - - // Ports (drawn last, interactable over the node cards). + // Ports (drawn last, interactable over the node cards) let port_hover = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 9.0)).cloned(); for h in &app.graph.ports { if !rect.contains(h.pos) { @@ -683,43 +504,35 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let r = (PORT_R * cam.zoom).clamp(2.5, 7.0) * if hot { 1.4 } else { 1.0 }; painter.circle(h.pos, r, port_color(h.kind), Stroke::new(1.0, Color32::from_gray(0x18))); } - if let Some(h) = &port_hover { - let anchor = if h.output { Align2::LEFT_CENTER } else { Align2::RIGHT_CENTER }; - let off = if h.output { vec2(10.0, 0.0) } else { vec2(-10.0, 0.0) }; - let g_ = painter.layout_no_wrap(h.label.clone(), FontId::proportional(11.0), tk.text_strong); - let bg = anchor.anchor_size(h.pos + off, g_.size()).expand(3.0); - painter.rect_filled(bg, 3.0, Color32::from_black_alpha(200)); - painter.galley(bg.min + vec2(3.0, 3.0), g_, tk.text_strong); + let hovered_node = app.graph.rects.iter().rev().find(|(_, bounds)| super::port_label::visible(ui, *bounds)).map(|(id, _)| *id); + for port in &app.graph.ports { + if Some(port.node) != hovered_node || !rect.contains(port.pos) { + continue; + } + + let anchor = if port.output { Align2::LEFT_CENTER } else { Align2::RIGHT_CENTER }; + let offset = if port.output { vec2(10.0, 0.0) } else { vec2(-10.0, 0.0) }; + super::port_label::paint(&painter, port.pos + offset, anchor, &port.label, cam.zoom, tk.text_strong); } - // A wire under a comment is not hit. + // 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); } - handle_input( - app, - ui, - &resp, - rect, - &cam, - &node_resps, - &frame_hits, - &comment_hits, - port_hover, - wire_hover, - &laid.iter().map(|l| (l.id, l.rect)).collect::<Vec<_>>(), - ); + app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); + handle_input(app, ui, &resp, rect, &cam, &node_resps, &frame_hits, &comment_hits, port_hover, wire_hover); + app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); - // Drag previews. + // GraphDrag previews match &app.graph.drag { - Some(Drag::Box { start }) => { + Some(GraphDrag::Box { start }) => { if let Some(p) = pointer { let r = Rect::from_two_pos(*start, p); painter.rect(r, 0.0, tk.accent.gamma_multiply(0.12), Stroke::new(1.0, tk.accent), StrokeKind::Inside); } } - Some(Drag::Wire { from, .. }) => { + Some(GraphDrag::Wire { from, .. }) => { if let (Some(p), Some(src)) = (pointer, app.graph.ports.iter().find(|h| h.output && h.node == from.0 && h.port == from.1)) { bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent)); } @@ -728,7 +541,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { } search_popup(app, ui, &cam); - comment_editor(app, ui); let (failed, placeholders) = app.session.cook_failures(); let mut at = rect.right_bottom() - vec2(8.0, 8.0); if !failed.is_empty() { @@ -742,8 +554,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { } } -fn grid(p: &egui::Painter, cam: &Cam, rect: Rect) { - for (step, alpha) in [(32.0f32, 10u8), (256.0, 22)] { +pub(crate) fn grid(p: &egui::Painter, cam: &GraphCamera, rect: Rect) { + for (step, alpha) in [(materialcraft_engine::graph_grid::GRID_SPACING, 10u8), (256.0, 22)] { let s = step * cam.zoom; if s < 8.0 { continue; @@ -776,13 +588,12 @@ fn handle_input( ui: &mut Ui, canvas: &egui::Response, rect: Rect, - cam: &Cam, + cam: &GraphCamera, nodes: &[(NodeId, egui::Response)], - frames: &[(u64, Rect, Rect)], + frames: &[super::frame_hit::FrameHit], comments: &[(u64, Rect)], port_hover: Option<PortHit>, wire_hover: Option<WireRef>, - graph_rects: &[(NodeId, Rect)], ) { let ctx = ui.ctx().clone(); let (pointer, mods, primary_pressed, primary_down, middle_down, released) = ctx.input(|i| { @@ -791,71 +602,66 @@ fn handle_input( let zoom = cam.zoom; let motion = ctx.input(|i| i.pointer.delta()) / zoom; - // Starting gestures (only on a press inside the canvas, with no gesture running). + // Starting gestures (only on a press inside the canvas, with no gesture running) if app.graph.drag.is_none() && let Some(p) = pointer && rect.contains(p) && app.graph.search.is_none() { if middle_down || (primary_pressed && mods.alt) { - app.graph.drag = Some(Drag::Pan); + app.graph.drag = Some(GraphDrag::Pan); } else if primary_pressed { + if app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", json!({})); + } + let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); - // Any press other than on a wire drops the wire selection. + // Any press other than on a wire drops the wire selection if wire.is_none() { app.graph.selected_wires.clear(); } if let Some(w) = wire { - app.graph.drag = Some(Drag::WirePress { wire: w.clone(), start: p }); + app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); } else if let Some(h) = &port_hover { if h.output { - app.graph.drag = Some(Drag::Wire { from: (h.node, h.port.clone()), detached: None }); + app.graph.drag = Some(GraphDrag::Wire { from: (h.node, h.port.clone()), detached: None }); } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { - app.graph.drag = Some(Drag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); + app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); } - } else if let Some((id, title, grip)) = frames.iter().find(|(_, t, g)| t.contains(p) || g.contains(p)) { - let resize = grip.contains(p) && !title.contains(p); - // Moving a frame carries the nodes inside it. - let inside: Vec<NodeId> = app + } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + app.graph.drag = Some(GraphDrag::Comment { id: *id, delta: Vec2::ZERO }); + } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { + super::node_selection::select(&mut app.session.selection, Some(*id), mods); + app.graph.drag = Some(GraphDrag::Nodes { delta: Vec2::ZERO }); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + let resize = hit.grip.contains(p); + let contents = app .session .graph() .ok() - .and_then(|g| g.frames.iter().find(|f| f.id == *id)) - .map(|f| { - let fr = Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2], f.rect[3])); - graph_rects.iter().filter(|(_, r)| fr.contains_rect(*r)).map(|(n, _)| *n).collect() + .and_then(|graph| { + graph.frames.iter().find(|frame| frame.id == hit.id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame)) }) .unwrap_or_default(); - app.graph.drag = Some(Drag::Frame { id: *id, delta: Vec2::ZERO, resize, nodes: if resize { Vec::new() } else { inside } }); - } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { - app.graph.drag = Some(Drag::Comment { id: *id, delta: Vec2::ZERO }); - } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { - if !app.session.selection.contains(id) { - if mods.ctrl || mods.shift { - app.session.selection.push(*id); - } else { - app.session.selection = vec![*id]; - } - } else if mods.ctrl { - app.session.selection.retain(|s| s != id); - } - app.graph.drag = Some(Drag::Nodes { delta: Vec2::ZERO }); + app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); + app.graph.drag = Some(GraphDrag::Frame { id: hit.id, delta: Vec2::ZERO, resize, contents }); } else { - app.graph.drag = Some(Drag::Box { start: p }); + app.graph.drag = Some(GraphDrag::Box { start: p }); } } } - // Continuing gestures. + // Continuing gestures match &mut app.graph.drag { - Some(Drag::Pan) => { + Some(GraphDrag::Pan) => { let d = ctx.input(|i| i.pointer.delta()) / zoom; app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; } - Some(Drag::Nodes { delta }) | Some(Drag::Frame { delta, .. }) | Some(Drag::Comment { delta, .. }) => *delta += motion, - Some(Drag::WirePress { wire, start }) => { - // Dragged far enough: a reroute dot where the press was, carried by the pointer. + Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, + Some(GraphDrag::WirePress { wire, start }) => { + // Dragged far enough: a reroute dot where the press was, carried by the pointer if let Some(p) = pointer && p.distance(*start) > 4.0 { @@ -863,23 +669,23 @@ fn handle_input( let at = cam.to_graph(start); app.graph.drag = None; if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { - app.graph.drag = Some(Drag::Nodes { delta: (p - start) / zoom }); + app.graph.drag = Some(GraphDrag::Nodes { delta: (p - start) / zoom }); } } } _ => {} } - // Ending gestures. + // Ending gestures let ended = released && !primary_down && !middle_down; if ended && let Some(drag) = app.graph.drag.take() { match drag { - Drag::Pan => {} - Drag::WirePress { wire, .. } => { + GraphDrag::Pan => {} + GraphDrag::WirePress { wire, .. } => { app.session.selection.clear(); let sel = &mut app.graph.selected_wires; if mods.ctrl && sel.contains(&wire) { - // Ctrl+click toggles a wire out of the selection. + // Ctrl+click toggles a wire out of the selection sel.retain(|w| *w != wire); } else if mods.ctrl || mods.shift { if !sel.contains(&wire) { @@ -889,12 +695,12 @@ fn handle_input( *sel = vec![wire]; } } - Drag::Nodes { delta } => { + GraphDrag::Nodes { delta } => { if delta.length() > 0.5 { app.run("graph.node.move", json!({"by": [delta.x, delta.y]})); } } - Drag::Box { start } => { + GraphDrag::Box { start } => { if let Some(p) = pointer { let r = Rect::from_two_pos(start, p); if r.width() > 3.0 || r.height() > 3.0 { @@ -908,21 +714,21 @@ fn handle_input( } else { app.session.selection = hit; } - } else if !mods.ctrl && !mods.shift { - app.session.selection.clear(); + } else { + super::node_selection::select(&mut app.session.selection, None, mods); } } } - Drag::Wire { from, detached } => { + GraphDrag::Wire { from, detached } => { let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); match target { Some(t) => { - if let Some((n, p)) = &detached - && (*n != t.node || *p != t.port) - { - app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); + let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); + if let Some((node, port)) = detached { + parameters["detach"] = json!({"to": node.0, "toPort": port}); } - app.run("graph.connect", json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port})); + + app.run("graph.connect", parameters); } None => { if let Some((n, p)) = &detached { @@ -935,22 +741,19 @@ fn handle_input( } } } - Drag::Frame { id, delta, resize, nodes } => { - if delta.length() > 0.5 - && let Some(f) = app.session.graph().ok().and_then(|g| g.frames.iter().find(|f| f.id == id)).cloned() - { - let r = if resize { - [f.rect[0], f.rect[1], f.rect[2] + delta.x, f.rect[3] + delta.y] + GraphDrag::Frame { id, delta, resize, .. } => { + if delta.length() > 0.5 { + if resize { + if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { + let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; + app.run("graph.frame.edit", json!({"id": id, "rect": rect})); + } } else { - [f.rect[0] + delta.x, f.rect[1] + delta.y, f.rect[2], f.rect[3]] - }; - app.run("graph.frame.edit", json!({"id": id, "rect": r})); - if !nodes.is_empty() { - app.run("graph.node.move", json!({"ids": nodes.iter().map(|n| n.0).collect::<Vec<_>>(), "by": [delta.x, delta.y]})); + app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); } } } - Drag::Comment { id, delta } => { + GraphDrag::Comment { id, delta } => { if delta.length() > 0.5 && let Some(c) = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == id)).cloned() { @@ -960,7 +763,7 @@ fn handle_input( } } - // Clicks. + // Clicks for (id, r) in nodes { if r.double_clicked() { let def = app.session.graph().ok().and_then(|g| g.node(*id).ok()).map(|n| (n.def.clone(), n.params.get("graph").cloned())); @@ -970,18 +773,24 @@ fn handle_input( } Some((d, _)) if d == "pixel_processor" || d == "value_processor" => { app.run("view.2d", json!({"node": id.0, "port": 0})); - app.fn_editor = Some(crate::function_editor::FnEditor::new(*id, "function")); + app.function_editor = Some(crate::function::FunctionEditor::new(*id, crate::function::FunctionTarget::Parameter("function".into()))); } _ => { app.run("view.2d", json!({"node": id.0, "port": 0})); } } } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { - // A click that leaves the node selected shows it, replacing a node shown earlier (a - // Ctrl+click that deselects it does not; the shown node keeps its chosen port). + // Keep the current output when deselecting or clicking the node already shown app.run("view.2d", json!({"node": id.0})); } - r.context_menu(|ui| node_menu(app, ui, *id)); + if r.secondary_clicked() + && let Some(pointer) = pointer + { + app.graph.menu_at = cam.to_graph(pointer); + } + + let at = app.graph.menu_at; + r.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); } if let Some(h) = &port_hover && h.output @@ -990,19 +799,15 @@ fn handle_input( let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); app.run("view.2d", json!({"node": h.node.0, "port": idx})); } - for (id, r) in comments { - if canvas.double_clicked() && pointer.is_some_and(|p| r.contains(p)) { - let text = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == *id)).map(|c| c.text.clone()).unwrap_or_default(); - app.graph.editing = Some((*id, text)); - } - } - let on_node = pointer.is_some_and(|p| nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p))); + let on_node = pointer.is_some_and(|p| { + nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)) || frames.iter().any(|frame| frame.contains(p)) + }); if canvas.double_clicked() && !on_node && let Some(p) = pointer { match &wire_hover { - // Double-click a wire: a reroute dot there. + // Double-click a wire: a reroute dot there Some(w) => { let at = cam.to_graph(p); app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); @@ -1015,8 +820,13 @@ fn handle_input( && let Some(p) = pointer { app.graph.menu_at = cam.to_graph(p); + if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); + } app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); - // Right-clicking a selected wire keeps the selection (to swap or delete them all). + // Right-clicking a selected wire keeps the selection (to swap or delete them all) if let Some(w) = &app.graph.menu_wire && !app.graph.selected_wires.contains(w) { @@ -1027,10 +837,10 @@ fn handle_input( let at = app.graph.menu_at; canvas.context_menu(|ui| match app.graph.menu_wire.clone() { Some(w) => wire_menu(app, ui, w, at), - None => canvas_menu(app, ui, at), + None => super::context_menu::show(app, ui, at, None), }); - // Library drops. + // Library drops if let Some(payload) = canvas.dnd_release_payload::<LibraryDrag>() && let Some(p) = pointer { @@ -1042,7 +852,7 @@ fn handle_input( }; } - // Keys over the canvas. + // Keys over the canvas let hovered = pointer.is_some_and(|p| rect.contains(p)); if hovered && app.graph.search.is_none() { let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); @@ -1060,11 +870,11 @@ fn handle_input( } fn open_search(app: &mut MaterialCraftApp, at: Pos2, connect: Option<(NodeId, String)>) { - app.graph.search = Some(Search { at, text: String::new(), sel: 0, connect, focus: true }); + app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, focus: true }); } -/// Catalog entries matching `text` (label or id contains every word). -fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDef> { +/// Catalog entries matching `text` (label or id contains every word) +fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDefinition> { let words: Vec<String> = text.split_whitespace().map(str::to_ascii_lowercase).collect(); let mut v: Vec<_> = materialcraft_engine::nodes::catalog() .iter() @@ -1080,7 +890,7 @@ fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDef> { v } -fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) { +fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { let Some(s) = app.graph.search.as_mut() else { return }; let tk = Tokens::get(ui.ctx()); let screen = cam.to_screen(s.at); @@ -1152,60 +962,12 @@ fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) { } } -fn comment_editor(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Some((id, text)) = app.graph.editing.as_mut() else { return }; - let Some(r) = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == *id)).map(|c| (c.pos, c.size)) else { - app.graph.editing = None; - return; - }; - let cam = &app.ui.graph_camera; - let origin = app.graph.view.min; - let at = origin + (Vec2::from(r.0) - Vec2::from(cam.pan)) * cam.zoom; - let mut done = false; - egui::Area::new(egui::Id::unique("comment-edit")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - let resp = ui.add(egui::TextEdit::multiline(text).desired_width(r.1[0] * cam.zoom).desired_rows(3)); - resp.request_focus(); - done = resp.lost_focus() || ui.input(|i| i.key_pressed(egui::Key::Escape)); - }); - if done && let Some((id, text)) = app.graph.editing.take() { - app.run("graph.comment.edit", json!({"id": id, "text": text})); - } -} - -fn node_menu(app: &mut MaterialCraftApp, ui: &mut Ui, id: NodeId) { - if !app.session.selection.contains(&id) { - app.session.selection = vec![id]; - } - let mut item = |ui: &mut Ui, label: &str, cmd: &str, params: serde_json::Value| { - if ui.button(tr(label)).clicked() { - app.run(cmd, params); - ui.close(); - } - }; - item(ui, "View in 2D view", "view.2d", json!({"node": id.0})); - ui.separator(); - item(ui, "Copy selection", "edit.copy", json!({})); - item(ui, "Duplicate selection", "edit.duplicate", json!({})); - item(ui, "Duplicate selection without link", "edit.duplicate", json!({"withoutLinks": true})); - item(ui, "Delete selection", "edit.delete", json!({})); - item(ui, "Delete and relink", "edit.deleteRelink", json!({})); - ui.separator(); - item(ui, "Select upstream nodes", "graph.selectUpstream", json!({})); - item(ui, "Select downstream nodes", "graph.selectDownstream", json!({})); - item(ui, "Disable selection", "graph.node.disable", json!({})); - item(ui, "Reset parameters", "graph.node.reset", json!({"id": id.0})); - ui.separator(); - item(ui, "Add frame around selection", "graph.frame.add", json!({})); - item(ui, "Create graph from selection", "graph.createFromSelection", json!({})); -} - -/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands. +/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands fn wires_json(wires: &[WireRef]) -> serde_json::Value { json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()}) } -/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none -/// is selected. +/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none is selected pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { let wires = std::mem::take(&mut app.graph.selected_wires); if wires.is_empty() { @@ -1215,9 +977,7 @@ pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { true } -/// Swap where the selected wires come from (the X key): two wires trade sources, more reverse -/// them in input order. The wires stay selected, so X again swaps back. `false` when no wire is -/// selected. +/// Reverse the sources of selected wires so pressing X again restores them pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { if app.graph.selected_wires.is_empty() { return false; @@ -1248,132 +1008,17 @@ fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: P } } -fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { - ui.menu_button(tr("Add node"), |ui| { - for (cat, ids) in materialcraft_engine::nodes::categories() { - ui.menu_button(cat, |ui| { - egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| { - for id in ids { - let label = materialcraft_engine::nodes::find(id).map_or(id, |d| d.label); - if ui.button(label).clicked() { - app.run("graph.node.add", json!({"def": id, "at": [at.x, at.y]})); - ui.close(); - } - } - }); - }); - } - let others: Vec<String> = app.session.pkg.graphs.iter().enumerate().filter(|(i, _)| *i != app.session.graph).map(|(_, g)| g.name.clone()).collect(); - if !others.is_empty() { - ui.menu_button(tr("Graphs in this package"), |ui| { - for name in others { - if ui.button(&name).clicked() { - app.run("graph.node.add", json!({"def": "graph_instance", "at": [at.x, at.y], "params": {"graph": name}})); - ui.close(); - } - } - }); - } - }); - let mut item = |ui: &mut Ui, label: &str, cmd: &str, params: serde_json::Value| { - if ui.button(tr(label)).clicked() { - app.run(cmd, params); - ui.close(); - } - }; - item(ui, "Add Comment", "graph.comment.add", json!({"at": [at.x, at.y]})); - item(ui, "Add Frame", "graph.frame.add", json!({"rect": [at.x, at.y, 400.0, 260.0]})); - item(ui, "Add Navigation pin", "graph.pin.add", json!({"at": [at.x, at.y]})); - item(ui, "Add Dot node", "graph.node.add", json!({"def": "dot", "at": [at.x, at.y]})); - ui.separator(); - item(ui, "Compute graph", "graph.cook", json!({})); - item(ui, "Paste", "edit.paste", json!({"at": [at.x, at.y]})); - item(ui, "Select all", "edit.selectAll", json!({})); - ui.separator(); - let pins: Vec<(String, [f32; 2])> = app.session.graph().map(|g| g.pins.iter().map(|p| (p.name.clone(), p.pos)).collect()).unwrap_or_default(); - if !pins.is_empty() { - ui.menu_button(tr("Go to pin"), |ui| { - for (name, pos) in pins { - if ui.button(&name).clicked() { - let v = app.graph.view; - let z = app.ui.graph_camera.zoom; - app.ui.graph_camera.pan = [pos[0] - v.width() * 0.5 / z, pos[1] - v.height() * 0.5 / z]; - ui.close(); - } - } - }); - } - if ui.button(tr("Frame all")).clicked() { - app.ui.frame_all = true; - ui.close(); - } -} - #[cfg(test)] mod tests { use super::*; - /// The whole app in an offscreen egui context, driven one frame at a time. - struct Frames { - ctx: egui::Context, - app: MaterialCraftApp, - time: f64, - } + use super::super::frames::Frames; - impl Frames { - /// `session` after a few frames, so the canvas is laid out. - fn new(session: materialcraft_engine::Session) -> Frames { - let mut f = Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0 }; - for _ in 0..3 { - f.run(Vec::new(), egui::Modifiers::NONE); - } - f - } - - /// One frame with `events` while `modifiers` are held, in a desktop-sized window (egui's - /// default screen is so large that the 3D view's frame would exceed the texture limit). - fn run(&mut self, events: Vec<egui::Event>, modifiers: egui::Modifiers) { - self.time += 0.05; - let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); - let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))); - let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() }; - let app = &mut self.app; - self.ctx - .run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - } - - /// Press and release the primary button at `pos`, a second after any earlier click so - /// the two never pair into a double-click. - fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) { - self.time += 1.0; - self.run(vec![egui::Event::PointerMoved(pos)], modifiers); - for pressed in [true, false] { - self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers); - } - } - - /// The center of node `id` on screen last frame. - fn center(&self, id: NodeId) -> Pos2 { - self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen")) - } - - /// The node the 2D view shows once the graph has cooked. - fn shown(&mut self) -> Option<NodeId> { - self.app.session.cook(); - self.app.session.view2d_image().map(|(id, _)| id) - } - } - - /// A graph with a Perlin noise, a checker and an RGBA split side by side, framed on screen. + /// Three primitive nodes framed on screen fn three_nodes() -> (Frames, [NodeId; 3]) { let mut s = materialcraft_engine::sample_session(); materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); - let ids = ["perlin_noise", "checker", "rgba_split"].iter().enumerate().map(|(i, def)| { + let ids = ["uniform", "uniform", "channels_shuffle"].iter().enumerate().map(|(i, def)| { let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); NodeId(added["id"].as_u64().unwrap()) }); @@ -1385,7 +1030,7 @@ mod tests { #[test] fn clicking_a_node_shows_it_in_the_2d_view() { let (mut f, [noise, checker, _]) = three_nodes(); - // Shown explicitly first (a double-click, an output port or "View in 2D view"). + // Shown explicitly first (a double-click, an output port or "View in 2D view") f.app.run("view.2d", json!({"node": noise.0})); assert_eq!(f.shown(), Some(noise)); let at = f.center(checker); @@ -1393,12 +1038,12 @@ mod tests { assert_eq!(f.app.session.selection, vec![checker]); assert_eq!(f.app.session.view2d.node, Some(checker)); assert_eq!(f.shown(), Some(checker)); - // And back. + // And back let at = f.center(noise); f.click(at, egui::Modifiers::NONE); assert_eq!(f.app.session.view2d.node, Some(noise)); assert_eq!(f.shown(), Some(noise)); - // Ctrl+click adds a node to the selection and shows it too. + // Ctrl+click adds a node to the selection and shows it too let at = f.center(checker); f.click(at, egui::Modifiers::CTRL); assert_eq!(f.app.session.selection, vec![noise, checker]); @@ -1432,7 +1077,7 @@ mod tests { f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; let moved = 40.0 / f.app.ui.graph_camera.zoom; - assert!((after[0] - before[0] - moved).abs() < 1e-3 && after[1] == before[1], "the checker moved {before:?} -> {after:?}, not {moved} right"); + assert_eq!(after, materialcraft_engine::graph_grid::snap_position([before[0] + moved, before[1]], true)); assert_eq!(f.app.session.selection, vec![checker]); assert_eq!(f.shown(), Some(noise)); } @@ -1461,8 +1106,8 @@ mod tests { let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); app.run("file.new", json!({"template": "empty"})); let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap(); - let a = id(app.run("graph.node.add", json!({"def": "clouds_1", "at": [0, -150]}))); - let b = id(app.run("graph.node.add", json!({"def": "checker", "at": [0, 150]}))); + let a = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, -150]}))); + let b = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, 150]}))); let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); @@ -1477,6 +1122,7 @@ mod tests { .textures_delta .clear(); }; + for _ in 0..3 { frame(&mut app, Vec::new(), egui::Modifiers::NONE); } @@ -1490,6 +1136,7 @@ mod tests { frame(app, vec![button(true)], m); frame(app, vec![button(false)], m); }; + click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE); click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT); assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires); @@ -1497,7 +1144,7 @@ mod tests { let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a)); - // Still selected: X again swaps back. + // Still selected: X again swaps back frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b)); frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE); @@ -1519,6 +1166,7 @@ mod tests { app.graph.keyboard_was_focused = ui.ctx().egui_wants_keyboard_input(); show(&mut app, ui); }; + ctx.run_ui(egui::RawInput::default(), &mut draw).textures_delta.clear(); let pointer = if hovered { pos2(200.0, 200.0) } else { pos2(-10.0, -10.0) }; let input = egui::RawInput { @@ -1528,10 +1176,11 @@ mod tests { ], ..Default::default() }; + ctx.run_ui(input, &mut draw).textures_delta.clear(); assert_eq!(app.graph.search.is_some(), hovered && !editing, "{key:?}: hovered={hovered}, editing={editing}"); if let Some(search) = &app.graph.search { - let cam = Cam { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; + let cam = GraphCamera { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; assert_eq!(search.at, cam.to_graph(pointer)); assert!(search.text.is_empty()); } @@ -1541,7 +1190,7 @@ mod tests { #[test] fn search_finds_by_label_and_category() { - assert!(matches("perlin").iter().any(|d| d.id == "perlin_noise")); + assert!(matches("uniform").iter().any(|d| d.id == "uniform")); assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); assert!(matches("zzzz").is_empty()); @@ -1552,14 +1201,14 @@ mod tests { let a = (NodeId(1), "input".to_string()); let b = (NodeId(2), "input".to_string()); let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))]; - // The midpoint of a symmetric wire lies on the line between its ends. + // The midpoint of a symmetric wire lies on the line between its ends let mid = bezier_at(&wires[0].1, 0.5); assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}"); assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a)); assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b)); assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None); assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None); - // The ends are on the wire. + // The ends are on the wire assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); } @@ -1571,7 +1220,7 @@ mod tests { for i in 0..3 { let p = port_pos(r, i, 3, false, false); assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); - assert!(p.y > r.top() + HEADER_H && p.y < r.bottom() - FOOTER_H); + assert!(p.y > r.top() + node_card::HEADER_HEIGHT && p.y < r.bottom() - node_card::FOOTER_HEIGHT); } } } diff --git a/crates/ui-egui/src/graph/context_menu.rs b/crates/ui-egui/src/graph/context_menu.rs new file mode 100644 index 00000000..ab305ff2 --- /dev/null +++ b/crates/ui-egui/src/graph/context_menu.rs @@ -0,0 +1,118 @@ +use egui::{Pos2, Ui}; +use materialcraft_engine::core::NodeId; +use serde_json::{Value, json}; + +use crate::{MaterialCraftApp, i18n::tr, menus}; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2, node: Option<NodeId>) { + if let Some(node) = node + && app.session.selection.last() != Some(&node) + { + let mut selection = app.session.selection.clone(); + if selection.contains(&node) { + selection.retain(|selected| *selected != node); + } else { + selection.clear(); + } + selection.push(node); + app.run("graph.select", json!({"ids": selection})); + } + + ui.set_min_width(290.0); + if node.is_some() && menus::enabled(app, "graph.node.edit") { + action(app, ui, "Edit graph", "graph.node.edit", Value::Null); + ui.separator(); + } + + ui.menu_button(tr("Add node"), |ui| add_nodes(app, ui, at)); + action(app, ui, "Add Comment", "graph.comment.add", json!({"at": [at.x, at.y]})); + action(app, ui, "Add Frame", "graph.frame.add", json!({"rect": [at.x, at.y, 400.0, 260.0]})); + action(app, ui, "Add Navigation pin", "graph.pin.add", json!({"at": [at.x, at.y]})); + action(app, ui, "Add Dot node", "graph.node.add", json!({"def": "dot", "at": [at.x, at.y]})); + ui.separator(); + + action(app, ui, "View outputs in 3D view", "ui.graph.viewOutputs", Value::Null); + action(app, ui, "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", Value::Null); + outputs(app, ui, node); + action(app, ui, "Compute nodes thumbnails", "ui.graph.computeThumbnails", Value::Null); + action(app, ui, "Clear nodes thumbnails", "ui.graph.clearThumbnails", Value::Null); + action(app, ui, "Save package", "file.save", Value::Null); + action(app, ui, "Paste", "edit.paste", json!({"at": [at.x, at.y]})); + action(app, ui, "Paste without link", "edit.pasteWithoutLinks", json!({"at": [at.x, at.y]})); + action(app, ui, "Select all", "edit.selectAll", Value::Null); + action(app, ui, "Previous pin", "ui.graph.previousPin", Value::Null); + action(app, ui, "Next pin", "ui.graph.nextPin", Value::Null); + ui.separator(); + + for (label, command) in [ + ("Copy selection", "edit.copy"), + ("Delete selection", "edit.delete"), + ("Delete and relink", "edit.deleteRelink"), + ("Duplicate selection", "edit.duplicate"), + ("Duplicate selection without link", "edit.duplicateWithoutLinks"), + ("Select upstream nodes", "graph.selectUpstream"), + ("Select downstream nodes", "graph.selectDownstream"), + ("Disable selection", "graph.node.disable"), + ] { + action(app, ui, label, command, Value::Null); + } +} + +fn add_nodes(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { + let definitions = materialcraft_engine::nodes::catalog().iter().filter(|definition| definition.id != "dot"); + let entries = definitions.map(|definition| (definition.id, definition.label, definition.category)); + if let Some(definition) = super::add_node_menu::show(ui, entries) { + app.run("graph.node.add", json!({"def": definition, "at": [at.x, at.y], "snapToGrid": app.ui.prefs.snap_to_grid})); + } +} + +fn outputs(app: &mut MaterialCraftApp, ui: &mut Ui, node: Option<NodeId>) { + let targets: Vec<_> = app + .session + .graph() + .into_iter() + .flat_map(|graph| graph.nodes.iter().map(move |node| (graph, node))) + .filter(|(_, candidate)| node == Some(candidate.id) || (node.is_none() && candidate.def == "output")) + .flat_map(|(graph, node)| { + if node.def == "output" { + return vec![(node.id, 0, super::node_label(node))]; + } + + materialcraft_engine::eval::ports(&app.session.pkg, graph, node) + .1 + .into_iter() + .enumerate() + .map(move |(index, port)| (node.id, index, format!("{} / {}", super::node_label(node), port.label))) + .collect() + }) + .collect(); + + ui.add_enabled_ui(!targets.is_empty(), |ui| { + ui.menu_button(tr("View output in 2D view"), |ui| { + for (node, port, label) in targets { + if ui.button(label).clicked() { + app.run("view.2d", json!({"node": node.0, "port": port})); + app.ui.dock.focus(crate::docking::Panel::View2d); + ui.close(); + } + } + }); + }); +} + +fn action(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, command: &str, parameters: Value) { + let mut button = egui::Button::new(tr(label)); + if let Some(shortcut) = menus::shortcut_of(command) { + button = button.shortcut_text(shortcut); + } + + if ui.add_enabled(menus::enabled(app, command), button).clicked() { + if command.starts_with("ui.") || matches!(command, "file.save" | "graph.node.edit") { + menus::invoke(app, ui.ctx(), command); + } else { + app.run(command, parameters); + } + + ui.close(); + } +} diff --git a/crates/ui-egui/src/graph/frame_hit.rs b/crates/ui-egui/src/graph/frame_hit.rs new file mode 100644 index 00000000..fee4831c --- /dev/null +++ b/crates/ui-egui/src/graph/frame_hit.rs @@ -0,0 +1,14 @@ +use egui::{Pos2, Rect}; + +pub(crate) struct FrameHit { + pub id: u64, + pub rect: Rect, + pub title: Rect, + pub grip: Rect, +} + +impl FrameHit { + pub fn contains(&self, position: Pos2) -> bool { + self.rect.contains(position) || self.title.contains(position) + } +} diff --git a/crates/ui-egui/src/graph/frames.rs b/crates/ui-egui/src/graph/frames.rs new file mode 100644 index 00000000..7b842b77 --- /dev/null +++ b/crates/ui-egui/src/graph/frames.rs @@ -0,0 +1,64 @@ +use crate::MaterialCraftApp; +use egui::{Pos2, Rect, vec2}; +use materialcraft_engine::core::NodeId; + +/// The whole app in an offscreen egui context, driven one frame at a time +pub(super) struct Frames { + pub(super) ctx: egui::Context, + pub(super) app: MaterialCraftApp, + pub(super) time: f64, + pub(super) canvas_text: Vec<String>, +} + +impl Frames { + /// `session` after a few frames, so the canvas is laid out + pub(super) fn new(session: materialcraft_engine::Session) -> Frames { + let mut f = + Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0, canvas_text: Vec::new() }; + for _ in 0..3 { + f.run(Vec::new(), egui::Modifiers::NONE); + } + f + } + + /// Draw a desktop-sized frame with synthetic input + pub(super) fn run(&mut self, events: Vec<egui::Event>, modifiers: egui::Modifiers) { + self.time += 0.05; + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))); + let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() }; + let app = &mut self.app; + let output = self.ctx.run_ui(input, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }); + self.canvas_text = output + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if self.app.graph.view.contains(text.pos) => Some(text.galley.job.text.clone()), + _ => None, + }) + .collect(); + } + + /// Press and release the primary button at `pos`, a second after any earlier click so the two never pair into a double-click + pub(super) fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) { + self.time += 1.0; + self.run(vec![egui::Event::PointerMoved(pos)], modifiers); + for pressed in [true, false] { + self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers); + } + } + + /// The center of node `id` on screen last frame + pub(super) fn center(&self, id: NodeId) -> Pos2 { + self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen")) + } + + /// The node the 2D view shows once the graph has cooked + pub(super) fn shown(&mut self) -> Option<NodeId> { + self.app.session.cook(); + self.app.session.view2d_image().map(|(id, _)| id) + } +} diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs new file mode 100644 index 00000000..7ce3c3ff --- /dev/null +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -0,0 +1,16 @@ +use egui::{Pos2, Vec2}; + +pub(crate) struct GraphCamera { + pub(crate) origin: Pos2, + pub(crate) pan: Vec2, + pub(crate) zoom: f32, +} + +impl GraphCamera { + pub(crate) fn to_screen(&self, p: Pos2) -> Pos2 { + self.origin + (p.to_vec2() - self.pan) * self.zoom + } + pub(crate) fn to_graph(&self, s: Pos2) -> Pos2 { + ((s - self.origin) / self.zoom + self.pan).to_pos2() + } +} diff --git a/crates/ui-egui/src/graph/graph_drag.rs b/crates/ui-egui/src/graph/graph_drag.rs new file mode 100644 index 00000000..a2db9255 --- /dev/null +++ b/crates/ui-egui/src/graph/graph_drag.rs @@ -0,0 +1,33 @@ +use super::WireRef; +use egui::{Pos2, Vec2}; +use materialcraft_engine::core::NodeId; + +#[derive(Clone, Debug)] +pub(super) enum GraphDrag { + Nodes { + delta: Vec2, + }, + Box { + start: Pos2, + }, + Wire { + from: (NodeId, String), + detached: Option<(NodeId, String)>, + }, + /// Pressed on a wire: a click selects it, a drag pulls a reroute dot out of it + WirePress { + wire: WireRef, + start: Pos2, + }, + Pan, + Frame { + id: u64, + delta: Vec2, + resize: bool, + contents: materialcraft_engine::FrameContents, + }, + Comment { + id: u64, + delta: Vec2, + }, +} diff --git a/crates/ui-egui/src/graph/graph_view.rs b/crates/ui-egui/src/graph/graph_view.rs new file mode 100644 index 00000000..385faa2d --- /dev/null +++ b/crates/ui-egui/src/graph/graph_view.rs @@ -0,0 +1,56 @@ +use super::{GraphDrag, NodeSearch, PortHit, WireRef}; +use egui::{Pos2, Rect}; +use materialcraft_engine::core::NodeId; + +pub struct GraphView { + pub(crate) inspected_node: Option<NodeId>, + pub(crate) keyboard_was_focused: bool, + pub(super) thumbnails_cleared: bool, + pub(super) drag: Option<GraphDrag>, + pub(super) search: Option<NodeSearch>, + /// Node rectangles on screen last frame (for `ui.inspect` and scripted input) + pub rects: Vec<(NodeId, Rect)>, + pub ports: Vec<PortHit>, + pub frames: Vec<(u64, Rect)>, + pub comments: Vec<(u64, Rect)>, + /// The canvas rectangle last frame + pub view: Rect, + /// Graph point of the last right-click (context menu actions add things there) + pub(super) menu_at: Pos2, + /// The graph the camera last framed + pub(super) framed_graph: Option<usize>, + /// The selected wires, in the order they were picked (Delete removes them, X swaps them) + pub selected_wires: Vec<WireRef>, + /// The wire the context menu is for (right-clicked on a wire) + pub(super) menu_wire: Option<WireRef>, + /// Wires on screen last frame: the wire and its bezier control points + pub wires: Vec<(WireRef, [Pos2; 4])>, +} + +impl GraphView { + pub(crate) fn is_dragging(&self) -> bool { + self.drag.is_some() + } +} + +impl Default for GraphView { + fn default() -> Self { + GraphView { + inspected_node: None, + keyboard_was_focused: false, + thumbnails_cleared: false, + drag: None, + search: None, + rects: Vec::new(), + ports: Vec::new(), + frames: Vec::new(), + comments: Vec::new(), + view: Rect::NOTHING, + menu_at: Pos2::ZERO, + framed_graph: None, + selected_wires: Vec::new(), + menu_wire: None, + wires: Vec::new(), + } + } +} diff --git a/crates/ui-egui/src/graph/input_visibility.rs b/crates/ui-egui/src/graph/input_visibility.rs new file mode 100644 index 00000000..d45c1af4 --- /dev/null +++ b/crates/ui-egui/src/graph/input_visibility.rs @@ -0,0 +1,11 @@ +pub(crate) fn count(connections: impl IntoIterator<Item = bool>, minimum: usize) -> usize { + let mut visible = minimum; + let mut total = 0; + for (index, connected) in connections.into_iter().enumerate() { + total = index + 1; + if connected { + visible = index + 2; + } + } + visible.min(total) +} diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs new file mode 100644 index 00000000..f3d93270 --- /dev/null +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -0,0 +1,470 @@ +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use materialcraft_engine::{core::NodeId, new_session}; +use serde_json::json; + +use super::frames::Frames; +use crate::{MaterialCraftApp, UiState, menus}; + +fn drag(frames: &mut Frames, from: Pos2, to: Pos2) { + frames.run(vec![Event::PointerMoved(from)], Modifiers::NONE); + frames.run(vec![Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], Modifiers::NONE); + for step in 1..=8 { + frames.run(vec![Event::PointerMoved(from.lerp(to, step as f32 / 8.0))], Modifiers::NONE); + } + frames.run(vec![Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + frames.run(Vec::new(), Modifiers::NONE); +} + +#[test] +fn output_port_drags_branch_to_two_fresh_processors() { + let mut frames = Frames::new(new_session()); + let mut ids = Vec::new(); + for (definition, position) in [("input_value", [0, 64]), ("value_processor", [320, 0]), ("value_processor", [320, 256])] { + ids.push(NodeId(frames.app.run("graph.node.add", json!({"def": definition, "at": position})).unwrap()["id"].as_u64().unwrap())); + } + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + for target in &ids[1..] { + let source = frames.app.graph.ports.iter().find(|port| port.node == ids[0] && port.output).unwrap().pos; + let destination = frames.app.graph.ports.iter().find(|port| port.node == *target && port.port == "value1").unwrap().pos; + drag(&mut frames, source, destination); + } + let graph = frames.app.session.graph().unwrap(); + assert_eq!(graph.connections.len(), 2); + assert!(graph.connections.iter().all(|wire| wire.from == ids[0])); +} + +#[test] +fn placement_and_dragging_snap_by_default_and_can_be_disabled() { + let mut frames = Frames::new(new_session()); + assert!(frames.app.ui.prefs.snap_to_grid); + let node = NodeId(frames.app.run("graph.node.add", json!({"def": "uniform", "at": [19, -19]})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(frames.app.session.graph().unwrap().node(node).unwrap().pos, [32.0, -32.0]); + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + + for snapping in [true, false] { + let before = frames.app.session.graph().unwrap().node(node).unwrap().pos; + let from = frames.center(node); + let zoom = frames.app.ui.graph_camera.zoom; + drag(&mut frames, from, from + vec2(23.0, 7.0)); + let expected = materialcraft_engine::graph_grid::snap_position([before[0] + 23.0 / zoom, before[1] + 7.0 / zoom], snapping); + let after = frames.app.session.graph().unwrap().node(node).unwrap().pos; + assert!((after[0] - expected[0]).abs() < 0.001 && (after[1] - expected[1]).abs() < 0.001, "{after:?} != {expected:?}"); + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.snapToGrid"); + } +} + +#[test] +fn pin_navigation_wraps_and_thumbnail_commands_keep_the_document() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + app.graph.view = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let context = egui::Context::default(); + for position in [[100, 200], [700, 400]] { + app.run("graph.pin.add", json!({"at": position})); + } + let original = app.session.pkg.clone(); + menus::invoke(&mut app, &context, "ui.graph.nextPin"); + let first = app.ui.graph_camera.pan; + menus::invoke(&mut app, &context, "ui.graph.nextPin"); + assert_ne!(first, app.ui.graph_camera.pan); + menus::invoke(&mut app, &context, "ui.graph.nextPin"); + assert_eq!(first, app.ui.graph_camera.pan); + menus::invoke(&mut app, &context, "ui.graph.previousPin"); + assert_ne!(first, app.ui.graph_camera.pan); + + menus::invoke(&mut app, &context, "ui.graph.clearThumbnails"); + assert!(app.graph.thumbnails_cleared); + menus::invoke(&mut app, &context, "ui.graph.computeThumbnails"); + assert!(!app.graph.thumbnails_cleared); + assert!(app.session.dirty); + assert_eq!(original, app.session.pkg); +} + +#[test] +fn frame_drag_selects_the_border_and_moves_comments_and_nodes_together() { + let mut frames = Frames::new(new_session()); + let node = NodeId(frames.app.run("graph.node.add", json!({"def": "uniform", "at": [64, 64]})).unwrap()["id"].as_u64().unwrap()); + frames.app.run("graph.comment.add", json!({"at": [64, 220], "text": "Follow the frame"})); + let id = + frames.app.run("graph.frame.add", json!({"rect": [0, 0, 400, 320], "description": "Follow the frame description"})).unwrap()["id"].as_u64().unwrap(); + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + assert!(frames.canvas_text.iter().any(|text| text == "Follow the frame description")); + let from = frames.app.graph.frames.iter().find(|(candidate, _)| *candidate == id).unwrap().1.left_bottom() + vec2(12.0, -12.0); + let original = frames.app.session.pkg.clone(); + let zoom = frames.app.ui.graph_camera.zoom; + drag(&mut frames, from, from + vec2(64.0, 32.0) * zoom); + let graph = frames.app.session.graph().unwrap(); + assert_eq!(graph.node(node).unwrap().pos, [128.0, 96.0]); + assert_eq!(graph.comments[0].pos, [128.0, 252.0]); + assert_eq!(frames.app.session.annotation_selection, Some(materialcraft_engine::AnnotationSelection::Frame(id))); + frames.app.session.undo().unwrap(); + assert_eq!(frames.app.session.pkg, original); + + frames.run(Vec::new(), Modifiers::NONE); + let comment = frames.app.graph.comments[0].1.center(); + frames.click(comment, Modifiers::NONE); + assert!(matches!(frames.app.session.annotation_selection, Some(materialcraft_engine::AnnotationSelection::Comment(_)))); + assert_eq!(crate::properties::title(&frames.app), "Comment - Properties"); +} + +#[test] +fn standalone_function_canvas_wires_constants_and_marks_an_output() { + let mut session = new_session(); + materialcraft_engine::execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + let mut function = materialcraft_engine::core::FunctionGraph::default(); + let first = function.add_constant(materialcraft_engine::core::Value::Float(2.0)); + let second = function.add_constant(materialcraft_engine::core::Value::Float(3.0)); + let multiply = function.add("mul", &[], None); + function.nodes[1].pos = [0.0, 128.0]; + function.nodes[2].pos = [256.0, 64.0]; + function.output = Some(multiply); + materialcraft_engine::execute(&mut session, "graph.function.set", &json!({"function": function})).unwrap(); + let mut frames = Frames::new(session); + + for (source, slot) in [(first, "0"), (second, "1")] { + let from = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(source) && port.output).unwrap().pos; + let to = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(multiply) && port.port == slot).unwrap().pos; + drag(&mut frames, from, to); + } + let function = frames.app.session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.node(multiply).unwrap().inputs, vec![Some(first), Some(second)]); + assert_eq!(function.output, Some(multiply)); +} + +#[test] +fn selected_pattern_subgraph_opens_with_control_e() { + let mut frames = Frames::new(new_session()); + let node = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + frames.app.run("graph.select", json!({"ids": [node.0]})); + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let history = frames.app.session.history(); + + let control = Modifiers::CTRL | Modifiers::COMMAND; + frames.run(vec![Event::Key { key: egui::Key::E, physical_key: Some(egui::Key::E), pressed: true, repeat: false, modifiers: control }], control); + frames.run(vec![Event::Key { key: egui::Key::E, physical_key: Some(egui::Key::E), pressed: false, repeat: false, modifiers: control }], control); + assert_eq!(frames.app.pattern_editor.as_ref().map(|editor| editor.node), Some(node)); + assert_eq!(frames.app.session.pkg, original); + assert_eq!(frames.app.session.history(), history); + assert_eq!(frames.app.graph.rects.len(), 1); + assert_eq!(frames.app.graph.ports.len(), 5); + assert!(frames.canvas_text.iter().any(|label| label == "Quadrant")); + + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); + assert!(frames.app.pattern_editor.is_none()); + let response = crate::control::handle(&mut frames.app, &frames.ctx, "ui.menu.invoke", &json!({"id": "graph.node.edit"})); + assert_eq!(response["ok"], true); + assert_eq!(frames.app.pattern_editor.as_ref().map(|editor| editor.node), Some(node)); + + frames.app.pattern_editor = None; + frames.app.run("graph.node.add", json!({"def": "uniform"})); + assert!(!menus::enabled(&frames.app, "graph.node.edit")); + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + assert!(frames.app.pattern_editor.is_none()); +} + +#[test] +fn pattern_canvas_wires_moves_and_deletes_only_embedded_nodes() { + use materialcraft_engine::core::{PatternGraph, PatternNodeKind, Value}; + + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut pattern = PatternGraph::default(); + let root = pattern.add(PatternNodeKind::Quadrant).unwrap(); + let child = pattern.add(PatternNodeKind::Switch).unwrap(); + let leaf = pattern.add(PatternNodeKind::Iterate).unwrap(); + pattern.nodes[0].position = [0.0, 0.0]; + pattern.nodes[1].position = [0.0, 192.0]; + pattern.nodes[2].position = [192.0, 384.0]; + frames.app.run("graph.pattern.set", json!({"id": owner.0, "pattern": pattern})).unwrap(); + let parent_camera = frames.app.ui.graph_camera; + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(frames.app.graph.rects.len(), 3); + assert_eq!(frames.app.graph.ports.len(), 11); + assert!(!menus::enabled(&frames.app, "graph.node.edit")); + + for (source, slot, target) in [(root, "output0", child), (root, "output1", leaf), (child, "output0", leaf)] { + let from = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(source) && port.port == slot).unwrap().pos; + let to = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(target) && !port.output).unwrap().pos; + drag(&mut frames, from, to); + } + let current = |frames: &Frames| { + let Value::PatternGraph(graph) = &frames.app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing pattern") }; + (**graph).clone() + }; + assert_eq!(current(&frames).nodes[0].children, vec![Some(child), Some(leaf), None, None]); + assert_eq!(current(&frames).nodes[1].children, vec![Some(leaf), None]); + let before_cycle = frames.app.session.pkg.clone(); + let history = frames.app.session.history(); + let from = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(leaf) && port.output).unwrap().pos; + let to = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(root) && !port.output).unwrap().pos; + drag(&mut frames, from, to); + assert_eq!(frames.app.session.pkg, before_cycle); + assert_eq!(frames.app.session.history(), history); + assert!(frames.app.status.contains("cycle")); + + let from = frames.center(NodeId(u64::from(child))); + drag(&mut frames, from, from + vec2(35.0, 12.0)); + let moved = current(&frames).nodes[1].position; + assert_ne!(moved, [0.0, 192.0]); + assert!(moved.iter().all(|coordinate| coordinate % 32.0 == 0.0)); + assert_eq!(crate::properties::title(&frames.app), "Switch - Properties"); + frames.app.session.undo().unwrap(); + assert_eq!(frames.app.session.pkg, before_cycle); + + frames.app.graph.selected_wires.push((owner, "parent-wire".into())); + frames.run(vec![Event::Key { key: egui::Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + frames.run(vec![Event::Key { key: egui::Key::Delete, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + assert_eq!(current(&frames).nodes.len(), 2); + assert_eq!(current(&frames).nodes[0].children[0], None); + assert_eq!(frames.app.session.graph().unwrap().nodes.len(), 1); + frames.app.session.undo().unwrap(); + assert_eq!(frames.app.session.pkg, before_cycle); + for command in ["edit.selectAll", "edit.copy", "edit.paste"] { + menus::invoke(&mut frames.app, &frames.ctx, command); + } + let pasted = current(&frames); + assert_eq!(pasted.nodes.len(), 6); + assert_eq!(pasted.nodes[3].children, vec![Some(pasted.nodes[4].id), Some(pasted.nodes[5].id), None, None]); + assert_eq!(pasted.nodes[4].children, vec![Some(pasted.nodes[5].id), None]); + frames.app.session.undo().unwrap(); + assert_eq!(frames.app.session.pkg, before_cycle); + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); + frames.run(Vec::new(), Modifiers::NONE); + assert!(frames.app.pattern_editor.is_none()); + assert_eq!(frames.app.ui.graph_camera, parent_camera); + assert_eq!(frames.app.graph.rects.len(), 1); +} + +#[test] +fn replacing_the_document_closes_the_embedded_graph() { + let mut frames = Frames::new(new_session()); + frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap(); + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + assert!(frames.app.pattern_editor.is_some()); + let response = crate::control::handle(&mut frames.app, &frames.ctx, "command.run", &json!({"id": "file.new", "params": {}})); + assert_eq!(response["ok"], true); + assert!(frames.app.pattern_editor.is_none()); +} + +#[test] +fn pattern_dot_has_vertical_ports_and_can_be_wired_and_moved() { + use materialcraft_engine::core::{PatternGraph, PatternNodeKind, Value}; + + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut pattern = PatternGraph::default(); + let dot = pattern.add(PatternNodeKind::Dot).unwrap(); + let quadrant = pattern.add(PatternNodeKind::Quadrant).unwrap(); + pattern.nodes[0].position = [48.0, 0.0]; + pattern.nodes[1].position = [0.0, 192.0]; + frames.app.run("graph.pattern.set", json!({"id": owner.0, "pattern": pattern})).unwrap(); + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + frames.run(Vec::new(), Modifiers::NONE); + + let input = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(dot) && !port.output).unwrap().pos; + let output = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(dot) && port.output).unwrap().pos; + assert_eq!(input.x, output.x); + assert!(input.y < output.y); + let destination = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(quadrant) && !port.output).unwrap().pos; + drag(&mut frames, output, destination); + let from = frames.center(NodeId(u64::from(dot))); + drag(&mut frames, from, from + vec2(32.0, 16.0)); + let Value::PatternGraph(graph) = &frames.app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing pattern") }; + assert_eq!(graph.nodes[0].children, vec![Some(quadrant)]); + assert_ne!(graph.nodes[0].position, [48.0, 0.0]); + assert_eq!(crate::properties::title(&frames.app), "Dot - Properties"); +} + +#[test] +fn pin_labels_follow_node_hover_while_pins_stay_visible() { + use materialcraft_engine::core::FunctionGraph; + + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + frames.app.ui.frame_all = true; + frames.run(vec![Event::PointerGone], Modifiers::NONE); + let labels = ["Background", "Input image 0", "Output"]; + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + assert_eq!(frames.app.graph.ports.len(), 3); + + let position = frames.center(owner); + frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE); + assert!(labels.iter().all(|label| frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + frames.run(vec![Event::PointerGone], Modifiers::NONE); + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + assert_eq!(frames.app.graph.ports.len(), 3); + + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + frames.run(vec![Event::PointerGone], Modifiers::NONE); + let labels = ["Input", "Top left", "Top right", "Bottom left", "Bottom right"]; + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + assert_eq!(frames.app.graph.ports.len(), 5); + + let position = frames.app.graph.rects[0].1.center(); + frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE); + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + frames.run(vec![Event::PointerGone], Modifiers::NONE); + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + assert_eq!(frames.app.graph.ports.len(), 5); + + frames.app.run("file.new", json!({"kind": "function"})); + let mut function = FunctionGraph::default(); + let multiply = function.add("mul", &[], None); + frames.app.run("graph.function.set", json!({"function": function})); + frames.run(vec![Event::PointerGone], Modifiers::NONE); + let labels = ["A", "Output"]; + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + assert_eq!(frames.app.graph.ports.len(), 2); + + let position = frames.center(NodeId(u64::from(multiply))); + frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE); + assert!(labels.iter().all(|label| frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + frames.run(vec![Event::PointerGone], Modifiers::NONE); + assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); + assert_eq!(frames.app.graph.ports.len(), 2); +} + +#[test] +fn function_dots_wire_move_and_save_with_regular_card_geometry() { + use materialcraft_engine::core::{FunctionGraph, Value}; + use materialcraft_engine::formats::sbs::{read_sbs, write_sbs}; + + let mut frames = Frames::new(new_session()); + frames.app.run("file.new", json!({"kind": "function", "name": "Dot_sample"})); + let mut function = FunctionGraph::default(); + let source = function.add_constant(Value::Float(3.0)); + let dot = function.add("passthrough", &[], None); + let multiply = function.add("mul", &[], None); + function.nodes[1].pos = [224.0, 64.0]; + function.nodes[2].pos = [416.0, 0.0]; + function.output = Some(multiply); + frames.app.run("graph.function.set", json!({"function": function})); + frames.run(Vec::new(), Modifiers::NONE); + let zoom = frames.app.ui.graph_camera.zoom; + let dot_bounds = frames.app.graph.rects.iter().find(|(id, _)| id.0 == u64::from(dot)).unwrap().1; + let card = frames.app.graph.rects.iter().find(|(id, _)| id.0 == u64::from(multiply)).unwrap().1; + assert!((dot_bounds.width() / zoom - 14.0).abs() < 0.01); + assert!((card.width() / zoom - 100.0).abs() < 0.01); + assert!((card.height() / zoom - 132.0).abs() < 0.01); + assert!(!frames.canvas_text.iter().any(|text| text.contains("Reroute"))); + let dot_ports: Vec<_> = frames.app.graph.ports.iter().filter(|port| port.node.0 == u64::from(dot)).collect(); + assert_eq!(dot_ports.len(), 2); + assert!((dot_ports[0].pos.y - dot_ports[1].pos.y).abs() < 0.01); + assert!(dot_ports[0].pos.x < dot_ports[1].pos.x); + assert!(!frames.app.graph.ports.iter().any(|port| port.node.0 == u64::from(multiply) && port.port == "1")); + + for (from, to, input) in [(source, dot, "0"), (dot, multiply, "0"), (dot, multiply, "1")] { + let start = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(from) && port.output).unwrap().pos; + let end = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(to) && port.port == input).unwrap().pos; + drag(&mut frames, start, end); + } + let graph = frames.app.session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(graph.node(dot).unwrap().inputs, vec![Some(source)]); + assert_eq!(graph.node(multiply).unwrap().inputs, vec![Some(dot), Some(dot)]); + let before_move = frames.app.session.pkg.clone(); + let center = frames.center(NodeId(u64::from(dot))); + drag(&mut frames, center, center + vec2(64.0, 32.0) * zoom); + let graph = frames.app.session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(graph.node(dot).unwrap().pos, [288.0, 96.0]); + assert_eq!(graph.node(multiply).unwrap().inputs, vec![Some(dot), Some(dot)]); + + let bytes = write_sbs(&frames.app.session.pkg).unwrap(); + assert!(std::str::from_utf8(&bytes).unwrap().contains("<function v=\"passthrough\"/>")); + let read = read_sbs(&bytes, "dot_sample.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let saved = read.pkg.graphs.iter().find(|graph| graph.name == "Dot_sample").unwrap().function.as_ref().unwrap(); + let saved_dot = saved.nodes.iter().find(|node| node.op == "passthrough").unwrap(); + assert_eq!(saved_dot.pos, [288.0, 96.0]); + let saved_multiply = saved.nodes.iter().find(|node| node.op == "mul").unwrap(); + assert_eq!(saved_multiply.inputs, vec![Some(saved_dot.id), Some(saved_dot.id)]); + frames.app.session.undo().unwrap(); + assert_eq!(frames.app.session.pkg, before_move); +} + +#[test] +fn regular_inputs_expand_on_connection_and_keep_saved_later_connections_visible() { + let mut frames = Frames::new(new_session()); + let source = frames.app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0]})).unwrap()["id"].as_u64().unwrap(); + let target = frames.app.run("graph.node.add", json!({"def": "blend", "at": [320, 0]})).unwrap()["id"].as_u64().unwrap(); + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + let visible = + |frames: &Frames| frames.app.graph.ports.iter().filter(|port| port.node.0 == target && !port.output).map(|port| port.port.clone()).collect::<Vec<_>>(); + let inputs = frames.app.session.input_ports(NodeId(target)); + assert_eq!(visible(&frames), inputs[..1]); + for input in &inputs { + frames.app.run("graph.connect", json!({"from": source, "to": target, "toPort": input})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + } + assert_eq!(visible(&frames), inputs); + frames.app.run("graph.disconnect", json!({"to": target, "toPort": inputs[0]})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(visible(&frames), inputs); + for input in &inputs[1..] { + frames.app.run("graph.disconnect", json!({"to": target, "toPort": input})).unwrap(); + } + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(visible(&frames), inputs[..1]); +} + +#[test] +fn every_canvas_keeps_properties_after_deselection() { + use materialcraft_engine::core::{FunctionGraph, Value}; + + for kind in ["graph", "function", "pattern"] { + let mut frames = Frames::new(new_session()); + let (id, title) = match kind { + "function" => { + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(Value::Float(2.0)); + let id = graph.add("mul", &[source, source], None); + graph.nodes[1].pos = [256.0, 0.0]; + graph.output = Some(id); + frames.app.run("graph.function.set", json!({"function": graph})).unwrap(); + (NodeId(u64::from(id)), "Multiply - Properties") + } + "pattern" => { + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + frames.app.pattern_editor = Some(crate::pattern::PatternEditor::new(frames.app.session.graph, owner)); + let Value::PatternGraph(graph) = &frames.app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { + panic!("missing pattern graph"); + }; + + (NodeId(u64::from(graph.root.unwrap())), "Quadrant - Properties") + } + _ => { + let id = NodeId(frames.app.run("graph.node.add", json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap()); + (id, "Uniform Color - Properties") + } + }; + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let center = frames.center(id); + frames.click(center, Modifiers::NONE); + assert_eq!(crate::properties::title(&frames.app), title, "{kind}"); + + let blank = frames.app.graph.view.left_bottom() + vec2(12.0, -12.0); + for deselect in [blank, center] { + frames.click(center, Modifiers::NONE); + let modifiers = if deselect == center { Modifiers::CTRL | Modifiers::COMMAND } else { Modifiers::NONE }; + frames.click(deselect, modifiers); + frames.run(Vec::new(), Modifiers::NONE); + + let empty = match kind { + "function" => frames.app.function_editor.as_ref().unwrap().selection.is_empty(), + "pattern" => frames.app.pattern_editor.as_ref().unwrap().selection.is_empty(), + _ => frames.app.session.selection.is_empty(), + }; + assert!(empty, "{kind} remained selected"); + assert_eq!(crate::properties::title(&frames.app), title, "{kind}"); + assert_eq!(frames.app.session.pkg, original); + } + } +} diff --git a/crates/ui-egui/src/graph/library_drag.rs b/crates/ui-egui/src/graph/library_drag.rs new file mode 100644 index 00000000..18bfea4c --- /dev/null +++ b/crates/ui-egui/src/graph/library_drag.rs @@ -0,0 +1,3 @@ +/// A library item being dragged onto the canvas +#[derive(Clone, Debug)] +pub struct LibraryDrag(pub String); diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs new file mode 100644 index 00000000..3b37ae1b --- /dev/null +++ b/crates/ui-egui/src/graph/mod.rs @@ -0,0 +1,31 @@ +pub(crate) mod actions; +pub(crate) mod add_node_menu; +pub(crate) mod annotation_canvas; +pub(crate) mod annotation_input; +pub(crate) mod canvas; +mod context_menu; +mod frame_hit; +#[cfg(test)] +mod frames; +mod graph_camera; +mod graph_drag; +mod graph_view; +pub(crate) mod input_visibility; +#[cfg(test)] +mod interaction_tests; +mod library_drag; +pub(crate) mod node_card; +mod node_layout; +mod node_search; +pub(crate) mod node_selection; +mod port_hit; +pub(crate) mod port_label; + +pub use canvas::{NODE_W, add_node_near_selection, delete_selected_wires, header_color, node_label, node_rect, port_color, show, swap_selected_wires}; +pub(crate) use graph_camera::GraphCamera; +use graph_drag::GraphDrag; +pub use graph_view::GraphView; +pub use library_drag::LibraryDrag; +use node_search::NodeSearch; +pub use port_hit::PortHit; +pub type WireRef = (materialcraft_engine::core::NodeId, String); diff --git a/crates/ui-egui/src/graph/node_card.rs b/crates/ui-egui/src/graph/node_card.rs new file mode 100644 index 00000000..9bab166f --- /dev/null +++ b/crates/ui-egui/src/graph/node_card.rs @@ -0,0 +1,55 @@ +use egui::{Color32, CornerRadius, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; + +pub(crate) const WIDTH: f32 = 100.0; +pub(crate) const HEADER_HEIGHT: f32 = 18.0; +pub(crate) const FOOTER_HEIGHT: f32 = 14.0; +const PORT_GAP: f32 = 18.0; +const DOT_RADIUS: f32 = 7.0; + +pub(crate) fn bounds(position: [f32; 2], inputs: usize, outputs: usize, previews: bool, dot: bool) -> Rect { + let position = pos2(position[0], position[1]); + if dot { + return Rect::from_center_size(position, vec2(DOT_RADIUS * 2.0, DOT_RADIUS * 2.0)); + } + + let ports = inputs.max(outputs) as f32 * PORT_GAP + 8.0; + let body = if previews { WIDTH.max(ports) } else { ports.max(26.0) }; + Rect::from_min_size(position, vec2(WIDTH, HEADER_HEIGHT + body + FOOTER_HEIGHT)) +} + +pub(crate) fn port(bounds: Rect, index: usize, count: usize, output: bool, dot: bool) -> Pos2 { + let x = if output { bounds.right() } else { bounds.left() }; + if dot { + return pos2(x, bounds.center().y); + } + + let body_height = bounds.height() - HEADER_HEIGHT - FOOTER_HEIGHT; + let first = bounds.top() + HEADER_HEIGHT + (body_height - count as f32 * PORT_GAP) * 0.5 + PORT_GAP * 0.5; + pos2(x, first + index as f32 * PORT_GAP) +} + +pub(crate) fn header(bounds: Rect, zoom: f32) -> Rect { + Rect::from_min_size(bounds.min, vec2(bounds.width(), HEADER_HEIGHT * zoom)) +} + +pub(crate) fn body(bounds: Rect, zoom: f32) -> Rect { + Rect::from_min_max(pos2(bounds.left(), bounds.top() + HEADER_HEIGHT * zoom), pos2(bounds.right(), bounds.bottom() - FOOTER_HEIGHT * zoom)) +} + +pub(crate) fn paint(painter: &Painter, bounds: Rect, zoom: f32, label: &str, color: Color32) { + let radius = (5.0 * zoom).clamp(1.0, 6.0) as u8; + let header = header(bounds, zoom); + painter.rect_filled(bounds, radius, Color32::from_rgb(0x1e, 0x20, 0x24)); + painter.rect_filled(header, CornerRadius { nw: radius, ne: radius, sw: 0, se: 0 }, color); + let font = FontId::proportional((10.5 * zoom).clamp(6.0, 16.0)); + let title = crate::widgets::elided(painter, label, font.size, Color32::WHITE, header.width() - 8.0); + painter.galley(header.left_center() + vec2(4.0, -title.size().y * 0.5), title, Color32::WHITE); +} + +pub(crate) fn outline(painter: &Painter, bounds: Rect, zoom: f32, stroke: Stroke) { + painter.rect_stroke(bounds, (5.0 * zoom).clamp(1.0, 6.0) as u8, stroke, StrokeKind::Outside); +} + +pub(crate) fn paint_dot(painter: &Painter, bounds: Rect, color: Color32) { + painter.circle(bounds.center(), bounds.width() * 0.5, Color32::from_gray(0x50), Stroke::new(1.5, color)); +} diff --git a/crates/ui-egui/src/graph/node_layout.rs b/crates/ui-egui/src/graph/node_layout.rs new file mode 100644 index 00000000..43e83826 --- /dev/null +++ b/crates/ui-egui/src/graph/node_layout.rs @@ -0,0 +1,9 @@ +use egui::{Pos2, Rect}; +use materialcraft_engine::{core::NodeId, nodes::PortKind}; + +pub(super) struct NodeLayout { + pub(super) id: NodeId, + pub(super) rect: Rect, + pub(super) ins: Vec<(String, String, PortKind, Pos2)>, + pub(super) outs: Vec<(String, String, PortKind, Pos2)>, +} diff --git a/crates/ui-egui/src/graph/node_search.rs b/crates/ui-egui/src/graph/node_search.rs new file mode 100644 index 00000000..b25f646c --- /dev/null +++ b/crates/ui-egui/src/graph/node_search.rs @@ -0,0 +1,12 @@ +use egui::Pos2; +use materialcraft_engine::core::NodeId; + +/// The node search popup (Space or Tab) +#[derive(Clone, Debug)] +pub(super) struct NodeSearch { + pub(super) at: Pos2, + pub(super) text: String, + pub(super) sel: usize, + pub(super) connect: Option<(NodeId, String)>, + pub(super) focus: bool, +} diff --git a/crates/ui-egui/src/graph/node_selection.rs b/crates/ui-egui/src/graph/node_selection.rs new file mode 100644 index 00000000..35a1d982 --- /dev/null +++ b/crates/ui-egui/src/graph/node_selection.rs @@ -0,0 +1,27 @@ +use egui::Modifiers; + +pub(crate) fn select<T: Copy + Eq>(selection: &mut Vec<T>, node: Option<T>, modifiers: Modifiers) { + let toggle = modifiers.ctrl || modifiers.command; + let additive = toggle || modifiers.shift; + let Some(node) = node else { + if !additive { + selection.clear(); + } + return; + }; + + if selection.contains(&node) { + if toggle { + selection.retain(|selected| *selected != node); + } + } else { + if !additive { + selection.clear(); + } + selection.push(node); + } +} + +pub(crate) fn inspected<T: Copy>(selection: &[T], previous: Option<T>) -> Option<T> { + selection.last().copied().or(previous) +} diff --git a/crates/ui-egui/src/graph/port_hit.rs b/crates/ui-egui/src/graph/port_hit.rs new file mode 100644 index 00000000..e2ef8bbc --- /dev/null +++ b/crates/ui-egui/src/graph/port_hit.rs @@ -0,0 +1,14 @@ +use egui::Pos2; +use materialcraft_engine::core::NodeId; +use materialcraft_engine::nodes::PortKind; + +/// One port as drawn this frame +#[derive(Clone, Debug)] +pub struct PortHit { + pub node: NodeId, + pub output: bool, + pub port: String, + pub label: String, + pub pos: Pos2, + pub kind: PortKind, +} diff --git a/crates/ui-egui/src/graph/port_label.rs b/crates/ui-egui/src/graph/port_label.rs new file mode 100644 index 00000000..bf7503a3 --- /dev/null +++ b/crates/ui-egui/src/graph/port_label.rs @@ -0,0 +1,13 @@ +use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Ui, vec2}; + +pub(crate) fn paint(painter: &Painter, position: Pos2, anchor: Align2, label: &str, zoom: f32, color: Color32) { + let font = FontId::proportional((10.5 * zoom).clamp(6.0, 14.0)); + let text = painter.layout_no_wrap(label.to_string(), font, color); + let bounds = anchor.anchor_size(position, text.size()).expand(2.0); + painter.rect_filled(bounds, 2.0, Color32::from_black_alpha(160)); + painter.galley(bounds.min + vec2(2.0, 2.0), text, color); +} + +pub(crate) fn visible(ui: &Ui, bounds: Rect) -> bool { + ui.input(|input| input.pointer.hover_pos().is_some()) && ui.rect_contains_pointer(bounds.expand(8.0)) +} diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index 6f151e70..986edb70 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -1,12 +1,3 @@ -//! The Levels node's editor in the properties panel: a histogram of the node's input with the -//! levels transfer curve over it, the input range handles (low, mid, high) under it and the -//! output range handles (low, high) under a black-to-white bar. -//! -//! The mid handle sits where `Level in mid` really acts: relative to the input range, so it moves -//! with the low and high handles. The input low and high handles cannot cross (the low one stays -//! left of the high one); the output handles may, which inverts the result. Every drag is a -//! `graph.node.param` command, merged into one undo step per handle. - use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, Ui, pos2, vec2}; use materialcraft_engine::core::{Node, NodeId, Value}; use materialcraft_engine::image::{Image, Kind}; @@ -17,13 +8,13 @@ use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::Tokens; -/// Histogram bins (one per 8-bit level). +/// Histogram bins (one per 8-bit level) pub const BINS: usize = 256; -/// Smallest gap kept between the input low and high handles. +/// Smallest gap kept between the input low and high handles 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. +/// 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(); @@ -40,30 +31,25 @@ pub fn histogram(img: &Image) -> Vec<[u32; BINS]> { h } -/// 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. +/// 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 fn scale(h: &[[u32; BINS]]) -> f32 { let inner = h.iter().flat_map(|b| b.get(1..BINS - 1).unwrap_or(&[]).iter().copied()).max().unwrap_or(0); let all = h.iter().flat_map(|b| b.iter().copied()).max().unwrap_or(0); (if inner > 0 { inner } else { all }).max(1) as f32 } -/// The five levels values of `n`: in low, in mid (relative), in high, out low, out high. +/// The five levels values of `n`: in low, in mid (relative), in high, out low, out high pub fn values(n: &Node) -> [f32; 5] { - let get = |id: &str, d: f32| match n.params.get(id) { - Some(Value::Float(v)) if v.is_finite() => *v, - _ => d, - }; + let get = |id: &str, default: f32| n.params.get(id).and_then(Value::as_f32).filter(|value| value.is_finite()).unwrap_or(default); [get("in_low", 0.0), get("in_mid", 0.5), get("in_high", 1.0), get("out_low", 0.0), get("out_high", 1.0)] } -/// Where the mid handle sits on the 0..1 axis. +/// Where the mid handle sits on the 0..1 axis pub fn mid_position(v: &[f32; 5]) -> f32 { v[0] + v[1].clamp(0.0, 1.0) * (v[2] - v[0]) } -/// The new value of handle `k` (0 in low, 1 in mid, 2 in high, 3 out low, 4 out high) dragged to -/// `x` on the 0..1 axis: input low and high cannot cross, mid is stored relative to the range. +/// The new value of handle `k` (0 in low, 1 in mid, 2 in high, 3 out low, 4 out high) dragged to `x` on the 0..1 axis: input low and high cannot cross, mid is stored relative to the range pub fn drag_value(v: &[f32; 5], k: usize, x: f32) -> f32 { let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }; let (lo, hi) = (v[0].min(v[2]), v[0].max(v[2])); @@ -78,13 +64,13 @@ pub fn drag_value(v: &[f32; 5], k: usize, x: f32) -> f32 { } } -/// The histogram of what feeds the node's input, computed once per cooked result. +/// The histogram of what feeds the node's input, computed once per cooked result fn input_histogram(app: &MaterialCraftApp, ui: &Ui, node: NodeId) -> Option<std::sync::Arc<Vec<[u32; BINS]>>> { let g = app.session.graph().ok()?; let c = g.input_of(node, "input")?; let port = app.session.output_ports(c.from).iter().position(|p| *p == c.from_port)?; let r = app.session.cooked.nodes.get(&c.from)?; - let img = r.outputs.get(port)?; + let img = r.outputs.get(port)?.as_image()?; let id = egui::Id::unique(("levels-histogram", r.key, port)); if let Some(h) = ui.ctx().data(|d| d.get_temp::<std::sync::Arc<Vec<[u32; BINS]>>>(id)) { return Some(h); @@ -94,18 +80,18 @@ fn input_histogram(app: &MaterialCraftApp, ui: &Ui, node: NodeId) -> Option<std: Some(h) } -/// A handle: a small triangle pointing up at `x`, filled with `fill`. +/// A handle: a small triangle pointing up at `x`, filled with `fill` fn handle(p: &egui::Painter, x: f32, top: f32, fill: Color32, active: bool, tk: &Tokens) { let s = 6.0; let pts = vec![pos2(x, top), pos2(x - s, top + s * 1.6), pos2(x + s, top + s * 1.6)]; p.add(Shape::convex_polygon(pts, fill, Stroke::new(if active { 1.5 } else { 1.0 }, if active { tk.accent } else { Color32::from_gray(0x10) }))); } -/// The editor for Levels node `n`. +/// The editor for Levels node `n` pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) { let tk = Tokens::get(ui.ctx()); let v = values(n); - // Handles of parameters driven by an input or a function are left alone. + // Handles of parameters driven by an input or a function are left alone let locked = |id: &str| n.bindings.contains_key(id) || n.functions.contains_key(id); let ids = ["in_low", "in_mid", "in_high", "out_low", "out_high"]; let w = ui.available_width().max(120.0); @@ -117,7 +103,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) { let p = ui.painter_at(rect.expand(2.0)); p.rect_filled(plot, 2.0, Color32::from_gray(0x16)); - // The input histogram. + // The input histogram match input_histogram(app, ui, n.id) { Some(h) => { let k = scale(&h); @@ -130,6 +116,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) { Color32::from_rgba_unmultiplied(0x50, 0x80, 0xf0, 110), ] }; + let bw = plot.width() / BINS as f32; for (bins, col) in h.iter().zip(colors) { for (i, &c) in bins.iter().enumerate() { @@ -146,7 +133,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) { p.text(plot.center(), egui::Align2::CENTER_CENTER, tr("Connect an input to see its histogram"), egui::FontId::proportional(10.5), tk.text_dim); } } - // Shade what the input range clips, and draw the transfer curve. + // Shade what the input range clips, and draw the transfer curve let (lo, hi) = (v[0].min(v[2]), v[0].max(v[2])); let shade = Color32::from_black_alpha(120); p.rect_filled(Rect::from_min_max(plot.min, pos2(axis(lo), plot.bottom())), 0.0, shade); @@ -162,7 +149,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) { p.add(Shape::line(curve, Stroke::new(1.5, tk.accent))); p.rect_stroke(plot, 2.0, Stroke::new(1.0, Color32::from_gray(0x40)), StrokeKind::Inside); - // Input handles under the histogram, output handles under the gradient bar. + // Input handles under the histogram, output handles under the gradient bar let in_row = plot.bottom() + 2.0; let bar = Rect::from_min_max(pos2(plot.left(), in_row + 16.0), pos2(plot.right(), in_row + 26.0)); let mesh = { @@ -175,13 +162,14 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) { m.add_triangle(0, 2, 3); m }; + p.add(Shape::mesh(mesh)); let out_row = bar.bottom() + 2.0; let xs = [v[0], mid_position(&v), v[2], v[3], v[4]]; let rows = [in_row, in_row, in_row, out_row, out_row]; let fills = [Color32::from_gray(0x08), Color32::from_gray(0x80), Color32::WHITE, Color32::from_gray(0x08), Color32::WHITE]; let names = ["Level in low", "Level in mid", "Level in high", "Level out low", "Level out high"]; - // Mid last, so it wins where it overlaps low or high. + // Mid last, so it wins where it overlaps low or high for k in [0usize, 2, 3, 4, 1] { let x = axis(xs[k].clamp(0.0, 1.0)); let hit = Rect::from_min_size(pos2(x - 7.0, rows[k] - 1.0), vec2(14.0, 13.0)); @@ -215,9 +203,9 @@ mod tests { let color = Image::filled(2, 2, Kind::Color, [2.0, f32::NAN, -1.0, 0.5]); let h = histogram(&color); assert_eq!(h.len(), 3); - // Out of range and NaN values land in the end bins. + // Out of range and NaN values land in the end bins assert_eq!((h[0][255], h[1][0], h[2][0]), (4, 4, 4)); - // The scale ignores the end bins when there is anything in between. + // The scale ignores the end bins when there is anything in between assert_eq!(scale(&[[0; BINS]]), 1.0); } @@ -225,19 +213,19 @@ mod tests { fn input_handles_do_not_cross_and_mid_follows_the_range() { let v = [0.2, 0.5, 0.6, 0.0, 1.0]; assert!((mid_position(&v) - 0.4).abs() < 1e-6); - // Low cannot pass high, high cannot pass low. + // Low cannot pass high, high cannot pass low assert!(drag_value(&v, 0, 0.9) < 0.6); assert!(drag_value(&v, 2, 0.1) > 0.2); assert_eq!(drag_value(&v, 0, -1.0), 0.0); assert_eq!(drag_value(&v, 2, 2.0), 1.0); - // Mid is stored relative to the range, kept inside it. + // Mid is stored relative to the range, kept inside it assert!((drag_value(&v, 1, 0.3) - 0.25).abs() < 1e-5); assert_eq!(drag_value(&v, 1, 0.0), 0.01); assert_eq!(drag_value(&v, 1, 1.0), 0.99); - // Output handles may cross (that inverts); NaN never escapes. + // Output handles may cross (that inverts); NaN never escapes assert_eq!(drag_value(&v, 3, 0.8), 0.8); assert_eq!(drag_value(&v, 4, f32::NAN), 0.0); - // A collapsed range keeps mid centered. + // A collapsed range keeps mid centered assert_eq!(drag_value(&[0.5, 0.3, 0.5, 0.0, 1.0], 1, 0.7), 0.5); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 68aac018..7937e5c6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,304 +1,41 @@ -//! # materialcraft-ui-egui -//! -//! The MaterialCraft desktop and web shell: a dense dark professional layout (menu bar, main -//! toolbar, explorer, library, node graph editor, 3D and 2D views, properties, status bar). It is -//! a thin layer: every edit goes through `materialcraft-engine` commands, so the CLI, the control -//! channel and MCP can do the same. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod annotation; pub mod control; pub mod cook; pub mod docking; pub mod explorer; pub mod fonts; -pub mod function_editor; -pub mod graph_view; +pub mod function; +pub mod graph; pub mod i18n; pub mod levels_editor; pub mod library; +mod menu_item; pub mod menus; pub mod properties; pub mod state; pub mod theme; pub mod thumbs; pub mod toolbar; +mod value_input_editor; pub mod view2d; pub mod view3d; pub mod web_files; pub mod widgets; pub mod windows; -use std::collections::VecDeque; - -use materialcraft_engine::Session; -use serde_json::Value; +mod material_craft_app; +pub mod pattern; +mod toast; +mod user_directory; +mod value_editor; pub use control::ControlRequest; +pub use material_craft_app::MaterialCraftApp; +pub use materialcraft_engine::eval::now_ms; pub use state::UiState; - -pub struct Toast { - pub text: String, - pub error: bool, - pub until: f64, -} - -pub struct MaterialCraftApp { - pub session: Session, - pub ui: UiState, - pub control: Option<std::sync::mpsc::Receiver<ControlRequest>>, - pub toasts: Vec<Toast>, - /// Background cooking of the open graph. - pub cooker: cook::Cooker, - /// Node output thumbnails and library previews. - pub thumbs: thumbs::Thumbs, - /// The graph editor's gesture state. - pub graph: graph_view::GraphView, - pub view3d: view3d::View3dState, - pub view2d: view2d::View2dState, - /// The function graph editor window, when open. - pub fn_editor: Option<function_editor::FnEditor>, - /// Synthetic input from the control channel, fed to egui on the next frames. - pub input_queue: VecDeque<control::Scripted>, - /// Replies waiting for the next window capture (`ui.screenshot`). - pub pending_screenshots: Vec<std::sync::mpsc::Sender<Value>>, - pub fps: f32, - /// Smoothed CPU time spent building the UI per frame (ms). - pub ui_ms: f32, - /// The last status message (bottom left). - pub status: String, - last_time: f64, - #[cfg_attr(target_arch = "wasm32", allow(dead_code))] - next_autosave: f64, - styled: Option<(theme::Brightness, theme::Accent)>, - /// Fallback fonts for Arabic. - pub fonts: fonts::UiFonts, - /// The icon font is installed (it takes effect on the frame after `set_fonts`). - fonts_ready: bool, -} - -impl MaterialCraftApp { - pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> MaterialCraftApp { - let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_default(); - theme::install(&cc.egui_ctx); - let mut app = MaterialCraftApp::headless(session, ui); - i18n::set_language(&app.ui.prefs.language); - app.fonts_ready = true; - app.ui.windows.home = app.ui.prefs.show_home; - app - } - - /// An app without eframe (offscreen snapshots and tests): fonts are installed on the first - /// frame, which draws nothing. - pub fn headless(session: Session, mut ui: UiState) -> MaterialCraftApp { - ui.windows = state::Windows::default(); - ui.frame_all = true; - let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; - let mut app = MaterialCraftApp { - session, - ui, - control: None, - toasts: Vec::new(), - cooker: cook::Cooker::default(), - thumbs: thumbs::Thumbs::default(), - graph: graph_view::GraphView::default(), - view3d: view3d::View3dState::default(), - view2d: view2d::View2dState::default(), - fn_editor: None, - input_queue: VecDeque::new(), - pending_screenshots: Vec::new(), - fps: 0.0, - ui_ms: 0.0, - status: String::new(), - last_time: 0.0, - next_autosave, - styled: None, - fonts: fonts::UiFonts::default(), - fonts_ready: false, - }; - i18n::set_language(&app.ui.prefs.language); - app.apply_prefs(); - app - } - - /// Push the preferences that live in the session (preview size, 3D camera). - pub fn apply_prefs(&mut self) { - if self.session.camera != self.ui.prefs.camera.sanitized() { - self.session.set_camera_prefs(self.ui.prefs.camera); - } - let p = if self.ui.prefs.preview_size == 0 { None } else { Some(self.ui.prefs.preview_size.clamp(64, 8192)) }; - if self.session.preview_size != p { - self.session.preview_size = p; - self.session.dirty = true; - } - } - - /// Run an engine command, reporting errors as toasts. Returns the result on success. - pub fn run(&mut self, id: &str, params: Value) -> Option<Value> { - match materialcraft_engine::execute(&mut self.session, id, ¶ms) { - Ok(v) => Some(v), - Err(e) => { - self.toast(e.to_string(), true); - None - } - } - } - - pub fn toast(&mut self, text: impl Into<String>, error: bool) { - let text = text.into(); - self.status = text.clone(); - self.session.log(text.clone()); - self.toasts.push(Toast { text, error, until: self.last_time + if error { 6.0 } else { 3.0 } }); - } - - /// Every `prefs.autosave_minutes`, write a modified package to the autosave folder. - #[cfg(not(target_arch = "wasm32"))] - fn autosave(&mut self, now: f64) { - let period = self.ui.prefs.autosave_minutes as f64 * 60.0; - if period <= 0.0 || !self.session.modified { - self.next_autosave = now + period; - return; - } - if now < self.next_autosave { - return; - } - self.next_autosave = now + period; - let dir = user_dir("autosave"); - let path = dir.join(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name))); - let pkg = self.session.pkg.clone(); - let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || { - let result = std::fs::create_dir_all(&dir) - .map_err(|e| e.to_string()) - .and_then(|_| materialcraft_engine::formats::sbs::write_sbs(&pkg).map_err(|e| e.to_string())) - .and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string())); - match result { - Ok(()) => log::info!("autosaved {}", path.display()), - Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), - } - }); - if let Err(e) = spawned { - log::warn!("could not start autosave: {e}"); - } - } -} - -impl eframe::App for MaterialCraftApp { - fn auto_save_interval(&self) -> std::time::Duration { - std::time::Duration::from_secs(if cfg!(target_arch = "wasm32") { 5 } else { 30 }) - } - - fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); - } - - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { - control::feed_input(self, raw); - } - - fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - self.step(ctx); - } - - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { - self.draw(ui); - } -} - -impl MaterialCraftApp { - /// Per-frame logic before drawing: styles, the control channel, cooking, shortcuts. - pub fn step(&mut self, ctx: &egui::Context) { - if !self.fonts_ready { - theme::install(ctx); - ctx.request_repaint(); - return; - } - i18n::set_language(&self.ui.prefs.language); - self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences); - let now = ctx.input(|i| i.time); - let dt = (now - self.last_time) as f32; - if dt > 0.0 { - self.fps = self.fps * 0.9 + (1.0 / dt) * 0.1; - } - self.last_time = now; - let style = (self.ui.prefs.brightness, self.ui.prefs.accent); - if self.styled != Some(style) { - theme::apply(ctx, style.0, style.1); - self.styled = Some(style); - } - let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); - if (ctx.zoom_factor() - scale).abs() > 1e-3 { - ctx.set_zoom_factor(scale); - } - control::poll(self, ctx); - web_files::poll(self); - for f in ctx.input(|i| i.raw.dropped_files.clone()) { - web_files::dropped(self, ctx, &f); - } - self.apply_prefs(); - cook::drive(self, ctx); - #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); - menus::shortcuts(self, ctx); - self.toasts.retain(|t| t.until > now); - if !self.input_queue.is_empty() { - ctx.request_repaint(); - } - } - - /// Draw the whole window into `ui`. - pub fn draw(&mut self, ui: &mut egui::Ui) { - if !self.fonts_ready { - self.fonts_ready = true; - return; - } - let ctx = ui.ctx().clone(); - let t0 = now_ms(); - // Tab can focus a menu or toolbar button while drawing; preserve keyboard ownership. - self.graph.keyboard_was_focused = ctx.egui_wants_keyboard_input(); - menus::menu_bar(self, ui); - toolbar::main_toolbar(self, ui); - toolbar::status_bar(self, ui); - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); - windows::show(self, &ctx); - function_editor::show(self, &ctx); - toasts(self, &ctx); - control::request_screenshots(self, &ctx); - let dt = (now_ms() - t0) as f32; - self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; - } -} - -/// `Documents/MaterialCraft/<sub>` in the user's home folder. +pub use toast::Toast; #[cfg(not(target_arch = "wasm32"))] -pub fn user_dir(sub: &str) -> std::path::PathBuf { - let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into()); - std::path::Path::new(&home).join("Documents").join("MaterialCraft").join(sub) -} - -/// Milliseconds since the first call (0 on the web, where `std::time` is unavailable). -pub fn now_ms() -> f64 { - materialcraft_engine::eval::now_ms() -} - -fn toasts(app: &mut MaterialCraftApp, ctx: &egui::Context) { - if app.toasts.is_empty() { - return; - } - ctx.request_repaint_after(std::time::Duration::from_millis(250)); - let tk = theme::Tokens::get(ctx); - egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| { - for t in &app.toasts { - egui::Frame::NONE - .fill(tk.panel) - .stroke(egui::Stroke::new(1.0, if t.error { tk.danger } else { tk.accent })) - .corner_radius(theme::CARD_RADIUS) - .shadow(ui.visuals().popup_shadow) - .inner_margin(egui::Margin::symmetric(10, 6)) - .show(ui, |ui| { - ui.set_max_width(380.0); - ui.label(egui::RichText::new(&t.text).color(tk.text_strong)); - }); - ui.add_space(4.0); - } - }); -} +pub use user_directory::user_dir; diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 9b981851..639eee81 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -6,7 +6,7 @@ use egui::{Color32, Rect, RichText, Sense, Ui, vec2}; use egui_phosphor::regular as icon; use crate::MaterialCraftApp; -use crate::graph_view::{LibraryDrag, header_color}; +use crate::graph::{LibraryDrag, header_color}; use crate::i18n::tr; use crate::theme::Tokens; @@ -39,6 +39,16 @@ fn category_icon(top: &str) -> &'static str { } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + if crate::pattern::active(app) { + crate::pattern::library::show(app, ui); + return; + } + + if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + crate::function::library::show(app, ui); + return; + } + let tk = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); @@ -196,7 +206,7 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui) { if is_graph { app.run("graph.node.add", serde_json::json!({"def": "graph_instance", "params": {"graph": id}})); } else { - crate::graph_view::add_node_near_selection(app, &id); + crate::graph::add_node_near_selection(app, &id); } } } diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs new file mode 100644 index 00000000..85ba045f --- /dev/null +++ b/crates/ui-egui/src/material_craft_app.rs @@ -0,0 +1,264 @@ +#[cfg(not(target_arch = "wasm32"))] +use crate::user_dir; +use crate::{ControlRequest, Toast, UiState, now_ms}; +use crate::{control, cook, docking, fonts, function, graph, i18n, menus, pattern, state, theme, thumbs, toolbar, view2d, view3d, web_files, windows}; +use materialcraft_engine::Session; +use serde_json::Value; +use std::collections::VecDeque; + +pub struct MaterialCraftApp { + pub session: Session, + pub ui: UiState, + pub control: Option<std::sync::mpsc::Receiver<ControlRequest>>, + pub toasts: Vec<Toast>, + /// Background cooking of the open graph + pub cooker: cook::Cooker, + /// Node output thumbnails and library previews + pub thumbs: thumbs::Thumbs, + /// The graph editor's gesture state + pub graph: graph::GraphView, + pub view3d: view3d::View3dState, + pub view2d: view2d::View2dState, + /// The function graph editor window, when open + pub pattern_editor: Option<pattern::PatternEditor>, + pub function_editor: Option<function::FunctionEditor>, + /// Synthetic input from the control channel, fed to egui on the next frames + pub input_queue: VecDeque<control::Scripted>, + /// Replies waiting for the next window capture (`ui.screenshot`) + pub pending_screenshots: Vec<std::sync::mpsc::Sender<Value>>, + pub fps: f32, + /// Smoothed CPU time spent building the UI per frame (ms) + pub ui_ms: f32, + /// The last status message (bottom left) + pub status: String, + last_time: f64, + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + next_autosave: f64, + styled: Option<(theme::Brightness, theme::Accent)>, + /// Fallback fonts for Arabic + pub fonts: fonts::UiFonts, + /// The icon font is installed (it takes effect on the frame after `set_fonts`) + fonts_ready: bool, +} + +impl MaterialCraftApp { + pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> MaterialCraftApp { + let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_default(); + theme::install(&cc.egui_ctx); + let mut app = MaterialCraftApp::headless(session, ui); + i18n::set_language(&app.ui.prefs.language); + app.fonts_ready = true; + app.ui.windows.home = app.ui.prefs.show_home; + app + } + + /// An app without eframe (offscreen snapshots and tests): fonts are installed on the first frame, which draws nothing + pub fn headless(session: Session, mut ui: UiState) -> MaterialCraftApp { + ui.windows = state::Windows::default(); + ui.frame_all = true; + let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + let mut app = MaterialCraftApp { + session, + ui, + control: None, + toasts: Vec::new(), + cooker: cook::Cooker::default(), + thumbs: thumbs::Thumbs::default(), + graph: graph::GraphView::default(), + view3d: view3d::View3dState::default(), + view2d: view2d::View2dState::default(), + function_editor: None, + pattern_editor: None, + input_queue: VecDeque::new(), + pending_screenshots: Vec::new(), + fps: 0.0, + ui_ms: 0.0, + status: String::new(), + last_time: 0.0, + next_autosave, + styled: None, + fonts: fonts::UiFonts::default(), + fonts_ready: false, + }; + i18n::set_language(&app.ui.prefs.language); + app.apply_prefs(); + app + } + + /// Push the preferences that live in the session (preview size, 3D camera) + pub fn apply_prefs(&mut self) { + if self.session.camera != self.ui.prefs.camera.sanitized() { + self.session.set_camera_prefs(self.ui.prefs.camera); + } + let p = if self.ui.prefs.preview_size == 0 { None } else { Some(self.ui.prefs.preview_size.clamp(64, 8192)) }; + if self.session.preview_size != p { + self.session.preview_size = p; + self.session.dirty = true; + } + } + + /// Run an engine command, reporting errors as toasts. Returns the result on success + pub fn run(&mut self, id: &str, mut params: Value) -> Option<Value> { + if matches!( + id, + "graph.node.add" + | "graph.node.move" + | "graph.frame.move" + | "graph.wire.insertDot" + | "edit.paste" + | "edit.pasteWithoutLinks" + | "edit.duplicate" + | "edit.duplicateWithoutLinks" + ) { + if params.is_null() { + params = serde_json::json!({}); + } + + if let Some(parameters) = params.as_object_mut() { + parameters.entry("snapToGrid").or_insert(Value::Bool(self.ui.prefs.snap_to_grid)); + } + } + + match materialcraft_engine::execute(&mut self.session, id, ¶ms) { + Ok(v) => { + self.close_subgraph_after(id); + Some(v) + } + Err(e) => { + self.toast(e.to_string(), true); + None + } + } + } + + pub(crate) fn close_subgraph_after(&mut self, command: &str) { + if command.starts_with("file.new") || matches!(command, "file.open" | "graph.open" | "graph.delete" | "graph.duplicate") { + self.graph.inspected_node = None; + self.pattern_editor = None; + self.function_editor = None; + } + } + + pub fn toast(&mut self, text: impl Into<String>, error: bool) { + let text = text.into(); + self.status = text.clone(); + self.session.log(text.clone()); + self.toasts.push(Toast { text, error, until: self.last_time + if error { 6.0 } else { 3.0 } }); + } + + /// Every `prefs.autosave_minutes`, write a modified package to the autosave folder + #[cfg(not(target_arch = "wasm32"))] + fn autosave(&mut self, now: f64) { + let period = self.ui.prefs.autosave_minutes as f64 * 60.0; + if period <= 0.0 || !self.session.modified { + self.next_autosave = now + period; + return; + } + if now < self.next_autosave { + return; + } + self.next_autosave = now + period; + let dir = user_dir("autosave"); + let path = dir.join(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name))); + let pkg = self.session.pkg.clone(); + let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || { + let result = std::fs::create_dir_all(&dir) + .map_err(|e| e.to_string()) + .and_then(|_| materialcraft_engine::formats::sbs::write_sbs(&pkg).map_err(|e| e.to_string())) + .and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string())); + match result { + Ok(()) => log::info!("autosaved {}", path.display()), + Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), + } + }); + if let Err(e) = spawned { + log::warn!("could not start autosave: {e}"); + } + } +} + +impl eframe::App for MaterialCraftApp { + fn auto_save_interval(&self) -> std::time::Duration { + std::time::Duration::from_secs(if cfg!(target_arch = "wasm32") { 5 } else { 30 }) + } + + fn save(&mut self, storage: &mut dyn eframe::Storage) { + eframe::set_value(storage, "ui", &self.ui); + } + + fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { + control::feed_input(self, raw); + } + + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + self.step(ctx); + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + self.draw(ui); + } +} + +impl MaterialCraftApp { + /// Per-frame logic before drawing: styles, the control channel, cooking, shortcuts + pub fn step(&mut self, ctx: &egui::Context) { + if !self.fonts_ready { + theme::install(ctx); + ctx.request_repaint(); + return; + } + i18n::set_language(&self.ui.prefs.language); + self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences); + let now = ctx.input(|i| i.time); + let dt = (now - self.last_time) as f32; + if dt > 0.0 { + self.fps = self.fps * 0.9 + (1.0 / dt) * 0.1; + } + self.last_time = now; + let style = (self.ui.prefs.brightness, self.ui.prefs.accent); + if self.styled != Some(style) { + theme::apply(ctx, style.0, style.1); + self.styled = Some(style); + } + let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); + if (ctx.zoom_factor() - scale).abs() > 1e-3 { + ctx.set_zoom_factor(scale); + } + control::poll(self, ctx); + web_files::poll(self); + for f in ctx.input(|i| i.raw.dropped_files.clone()) { + web_files::dropped(self, ctx, &f); + } + self.apply_prefs(); + cook::drive(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + self.autosave(now); + menus::shortcuts(self, ctx); + self.toasts.retain(|t| t.until > now); + if !self.input_queue.is_empty() { + ctx.request_repaint(); + } + } + + /// Draw the whole window into `ui` + pub fn draw(&mut self, ui: &mut egui::Ui) { + if !self.fonts_ready { + self.fonts_ready = true; + return; + } + let ctx = ui.ctx().clone(); + let t0 = now_ms(); + // Tab can focus a menu or toolbar button while drawing; preserve keyboard ownership + self.graph.keyboard_was_focused = ctx.egui_wants_keyboard_input(); + menus::menu_bar(self, ui); + toolbar::main_toolbar(self, ui); + toolbar::status_bar(self, ui); + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); + windows::show(self, &ctx); + function::show(self, &ctx); + crate::toast::show(self, &ctx); + control::request_screenshots(self, &ctx); + let dt = (now_ms() - t0) as f32; + self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; + } +} diff --git a/crates/ui-egui/src/menu_item.rs b/crates/ui-egui/src/menu_item.rs new file mode 100644 index 00000000..bd3bf80f --- /dev/null +++ b/crates/ui-egui/src/menu_item.rs @@ -0,0 +1,9 @@ +/// A menu entry with an optional submenu and shortcut +#[derive(Clone, Copy, Debug)] +pub struct MenuItem { + pub menu: &'static str, + pub sub: Option<&'static str>, + pub label: &'static str, + pub id: &'static str, + pub shortcut: Option<&'static str>, +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index e615b66c..99bf6871 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,6 +1,4 @@ -//! The menu bar and global shortcuts. The menu catalog follows the menu layout of a standard -//! node-based material authoring workflow, with stable ids; an item is live when the engine (or -//! the shell, for `ui.*` ids) implements its id. The same catalog drives `docs/parity-checklist.md`. +//! Menu actions and shortcuts share stable command ids use egui::{Key, KeyboardShortcut, Modifiers}; use serde_json::Value; @@ -9,32 +7,26 @@ use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::Tokens; -/// One menu entry. `label == "-"` is a separator; `sub` names a submenu group. -#[derive(Clone, Copy, Debug)] -pub struct Item { - pub menu: &'static str, - pub sub: Option<&'static str>, - pub label: &'static str, - pub id: &'static str, - pub shortcut: Option<&'static str>, +pub use crate::menu_item::MenuItem; + +const fn it(menu: &'static str, label: &'static str, id: &'static str, shortcut: Option<&'static str>) -> MenuItem { + MenuItem { menu, sub: None, label, id, shortcut } } -const fn it(menu: &'static str, label: &'static str, id: &'static str, shortcut: Option<&'static str>) -> Item { - Item { menu, sub: None, label, id, shortcut } +const fn sub(menu: &'static str, sub: &'static str, label: &'static str, id: &'static str, shortcut: Option<&'static str>) -> MenuItem { + MenuItem { menu, sub: Some(sub), label, id, shortcut } } -const fn sub(menu: &'static str, sub: &'static str, label: &'static str, id: &'static str, shortcut: Option<&'static str>) -> Item { - Item { menu, sub: Some(sub), label, id, shortcut } -} -const fn sep(menu: &'static str) -> Item { - Item { menu, sub: None, label: "-", id: "", shortcut: None } + +const fn sep(menu: &'static str) -> MenuItem { + MenuItem { menu, sub: None, label: "-", id: "", shortcut: None } } pub const TOP: [&str; 5] = ["File", "Edit", "Tools", "Windows", "Help"]; -/// The menu catalog (the target menu tree with our ids). -pub const CATALOG: &[Item] = &[ +/// The menu catalog (the target menu tree with our ids) +pub const CATALOG: &[MenuItem] = &[ sub("File", "New", "Graph...", "ui.newGraph", Some("Ctrl+N")), - sub("File", "New", "Function graph", "ui.newFunctionGraph", None), + sub("File", "New", "Function Graph...", "ui.newFunctionGraph", None), sub("File", "New", "Empty package", "file.newPackage", None), it("File", "Open...", "file.open", Some("Ctrl+O")), sep("File"), @@ -59,9 +51,18 @@ pub const CATALOG: &[Item] = &[ it("Edit", "Delete", "edit.delete", Some("Delete")), it("Edit", "Delete and relink", "edit.deleteRelink", Some("Backspace")), it("Edit", "Select all", "edit.selectAll", Some("Ctrl+A")), + it("Edit", "Edit node graph", "graph.node.edit", Some("Ctrl+E")), + it("Edit", "Parent graph", "ui.graph.parent", Some("Alt+ArrowLeft")), sep("Edit"), it("Edit", "Preferences...", "ui.preferences", None), - it("Tools", "Compute graph", "graph.cook", Some("F5")), + it("Tools", "Compute graph", "graph.cook", None), + it("Tools", "Snap to grid", "ui.graph.snapToGrid", None), + it("Tools", "Compute nodes thumbnails", "ui.graph.computeThumbnails", None), + it("Tools", "Clear nodes thumbnails", "ui.graph.clearThumbnails", Some("F5")), + it("Tools", "Previous pin", "ui.graph.previousPin", Some("Shift+F2")), + it("Tools", "Next pin", "ui.graph.nextPin", Some("F2")), + it("Tools", "View outputs in 3D view", "ui.graph.viewOutputs", None), + it("Tools", "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", None), it("Tools", "Clear cache", "ui.clearCache", None), sub("Tools", "Preview size", "256 px", "ui.preview.256", None), sub("Tools", "Preview size", "512 px", "ui.preview.512", None), @@ -94,21 +95,49 @@ fn is_ui(id: &str) -> bool { id.starts_with("ui.") } -/// Whether an item can run now. +/// Whether an item can run now pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { + if let Some(enabled) = crate::pattern::enabled(app, id) { + return enabled; + } + + if let Some(enabled) = crate::function::enabled(app, id) { + return enabled; + } + + if let Some(enabled) = crate::graph::actions::enabled(app, id) { + return enabled; + } + + if matches!(id, "edit.paste" | "edit.pasteWithoutLinks") { + return app.session.graph().is_ok() && app.session.clipboard.as_ref().is_some_and(|clip| !clip.nodes.is_empty()); + } + if is_ui(id) { - return id != "ui.newFunctionGraph"; + return true; } materialcraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok()) } -/// Whether an id is implemented at all (parity report). +/// Whether an id is implemented at all (parity report) pub fn implemented(id: &str) -> bool { - (is_ui(id) && id != "ui.newFunctionGraph") || materialcraft_engine::find(id).is_some() + is_ui(id) || materialcraft_engine::find(id).is_some() } -/// Invoke a menu item (menus, shortcuts, the control channel's `ui.menu.invoke`). +/// Invoke a menu item (menus, shortcuts, the control channel's `ui.menu.invoke`) pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { + if crate::pattern::invoke(app, id) { + return; + } + + if crate::function::invoke(app, id) { + return; + } + + if crate::graph::actions::invoke(app, id) { + return; + } + if let Some(panel) = crate::docking::view_panel(id) { app.ui.dock.toggle(panel); return; @@ -119,7 +148,11 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { return; } match id { - "ui.newGraph" => app.ui.windows.new_graph = true, + "ui.newGraph" | "ui.newFunctionGraph" => { + app.ui.new_graph_kind = + if id == "ui.newFunctionGraph" { materialcraft_engine::core::GraphKind::Function } else { materialcraft_engine::core::GraphKind::Material }; + app.ui.windows.new_graph = true; + } "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), "ui.preferences" => app.ui.windows.preferences = true, @@ -150,7 +183,7 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { } } -/// Parse "Ctrl+Shift+E" style shortcuts. +/// Parse "Ctrl+Shift+E" style shortcuts pub fn parse_shortcut(s: &str) -> Option<KeyboardShortcut> { let mut mods = Modifiers::NONE; let mut key = None; @@ -165,7 +198,7 @@ pub fn parse_shortcut(s: &str) -> Option<KeyboardShortcut> { key.map(|k| KeyboardShortcut::new(mods, k)) } -/// The shortcut text shown for `id` (the catalog's, else the engine command's). +/// The shortcut text shown for `id` (the catalog's, else the engine command's) pub fn shortcut_of(id: &str) -> Option<&'static str> { CATALOG.iter().find(|i| i.id == id).and_then(|i| i.shortcut).or_else(|| materialcraft_engine::find(id).and_then(|c| c.shortcut)) } @@ -179,7 +212,7 @@ pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { ui.menu_button(tr(top), |ui| { ui.set_min_width(220.0); let mut current_sub: Option<&str> = None; - let items: Vec<Item> = CATALOG.iter().filter(|i| i.menu == top).copied().collect(); + let items: Vec<MenuItem> = CATALOG.iter().filter(|i| i.menu == top).copied().collect(); for item in &items { if let Some(s) = item.sub { if current_sub == Some(s) { @@ -205,7 +238,7 @@ pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { }); } -fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, item: &Item) { +fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, item: &MenuItem) { let on = enabled(app, item.id); let mut b = egui::Button::new(tr(item.label)); if let Some(sc) = item.shortcut { @@ -213,9 +246,11 @@ fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, } let checked = match item.id { "ui.view.graph" => Some(true), + "ui.graph.snapToGrid" => Some(app.ui.prefs.snap_to_grid), id if id.starts_with("ui.preview.") => id.strip_prefix("ui.preview.").and_then(|s| s.parse::<u32>().ok()).map(|s| s == app.ui.prefs.preview_size), id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)), }; + if let Some(c) = checked { b = b.selected(c); } @@ -243,23 +278,24 @@ fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, } } -/// Global shortcuts from the catalog and the engine commands (skipped while a text field has -/// the keyboard). +/// Dispatch shortcuts unless a widget or popup owns the keyboard pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { - if ctx.egui_wants_keyboard_input() { + if ctx.egui_wants_keyboard_input() || egui::Popup::is_any_open(ctx) { return; } if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) { return; } - // Selected wires take Delete and Backspace before the node commands do, and X swaps them. - if !app.graph.selected_wires.is_empty() { + + // Selected wires handle deletion and swapping before nodes + if !crate::pattern::active(app) && !app.graph.selected_wires.is_empty() { if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { - crate::graph_view::delete_selected_wires(app); + crate::graph::delete_selected_wires(app); } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) { - crate::graph_view::swap_selected_wires(app); + crate::graph::swap_selected_wires(app); } } + let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect(); for c in materialcraft_engine::command_specs() { if table.iter().any(|(id, _)| *id == c.id) { @@ -269,7 +305,8 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { table.push((c.id, sc)); } } - // Longer chords first, so Ctrl+Shift+S is not taken by Ctrl+S. + + // Longer chords take priority table.sort_by_key(|(_, sc)| std::cmp::Reverse(sc.modifiers.ctrl as u8 + sc.modifiers.shift as u8 + sc.modifiers.alt as u8 + sc.modifiers.command as u8)); let mut fire: Vec<&str> = Vec::new(); ctx.input_mut(|i| { @@ -284,7 +321,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } -/// Menu items for `ui.menu.list`. +/// Menu items for `ui.menu.list` pub fn list(app: &MaterialCraftApp) -> Value { Value::Array( CATALOG @@ -311,7 +348,7 @@ mod tests { assert!(parse_shortcut(sc).is_some(), "{sc}"); } } - // Almost every item is live. + // Almost every item is live let live = CATALOG.iter().filter(|i| i.label != "-" && implemented(i.id)).count(); assert!(live + 1 >= CATALOG.iter().filter(|i| i.label != "-").count()); } diff --git a/crates/ui-egui/src/pattern/actions.rs b/crates/ui-egui/src/pattern/actions.rs new file mode 100644 index 00000000..a8aa13d9 --- /dev/null +++ b/crates/ui-egui/src/pattern/actions.rs @@ -0,0 +1,55 @@ +use super::selection; +use crate::MaterialCraftApp; + +pub(crate) fn active(app: &MaterialCraftApp) -> bool { + app.pattern_editor.as_ref().is_some_and(|editor| { + editor.graph == app.session.graph && app.session.graph().is_ok_and(|graph| graph.node(editor.node).is_ok_and(|node| node.def == "fx_map")) + }) +} + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { + if command == "ui.graph.parent" { + return Some(active(app)); + } + if !active(app) { + return None; + } + + if let Some(enabled) = selection::enabled(app.pattern_editor.as_ref()?, command) { + return Some(enabled); + } + match command { + "ui.graph.snapToGrid" | "graph.cook" => None, + command + if command.starts_with("graph.") + || command.starts_with("ui.graph.") + || command.starts_with("edit.") && !matches!(command, "edit.undo" | "edit.redo") => + { + Some(false) + } + _ => None, + } +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + if command == "ui.graph.parent" { + app.pattern_editor = None; + app.function_editor = None; + return true; + } + let Some(allowed) = enabled(app, command) else { return false }; + if !allowed { + return true; + } + + let Some(mut editor) = app.pattern_editor.take() else { return true }; + if let Some(mut graph) = editor.current(app) { + match selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid) { + Ok(true) => editor.commit(app, graph), + Ok(false) => {} + Err(error) => app.toast(error, true), + } + } + app.pattern_editor = Some(editor); + true +} diff --git a/crates/ui-egui/src/pattern/canvas.rs b/crates/ui-egui/src/pattern/canvas.rs new file mode 100644 index 00000000..41e6e6a1 --- /dev/null +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -0,0 +1,158 @@ +use egui::{Color32, Rect, Sense, Stroke, Ui, vec2}; +use materialcraft_engine::core::{NodeId, PatternGraph}; +use materialcraft_engine::nodes::PortKind; +use std::collections::BTreeMap; + +use super::{PatternDrag, PatternEditor, geometry}; +use crate::{ + MaterialCraftApp, + graph::{GraphCamera, PortHit}, + i18n::tr, + theme::Tokens, +}; + +const PORT_COLOR: Color32 = Color32::from_rgb(165, 157, 215); + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let Some(mut editor) = app.pattern_editor.take() else { return }; + let Some(mut graph) = editor.current(app) else { return }; + editor.selection.retain(|id| graph.nodes.iter().any(|node| node.id == *id)); + let parent = app.session.graph().map(|graph| graph.name.clone()).unwrap_or_default(); + let label = app.session.graph().ok().and_then(|graph| graph.node(editor.node).ok()).map(crate::graph::node_label).unwrap_or_default(); + let mut back = false; + ui.horizontal(|ui| { + back = ui.button(&parent).on_hover_text(tr("Return to parent graph")).clicked(); + ui.label("›"); + ui.label(label); + }); + ui.horizontal(|ui| { + if ui.button(tr("Frame all")).clicked() { + editor.framed = false; + } + ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid")); + if graph.root.is_none() { + ui.label(tr("Set a node as the root")); + } + }); + + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); + let changed = canvas(app, &mut editor, &mut graph, ui); + editor.inspected_node = + crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.nodes.iter().any(|node| node.id == *id)); + if changed { + editor.commit(app, graph); + } + if back { + app.function_editor = None; + } else { + app.pattern_editor = Some(editor); + } +} + +fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut PatternGraph, ui: &mut Ui) -> bool { + let (bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(100.0, 100.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "FX-Map graph"); + let painter = ui.painter_at(bounds); + painter.rect_filled(bounds, 0.0, Color32::from_rgb(0x26, 0x28, 0x2c)); + let snap = app.ui.prefs.snap_to_grid; + let frame_key = response.hovered() && !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::F)); + if !editor.framed || app.ui.frame_all || frame_key { + let destination = graph.nodes.iter().map(|node| geometry::bounds(node, editor, snap)).fold(Rect::NOTHING, |all, node| all.union(node)); + if destination.is_finite() { + let destination = destination.expand(48.0); + editor.zoom = (bounds.width() / destination.width()).min(bounds.height() / destination.height()).clamp(0.15, 1.2); + editor.pan = destination.center().to_vec2() - bounds.size() * 0.5 / editor.zoom; + } + editor.framed = true; + app.ui.frame_all = false; + } + + let mut camera = GraphCamera { origin: bounds.min, pan: editor.pan, zoom: editor.zoom }; + if response.hovered() + && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) + { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); + if scroll != 0.0 { + let before = camera.to_graph(pointer); + editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.15, 3.0); + editor.pan = before.to_vec2() - (pointer - bounds.min) / editor.zoom; + camera.pan = editor.pan; + camera.zoom = editor.zoom; + } + } + crate::graph::canvas::grid(&painter, &camera, bounds); + app.graph.view = bounds; + app.graph.rects.clear(); + app.graph.ports.clear(); + app.graph.wires.clear(); + app.graph.frames.clear(); + app.graph.comments.clear(); + + let rectangles: BTreeMap<_, _> = graph + .nodes + .iter() + .map(|node| { + let bounds = geometry::bounds(node, editor, snap); + (node.id, Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max))) + }) + .collect(); + for node in &graph.nodes { + let Some(bounds) = rectangles.get(&node.id) else { continue }; + for (slot, child) in node.children.iter().enumerate() { + if let Some(child_bounds) = child.and_then(|id| rectangles.get(&id)) { + let points = geometry::wire(geometry::port(*bounds, Some(slot), node.children.len()), child_bounds.center_top()); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); + app.graph.wires.push(((NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()), points)); + } + } + } + + let tokens = Tokens::get(ui.ctx()); + for node in &graph.nodes { + let Some(bounds) = rectangles.get(&node.id).copied() else { continue }; + app.graph.rects.push((NodeId(u64::from(node.id)), bounds)); + let outline = if editor.selection.contains(&node.id) { tokens.accent } else { Color32::from_gray(30) }; + super::node_canvas::paint(&painter, bounds, node.kind, editor.zoom, outline); + if graph.root == Some(node.id) { + painter.text( + bounds.right_top() + vec2(-4.0, 4.0) * editor.zoom, + egui::Align2::RIGHT_TOP, + egui_phosphor::regular::STAR, + egui::FontId::proportional(11.0 * editor.zoom), + Color32::GOLD, + ); + } + let node_response = ui.interact(bounds, response.id.with(("node", node.id)), Sense::hover()); + crate::widgets::name(&node_response, egui::Role::Button, node.kind.label()); + + for slot in std::iter::once(None).chain((0..node.children.len()).map(Some)) { + let position = geometry::port(bounds, slot, node.children.len()); + let label = slot.map_or("Input", |slot| geometry::port_label(node.kind, slot)); + painter.circle_filled(position, 5.0 * editor.zoom, PORT_COLOR); + painter.circle_stroke(position, 5.0 * editor.zoom, Stroke::new(1.5, Color32::from_gray(30))); + ui.interact(Rect::from_center_size(position, vec2(16.0, 16.0)), response.id.with((node.id, slot)), Sense::hover()) + .on_hover_text(tr("Drag to connect; Alt-click to disconnect")); + app.graph.ports.push(PortHit { + node: NodeId(u64::from(node.id)), + output: slot.is_some(), + port: slot.map_or_else(|| "input".into(), |slot| node.kind.child_port(slot).unwrap_or_default().to_string()), + label: label.into(), + pos: position, + kind: PortKind::Any, + }); + } + } + + let mut changed = super::input::handle(app, editor, graph, ui, &response, &camera); + if let Some(PatternDrag::Wire { node, slot }) = editor.drag + && let Some(bounds) = rectangles.get(&node) + && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) + { + let count = graph.nodes.iter().find(|candidate| candidate.id == node).map_or(0, |node| node.children.len()); + let source = geometry::port(*bounds, slot, count); + let points = if slot.is_some() { geometry::wire(source, pointer) } else { geometry::wire(pointer, source) }; + painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); + } + response.context_menu(|ui| changed |= super::context_menu::show(app, editor, graph, ui)); + changed +} diff --git a/crates/ui-egui/src/pattern/context_menu.rs b/crates/ui-egui/src/pattern/context_menu.rs new file mode 100644 index 00000000..eb960e76 --- /dev/null +++ b/crates/ui-egui/src/pattern/context_menu.rs @@ -0,0 +1,71 @@ +use egui::Ui; +use materialcraft_engine::core::{PatternGraph, PatternNodeKind}; + +use super::{PatternEditor, selection}; +use crate::{MaterialCraftApp, i18n::tr, menus}; + +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut PatternGraph, ui: &mut Ui) -> bool { + let mut changed = false; + ui.menu_button(tr("Add node"), |ui| { + let kinds = PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot); + let entries = kinds.map(|kind| (kind.native_id(), kind.label(), "FX-Map")); + if let Some(id) = crate::graph::add_node_menu::show(ui, entries) + && let Some(kind) = PatternNodeKind::ALL.into_iter().find(|kind| kind.native_id() == id) + { + match editor.add(graph, kind, app.ui.prefs.snap_to_grid) { + Ok(()) => changed = true, + Err(error) => app.toast(error, true), + } + } + }); + if ui.button(tr("Add Dot node")).clicked() { + match editor.add(graph, PatternNodeKind::Dot, app.ui.prefs.snap_to_grid) { + Ok(()) => changed = true, + Err(error) => app.toast(error, true), + } + ui.close(); + } + if let Some(id) = editor.selection.last().copied() + && ui.button(tr("Set as root")).clicked() + { + graph.root = Some(id); + changed = true; + ui.close(); + } + ui.separator(); + + for (label, command) in [ + ("Copy selection", "edit.copy"), + ("Cut selection", "edit.cut"), + ("Paste", "edit.paste"), + ("Paste without link", "edit.pasteWithoutLinks"), + ("Duplicate selection", "edit.duplicate"), + ("Duplicate selection without link", "edit.duplicateWithoutLinks"), + ("Delete selection", "edit.delete"), + ("Select all", "edit.selectAll"), + ("Select upstream nodes", "graph.selectUpstream"), + ("Select downstream nodes", "graph.selectDownstream"), + ] { + let mut button = egui::Button::new(tr(label)); + if let Some(shortcut) = menus::shortcut_of(command) { + button = button.shortcut_text(shortcut); + } + if ui.add_enabled(selection::enabled(editor, command).unwrap_or(false), button).clicked() { + match selection::run(editor, graph, command, app.ui.prefs.snap_to_grid) { + Ok(edit) => changed |= edit, + Err(error) => app.toast(error, true), + } + ui.close(); + } + } + ui.separator(); + if ui.button(tr("Frame all")).clicked() { + editor.framed = false; + ui.close(); + } + if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() { + menus::invoke(app, ui.ctx(), "file.save"); + ui.close(); + } + changed +} diff --git a/crates/ui-egui/src/pattern/geometry.rs b/crates/ui-egui/src/pattern/geometry.rs new file mode 100644 index 00000000..01eba35f --- /dev/null +++ b/crates/ui-egui/src/pattern/geometry.rs @@ -0,0 +1,44 @@ +use egui::{Pos2, Rect, pos2, vec2}; +use materialcraft_engine::core::{PatternNode, PatternNodeKind}; + +use super::{PatternDrag, PatternEditor}; + +pub(super) const NODE_SIZE: f32 = 96.0; +pub(super) const HEADER_HEIGHT: f32 = 18.0; + +pub(super) fn bounds(node: &PatternNode, editor: &PatternEditor, snap: bool) -> Rect { + let mut position = materialcraft_engine::graph_grid::snap_position(node.position, false); + if let Some(PatternDrag::Nodes { delta, .. }) = editor.drag + && editor.selection.contains(&node.id) + { + position = materialcraft_engine::graph_grid::snap_position([position[0] + delta.x, position[1] + delta.y], snap); + } + let position = pos2(position[0], position[1]); + if node.kind == PatternNodeKind::Dot { + Rect::from_center_size(position, vec2(20.0, 20.0)) + } else { + Rect::from_min_size(position, vec2(NODE_SIZE, NODE_SIZE)) + } +} + +pub(super) fn port(bounds: Rect, slot: Option<usize>, count: usize) -> Pos2 { + match slot { + Some(slot) => pos2(bounds.left() + bounds.width() * (slot as f32 + 0.5) / count.max(1) as f32, bounds.bottom()), + None => bounds.center_top(), + } +} + +pub(super) fn port_label(kind: PatternNodeKind, slot: usize) -> &'static str { + let labels: &[&str] = match kind { + PatternNodeKind::Quadrant => &["Top left", "Top right", "Bottom left", "Bottom right"], + PatternNodeKind::Switch => &["False", "True"], + PatternNodeKind::Iterate => &["Once", "Repeat"], + PatternNodeKind::Dot => &["Output"], + }; + labels.get(slot).copied().unwrap_or("Child") +} + +pub(super) fn wire(source: Pos2, destination: Pos2) -> [Pos2; 4] { + let offset = vec2(0.0, ((destination.y - source.y).abs() * 0.5).max(24.0)); + [source, source + offset, destination - offset, destination] +} diff --git a/crates/ui-egui/src/pattern/input.rs b/crates/ui-egui/src/pattern/input.rs new file mode 100644 index 00000000..dea849c2 --- /dev/null +++ b/crates/ui-egui/src/pattern/input.rs @@ -0,0 +1,140 @@ +use egui::{PointerButton, Rect, Response, Ui}; +use materialcraft_engine::core::PatternGraph; + +use super::{PatternDrag, PatternEditor}; +use crate::{MaterialCraftApp, graph::GraphCamera}; + +pub(super) fn handle( + app: &mut MaterialCraftApp, + editor: &mut PatternEditor, + graph: &mut PatternGraph, + ui: &Ui, + response: &Response, + camera: &GraphCamera, +) -> bool { + let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return false }; + let position = camera.to_graph(pointer); + let port = app + .graph + .ports + .iter() + .filter(|port| port.pos.distance(pointer) < (6.0 * editor.zoom).clamp(1.5, 8.0)) + .min_by(|left, right| left.pos.distance_sq(pointer).total_cmp(&right.pos.distance_sq(pointer))) + .map(|port| { + ( + port.node.0 as u32, + port.output + .then(|| port.port.strip_prefix("output").and_then(|slot| if slot.is_empty() { Some(0) } else { slot.parse::<usize>().ok() })) + .flatten(), + ) + }); + let node = app.graph.rects.iter().rev().find(|(_, bounds)| bounds.contains(pointer)).map(|(id, _)| id.0 as u32); + let modifiers = ui.input(|input| input.modifiers); + let mut changed = false; + + if response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { + if let Some((id, slot)) = port { + if modifiers.alt { + disconnect(graph, id, slot); + changed = true; + } else { + editor.drag = Some(PatternDrag::Wire { node: id, slot }); + } + } else if let Some(id) = node { + crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); + if editor.selection.contains(&id) { + editor.drag = Some(PatternDrag::Nodes { start: position, delta: egui::Vec2::ZERO }); + } + } else { + let additive = modifiers.shift || modifiers.ctrl || modifiers.command; + crate::graph::node_selection::select(&mut editor.selection, None, modifiers); + editor.drag = Some(PatternDrag::Box { start: pointer, additive }); + } + } + if response.drag_started_by(PointerButton::Middle) { + editor.drag = Some(PatternDrag::Pan); + } + match &mut editor.drag { + Some(PatternDrag::Nodes { start, delta }) => *delta = position - *start, + Some(PatternDrag::Pan) => editor.pan -= ui.input(|input| input.pointer.delta()) / editor.zoom, + Some(PatternDrag::Box { start, .. }) => { + ui.painter().rect_stroke( + Rect::from_two_pos(*start, pointer), + 0.0, + egui::Stroke::new(1.0, crate::theme::Tokens::get(ui.ctx()).accent), + egui::StrokeKind::Inside, + ); + } + _ => {} + } + + if ui.input(|input| input.pointer.button_released(PointerButton::Primary)) { + match editor.drag.take() { + Some(PatternDrag::Nodes { delta, .. }) if delta.length_sq() > 0.01 => { + for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { + node.position = + materialcraft_engine::graph_grid::snap_position([node.position[0] + delta.x, node.position[1] + delta.y], app.ui.prefs.snap_to_grid); + } + changed = true; + } + Some(PatternDrag::Wire { node, slot }) => { + if let Some((target, target_slot)) = port { + let connection = match (slot, target_slot) { + (Some(slot), None) => Some((node, slot, target)), + (None, Some(slot)) => Some((target, slot, node)), + _ => None, + }; + if let Some((parent, slot, child)) = connection + && let Some(destination) = graph.nodes.iter_mut().find(|node| node.id == parent).and_then(|node| node.children.get_mut(slot)) + { + *destination = Some(child); + changed = true; + } + } + } + Some(PatternDrag::Box { start, additive }) => { + if !additive { + editor.selection.clear(); + } + let bounds = Rect::from_two_pos(start, pointer); + for (id, rectangle) in &app.graph.rects { + let id = id.0 as u32; + if bounds.intersects(*rectangle) && !editor.selection.contains(&id) { + editor.selection.push(id); + } + } + } + _ => {} + } + } + if ui.input(|input| input.pointer.button_released(PointerButton::Middle)) { + editor.drag = None; + } + if response.secondary_clicked() { + editor.menu_at = position; + if let Some(id) = node + && !editor.selection.contains(&id) + { + crate::graph::node_selection::select(&mut editor.selection, Some(id), egui::Modifiers::NONE); + } + } + if response.hovered() && ui.input(|input| input.key_pressed(egui::Key::Space)) { + editor.menu_at = position; + egui::Popup::open_id(ui.ctx(), response.id.with("menu")); + } + changed +} + +fn disconnect(graph: &mut PatternGraph, id: u32, slot: Option<usize>) { + if let Some(slot) = slot { + if let Some(child) = graph.nodes.iter_mut().find(|node| node.id == id).and_then(|node| node.children.get_mut(slot)) { + *child = None; + } + } else { + for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { + if *child == Some(id) { + *child = None; + } + } + } +} diff --git a/crates/ui-egui/src/pattern/library.rs b/crates/ui-egui/src/pattern/library.rs new file mode 100644 index 00000000..945e3d34 --- /dev/null +++ b/crates/ui-egui/src/pattern/library.rs @@ -0,0 +1,22 @@ +use egui::Ui; +use materialcraft_engine::core::PatternNodeKind; + +use crate::{MaterialCraftApp, i18n::tr}; + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + ui.label(tr("FX-Map nodes")); + for kind in PatternNodeKind::ALL { + if ui.selectable_label(false, tr(kind.label())).double_clicked() + && let Some(mut editor) = app.pattern_editor.take() + { + if let Some(mut graph) = editor.current(app) { + editor.menu_at = (editor.pan + app.graph.view.size() * 0.5 / editor.zoom).to_pos2(); + match editor.add(&mut graph, kind, app.ui.prefs.snap_to_grid) { + Ok(()) => editor.commit(app, graph), + Err(error) => app.toast(error, true), + } + } + app.pattern_editor = Some(editor); + } + } +} diff --git a/crates/ui-egui/src/pattern/mod.rs b/crates/ui-egui/src/pattern/mod.rs new file mode 100644 index 00000000..7a163694 --- /dev/null +++ b/crates/ui-egui/src/pattern/mod.rs @@ -0,0 +1,17 @@ +mod actions; +mod canvas; +mod context_menu; +mod geometry; +mod input; +pub(crate) mod library; +mod node_canvas; +mod parameter_value; +mod pattern_drag; +mod pattern_editor; +pub(crate) mod properties; +mod selection; + +pub(crate) use actions::{active, enabled, invoke}; +pub(crate) use canvas::show; +use pattern_drag::PatternDrag; +pub use pattern_editor::PatternEditor; diff --git a/crates/ui-egui/src/pattern/node_canvas.rs b/crates/ui-egui/src/pattern/node_canvas.rs new file mode 100644 index 00000000..8b92d28a --- /dev/null +++ b/crates/ui-egui/src/pattern/node_canvas.rs @@ -0,0 +1,31 @@ +use egui::{Align2, Color32, FontId, Painter, Rect, Stroke, StrokeKind, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::PatternNodeKind; + +use super::geometry; +use crate::i18n::tr; + +pub(super) fn paint(painter: &Painter, bounds: Rect, kind: PatternNodeKind, zoom: f32, outline: Color32) { + if kind == PatternNodeKind::Dot { + painter.circle(bounds.center(), 6.0 * zoom, Color32::from_gray(180), Stroke::new(2.0, outline)); + return; + } + let color = match kind { + PatternNodeKind::Quadrant => Color32::from_rgb(230, 157, 31), + PatternNodeKind::Switch => Color32::from_rgb(75, 153, 109), + PatternNodeKind::Iterate => Color32::from_rgb(79, 131, 185), + PatternNodeKind::Dot => Color32::from_gray(180), + }; + painter.rect_filled(bounds, 2.0, color); + let header = Rect::from_min_size(bounds.min, vec2(bounds.width(), geometry::HEADER_HEIGHT * zoom)); + painter.rect_filled(header, 2.0, color.gamma_multiply(0.75)); + painter.text(header.center(), Align2::CENTER_CENTER, tr(kind.label()), FontId::proportional(11.0 * zoom), Color32::WHITE); + let symbol = match kind { + PatternNodeKind::Quadrant => icon::GRID_FOUR, + PatternNodeKind::Switch => icon::GIT_BRANCH, + PatternNodeKind::Iterate => icon::ARROWS_CLOCKWISE, + PatternNodeKind::Dot => icon::CIRCLE, + }; + painter.text(bounds.center() + vec2(0.0, 8.0 * zoom), Align2::CENTER_CENTER, symbol, FontId::proportional(48.0 * zoom), Color32::from_gray(35)); + painter.rect_stroke(bounds, 2.0, Stroke::new(2.0, outline), StrokeKind::Outside); +} diff --git a/crates/ui-egui/src/pattern/parameter_value.rs b/crates/ui-egui/src/pattern/parameter_value.rs new file mode 100644 index 00000000..a9355590 --- /dev/null +++ b/crates/ui-egui/src/pattern/parameter_value.rs @@ -0,0 +1,45 @@ +use egui::Ui; +use materialcraft_engine::core::Value; + +pub(super) fn show(ui: &mut Ui, name: &str, value: &mut Value) -> bool { + let options: &[(i32, &str)] = match name { + "patterntype" => &[ + (0, "None"), + (1, "Input image"), + (2, "Square"), + (3, "Disc"), + (4, "Paraboloid"), + (5, "Bell"), + (6, "Gaussian"), + (7, "Thorn"), + (8, "Pyramid"), + (9, "Brick"), + (10, "Gradation"), + (11, "Waves"), + (12, "Half bell"), + (13, "Ridged bell"), + (14, "Crescent"), + (15, "Capsule"), + (16, "Cone"), + (17, "Hemisphere"), + (18, "Offset gradation"), + ], + "blendingmode" => &[(0, "Add"), (1, "Blend"), (2, "Max")], + "imagefiltering" => &[(0, "Nearest"), (1, "Bilinear")], + _ => return crate::value_editor::show(ui, value), + }; + + let Some(mut index) = value.as_i32() else { return false }; + let previous = index; + let label = options.iter().find(|(id, _)| *id == index).map_or("Custom", |(_, label)| *label); + egui::ComboBox::from_id_salt(name).selected_text(label).show_ui(ui, |ui| { + for (id, label) in options { + ui.selectable_value(&mut index, *id, *label); + } + }); + if index == previous { + return false; + } + *value = Value::Int(index); + true +} diff --git a/crates/ui-egui/src/pattern/pattern_drag.rs b/crates/ui-egui/src/pattern/pattern_drag.rs new file mode 100644 index 00000000..89623bad --- /dev/null +++ b/crates/ui-egui/src/pattern/pattern_drag.rs @@ -0,0 +1,8 @@ +use egui::{Pos2, Vec2}; + +pub(super) enum PatternDrag { + Nodes { start: Pos2, delta: Vec2 }, + Wire { node: u32, slot: Option<usize> }, + Box { start: Pos2, additive: bool }, + Pan, +} diff --git a/crates/ui-egui/src/pattern/pattern_editor.rs b/crates/ui-egui/src/pattern/pattern_editor.rs new file mode 100644 index 00000000..08a59674 --- /dev/null +++ b/crates/ui-egui/src/pattern/pattern_editor.rs @@ -0,0 +1,67 @@ +use egui::{Pos2, Vec2}; +use materialcraft_engine::core::{NodeId, PatternGraph, PatternNode, PatternNodeKind, Value}; +use serde_json::json; + +use super::PatternDrag; +use crate::MaterialCraftApp; + +pub struct PatternEditor { + pub node: NodeId, + pub graph: usize, + pub(crate) selection: Vec<u32>, + pub(crate) inspected_node: Option<u32>, + pub(super) clipboard: Vec<PatternNode>, + pub(super) pan: Vec2, + pub(super) zoom: f32, + pub(super) framed: bool, + pub(super) drag: Option<PatternDrag>, + pub(super) menu_at: Pos2, +} + +impl PatternEditor { + pub fn new(graph: usize, node: NodeId) -> Self { + Self { + node, + graph, + selection: Vec::new(), + inspected_node: None, + clipboard: Vec::new(), + pan: Vec2::ZERO, + zoom: 1.0, + framed: false, + drag: None, + menu_at: Pos2::ZERO, + } + } + + pub(super) fn current(&self, app: &MaterialCraftApp) -> Option<PatternGraph> { + if app.session.graph != self.graph { + return None; + } + + let node = app.session.graph().ok()?.node(self.node).ok()?; + if node.def != "fx_map" { + return None; + } + + let default = materialcraft_engine::nodes::find(&node.def)?.param("pattern"); + match node.params.get("pattern").or_else(|| default.map(|parameter| ¶meter.default)) { + Some(Value::PatternGraph(graph)) => Some((**graph).clone()), + None => Some(PatternGraph::default()), + _ => None, + } + } + + pub(super) fn commit(&self, app: &mut MaterialCraftApp, graph: PatternGraph) { + app.run("graph.pattern.set", json!({"id": self.node.0, "pattern": graph})); + } + + pub(super) fn add(&mut self, graph: &mut PatternGraph, kind: PatternNodeKind, snap: bool) -> Result<(), String> { + let id = graph.add(kind)?; + if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) { + node.position = materialcraft_engine::graph_grid::snap_position([self.menu_at.x, self.menu_at.y], snap); + } + self.selection = vec![id]; + Ok(()) + } +} diff --git a/crates/ui-egui/src/pattern/properties.rs b/crates/ui-egui/src/pattern/properties.rs new file mode 100644 index 00000000..5dd8de8b --- /dev/null +++ b/crates/ui-egui/src/pattern/properties.rs @@ -0,0 +1,72 @@ +use egui::Ui; +use materialcraft_engine::core::{FunctionGraph, Value}; + +use crate::{ + MaterialCraftApp, + function::{FunctionEditor, FunctionTarget}, + i18n::tr, +}; + +pub(crate) fn title(app: &MaterialCraftApp) -> String { + let kind = app.pattern_editor.as_ref().and_then(|editor| { + let graph = editor.current(app)?; + let inspected = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); + graph.nodes.iter().find(|node| Some(node.id) == inspected).map(|node| node.kind) + }); + format!("{} - {}", kind.map_or("FX-Map", |kind| kind.label()), tr("Properties")) +} + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let Some(editor) = app.pattern_editor.take() else { return }; + let Some(mut graph) = editor.current(app) else { return }; + let mut changed = false; + let mut function_target = None; + + let inspected = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); + if let Some(node) = graph.nodes.iter_mut().find(|node| Some(node.id) == inspected) { + ui.heading(tr(node.kind.label())); + if graph.root == Some(node.id) { + ui.label(tr("Root node")); + } + if let Some(definition) = materialcraft_engine::nodes::pattern::definition(node.kind) { + for parameter in &definition.params { + ui.push_id(parameter.id, |ui| { + ui.label(tr(parameter.label)); + let mut value = node.parameters.get(parameter.id).unwrap_or(¶meter.default).clone(); + ui.horizontal_wrapped(|ui| { + if matches!(value, Value::Function(_)) { + if ui.small_button(tr("Edit function")).clicked() { + function_target = Some(FunctionTarget::Pattern { node: node.id, parameter: parameter.id.to_string() }); + } + if ui.small_button(tr("Reset")).clicked() { + node.parameters.remove(parameter.id); + changed = true; + } + } else { + if super::parameter_value::show(ui, parameter.id, &mut value) { + node.parameters.insert(parameter.id.to_string(), value.clone()); + changed = true; + } + if ui.small_button(tr("Function")).clicked() { + node.parameters.insert(parameter.id.to_string(), Value::Function(Box::new(FunctionGraph::constant(value)))); + function_target = Some(FunctionTarget::Pattern { node: node.id, parameter: parameter.id.to_string() }); + changed = true; + } + } + }); + ui.add_space(6.0); + }); + } + } + } else { + ui.heading(tr("FX-Map")); + ui.label(tr("Select a node to edit its parameters")); + } + if changed { + editor.commit(app, graph); + } + if let Some(target) = function_target { + app.function_editor = Some(FunctionEditor::new(editor.node, target)); + } + app.pattern_editor = Some(editor); +} diff --git a/crates/ui-egui/src/pattern/selection.rs b/crates/ui-egui/src/pattern/selection.rs new file mode 100644 index 00000000..226a129c --- /dev/null +++ b/crates/ui-egui/src/pattern/selection.rs @@ -0,0 +1,88 @@ +use materialcraft_engine::core::PatternGraph; +use std::collections::{BTreeMap, BTreeSet}; + +use super::PatternEditor; + +pub(super) fn enabled(editor: &PatternEditor, command: &str) -> Option<bool> { + Some(match command { + "edit.selectAll" | "edit.selectNone" => true, + "edit.paste" | "edit.pasteWithoutLinks" => !editor.clipboard.is_empty(), + "edit.copy" | "edit.cut" | "edit.delete" | "edit.duplicate" | "edit.duplicateWithoutLinks" | "graph.selectUpstream" | "graph.selectDownstream" => { + !editor.selection.is_empty() + } + _ => return None, + }) +} + +pub(super) fn run(editor: &mut PatternEditor, graph: &mut PatternGraph, command: &str, snap: bool) -> Result<bool, String> { + match command { + "edit.selectAll" => editor.selection = graph.nodes.iter().map(|node| node.id).collect(), + "edit.selectNone" => editor.selection.clear(), + "edit.copy" | "edit.cut" => { + editor.clipboard = graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect(); + if command == "edit.cut" { + return Ok(remove(editor, graph)); + } + } + "edit.delete" => return Ok(remove(editor, graph)), + "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { + let duplicate = command.starts_with("edit.duplicate"); + let nodes = + if duplicate { graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect() } else { editor.clipboard.clone() }; + let anchor = nodes.first().map_or([0.0; 2], |node| node.position); + let offset = if duplicate { [32.0; 2] } else { [editor.menu_at.x - anchor[0], editor.menu_at.y - anchor[1]] }; + let present: BTreeSet<_> = graph.nodes.iter().map(|node| node.id).collect(); + let mut ids = BTreeMap::new(); + for mut node in nodes { + let original = node.id; + node.id = graph.add(node.kind)?; + node.position = materialcraft_engine::graph_grid::snap_position([node.position[0] + offset[0], node.position[1] + offset[1]], snap); + ids.insert(original, node.id); + if let Some(destination) = graph.nodes.last_mut() { + *destination = node; + } + } + editor.selection = ids.values().copied().collect(); + for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { + for child in &mut node.children { + *child = child.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks") && present.contains(&id)).then_some(id))); + } + } + return Ok(!ids.is_empty()); + } + "graph.selectUpstream" | "graph.selectDownstream" => { + let mut visited = BTreeSet::new(); + let mut pending = editor.selection.clone(); + while let Some(id) = pending.pop() { + if !visited.insert(id) { + continue; + } + if command == "graph.selectDownstream" { + if let Some(node) = graph.nodes.iter().find(|node| node.id == id) { + pending.extend(node.children.iter().flatten()); + } + } else { + pending.extend(graph.nodes.iter().filter(|node| node.children.contains(&Some(id))).map(|node| node.id)); + } + } + editor.selection = visited.into_iter().collect(); + } + _ => {} + } + Ok(false) +} + +fn remove(editor: &mut PatternEditor, graph: &mut PatternGraph) -> bool { + let before = graph.nodes.len(); + graph.nodes.retain(|node| !editor.selection.contains(&node.id)); + for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { + if child.is_some_and(|id| editor.selection.contains(&id)) { + *child = None; + } + } + if graph.root.is_some_and(|id| editor.selection.contains(&id)) { + graph.root = None; + } + editor.selection.clear(); + graph.nodes.len() != before +} diff --git a/crates/ui-egui/src/properties.rs b/crates/ui-egui/src/properties.rs index 487f7234..5046718b 100644 --- a/crates/ui-egui/src/properties.rs +++ b/crates/ui-egui/src/properties.rs @@ -1,25 +1,38 @@ -//! Properties: the selected node's base and specific parameters, or the graph's own settings, -//! inputs and outputs when no node is selected. Every change is an engine command (slider drags -//! merge into one undo step). - use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as icon; use materialcraft_engine::core::{Curve, Gradient, NodeId, OutputFormat, SizeMode, Value}; -use materialcraft_engine::nodes::ParamDef; +use materialcraft_engine::nodes::ParameterDefinition; use serde_json::{Value as J, json}; use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::Tokens; -/// The panel title: "<node> - Properties" or "<graph> - Properties". +/// The panel title: "<node> - Properties" or "<graph> - Properties" pub fn title(app: &MaterialCraftApp) -> String { - let sel = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().map(crate::graph_view::node_label)); + if crate::pattern::active(app) { + return crate::pattern::properties::title(app); + } + + if let Some(selection) = app.session.annotation_selection { + let name = match selection { + materialcraft_engine::AnnotationSelection::Frame(_) => tr("Frame"), + materialcraft_engine::AnnotationSelection::Comment(_) => tr("Comment"), + }; + return format!("{name} - {}", tr("Properties")); + } + + if let Some(title) = crate::function::properties::title(app) { + return title; + } + + let sel = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) + .and_then(|id| app.session.graph().ok()?.node(id).ok().map(crate::graph::node_label)); let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default(); format!("{name} - {}", tr("Properties")) } -fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { +pub(crate) fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { let tk = Tokens::get(ui.ctx()); let id = ui.make_persistent_id(id); let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); @@ -42,7 +55,22 @@ fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.set_width(ui.available_width()); - let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned()); + if crate::pattern::active(app) { + crate::pattern::properties::show(app, ui); + return; + } + + if let Some(selection) = app.session.annotation_selection { + ui.push_id((app.session.graph, format!("{selection:?}")), |ui| crate::annotation::show(app, ui, selection)); + return; + } + + if crate::function::properties::show(app, ui) { + return; + } + + let node = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) + .and_then(|id| app.session.graph().ok()?.node(id).ok().cloned()); ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { Some(n) => node_props(app, ui, &n), None => graph_props(app, ui), @@ -53,11 +81,11 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { let tk = Tokens::get(ui.ctx()); let def = materialcraft_engine::nodes::find(&n.def); - // Header: label (renamable) and description. + // Header: label (renamable) and description ui.horizontal(|ui| { - ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph_view::header_color(&n.def)); + ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph::header_color(&n.def)); ui.add_space(8.0); - let mut label = if n.label.is_empty() { crate::graph_view::node_label(n) } else { n.label.clone() }; + let mut label = if n.label.is_empty() { crate::graph::node_label(n) } else { n.label.clone() }; let r = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)); crate::widgets::name(&r, egui::Role::TextInput, "Node label"); if r.changed() { @@ -76,6 +104,10 @@ fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine: } ui.add_space(4.0); section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, n)); + crate::value_input_editor::show(app, ui, n); + if n.def == "input_value" { + crate::value_input_editor::default_value(app, ui, n); + } if n.def == "graph_instance" { section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, n)); return; @@ -92,6 +124,9 @@ fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine: let exposed: Vec<(String, String)> = app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default(); for p in &def.params { + if n.def == "input_value" && p.id == "default" { + continue; + } let cur = n.params.get(p.id).cloned().unwrap_or_else(|| p.default.clone()); if n.functions.contains_key(p.id) { function_row(app, ui, n.id, p.id, p.label); @@ -116,6 +151,7 @@ fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine SizeMode::RelativeToParent => "relativeToParent", SizeMode::Absolute => "absolute", }; + let size = if m == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); } @@ -129,6 +165,7 @@ fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine } else { format!("{label} x {}", 2f32.powi(b.size[axis])) }; + if crate::widgets::slider(ui, &caption, &mut v, lo..=hi, 0).changed() { let mut size = b.size; size[axis] = v.round() as i32; @@ -145,6 +182,7 @@ fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine OutputFormat::F16 => "f16", OutputFormat::F32 => "f32", }; + app.run("graph.node.base", json!({"id": id, "format": key})); } } @@ -171,8 +209,8 @@ fn typed(v: &Value) -> J { serde_json::to_value(v).unwrap_or(J::Null) } -/// One parameter: its editor, plus the expose/bind menu. -fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef, cur: Value, bound: Option<String>, exposed: &[(String, String)]) { +/// One parameter: its editor, plus the expose/bind menu +fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParameterDefinition, cur: Value, bound: Option<String>, exposed: &[(String, String)]) { let tk = Tokens::get(ui.ctx()); if let Some(input) = &bound { ui.horizontal(|ui| { @@ -190,10 +228,10 @@ fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef app.run("graph.node.reset", json!({"id": node.0, "param": p.id})); ui.close(); } - let dynamic = !matches!(p.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_)); + let dynamic = !matches!(p.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_)); if dynamic && ui.button(tr("Set function...")).clicked() { if app.run("graph.node.function", json!({"id": node.0, "param": p.id})).is_some() { - app.fn_editor = Some(crate::function_editor::FnEditor::new(node, &format!("fn:{}", p.id))); + app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Dynamic(p.id.to_string()))); } ui.close(); } @@ -213,6 +251,7 @@ fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef } }); }; + match cur { Value::Float(mut v) => { if p.angle { @@ -272,7 +311,14 @@ fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef } resp_menu(app, &r); } - Value::Color(c) | Value::Float4(c) => { + Value::Float3(_) | Value::Float4(_) | Value::Int3(_) | Value::Int4(_) => { + ui.label(tr(p.label)); + let mut value = cur.clone(); + if crate::value_editor::show(ui, &mut value) { + set(app, node, p.id, serde_json::to_value(value).unwrap_or_default()); + } + } + Value::Color(c) => { ui.horizontal(|ui| { ui.label(RichText::new(tr(p.label)).color(tk.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -329,24 +375,24 @@ fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef set(app, node, p.id, typed(&Value::Gradient(ng))); } } + Value::PatternGraph(graph) => { + ui.label(format!("{}: {} nodes", p.label, graph.nodes.len())); + } Value::Function(f) => { ui.label(RichText::new(tr(p.label)).color(tk.text)); crate::windows::function_summary(app, ui, node, p.id, &f); } - other => { - ui.label(format!("{}: {}", p.label, other.type_name())); - } } } -/// A parameter driven by a function: its label, Edit and Remove. +/// A parameter driven by a function: its label, Edit and Remove fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { let tk = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.label(RichText::new(tr(label)).color(tk.text)); ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tk.accent)); if ui.small_button(tr("Edit")).clicked() { - app.fn_editor = Some(crate::function_editor::FnEditor::new(node, &format!("fn:{param}"))); + app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Dynamic(param.to_string()))); } if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); @@ -360,6 +406,7 @@ fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_en ui.label(RichText::new(tr("The instanced graph is missing")).color(tk.danger)); return; }; + let exposed = sub.exposed.clone(); if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() { app.run("graph.open", json!({"graph": gi})); @@ -376,8 +423,8 @@ fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_en } } -/// The editor for one exposed input's value; returns the new value as JSON when it changed. -fn input_editor(ui: &mut Ui, e: &materialcraft_engine::core::ExposedParam, cur: &Value) -> Option<J> { +/// The editor for one exposed input's value; returns the new value as JSON when it changed +fn input_editor(ui: &mut Ui, e: &materialcraft_engine::core::ExposedParameter, cur: &Value) -> Option<J> { match *cur { Value::Float(mut f) => { let v0 = f; @@ -424,6 +471,7 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.label(tr("No graph is open")); return; }; + let g = g.clone(); section(ui, "graph-base", tr("Base parameters"), |ui| { ui.horizontal(|ui| { @@ -435,6 +483,10 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { app.run("graph.rename", json!({"name": name})); } }); + if g.function.is_some() { + return; + } + for (axis, label) in [(0usize, "Width"), (1, "Height")] { let mut v = g.size[axis] as f32; if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << g.size[axis]), &mut v, 4.0..=13.0, 0).changed() { @@ -486,7 +538,7 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { } } let mut last_group: Option<&str> = None; - let mut order: Vec<&materialcraft_engine::core::ExposedParam> = Vec::new(); + let mut order: Vec<&materialcraft_engine::core::ExposedParameter> = Vec::new(); for grp in &groups { order.extend(g.exposed.iter().filter(|e| e.group == *grp)); } @@ -525,8 +577,7 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { }); } -/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such -/// as a mesh map baked in TextureCraft. +/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such as a mesh map baked in TextureCraft fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { let inputs = materialcraft_engine::material_cmds::image_inputs(g); if inputs.is_empty() { @@ -560,7 +611,7 @@ fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_eng }); } -/// Presets: apply one, save the current inputs under a name, delete one. +/// Presets: apply one, save the current inputs under a name, delete one fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { let name_id = ui.make_persistent_id("preset-name"); let mut name: String = ui.data(|d| d.get_temp(name_id)).unwrap_or_default(); @@ -589,8 +640,7 @@ fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine ui.data_mut(|d| d.insert_temp(name_id, name)); } -/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. -/// Returns the new curve when it changed. +/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. Returns the new curve when it changed pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> { let tk = Tokens::get(ui.ctx()); let w = ui.available_width().min(240.0); @@ -634,7 +684,7 @@ pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> { let mut nc = c.clone(); let last = nc.points.len().saturating_sub(1); if let Some(pt) = nc.points.get_mut(i) { - // End points keep their x. + // End points keep their x if i != 0 && i != last { pt.x = x; } @@ -652,7 +702,7 @@ pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> { { let (x, _) = from_s(q); let mut nc = c.clone(); - nc.points.push(materialcraft_engine::core::CurvePoint { x, y: c.eval(x) }); + nc.points.push(materialcraft_engine::core::CurvePoint::new(x, c.eval(x))); nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); out = Some(nc); } @@ -668,8 +718,7 @@ pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> { out } -/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a -/// key's color, right-click a key to remove it. +/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a key's color, right-click a key to remove it pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option<Gradient> { let tk = Tokens::get(ui.ctx()); let w = ui.available_width().min(260.0); @@ -727,7 +776,7 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option<Gradient> None => { let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); let mut ng = g.clone(); - ng.keys.push(materialcraft_engine::core::GradientKey { pos: t, color: g.eval(t) }); + ng.keys.push(materialcraft_engine::core::GradientKey::new(t, g.eval(t))); ng.sort(); sel = ng.keys.iter().position(|k| k.pos == t).unwrap_or(0); out = Some(ng); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs deleted file mode 100644 index d49a628f..00000000 --- a/crates/ui-egui/src/state.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! UI state: serde data, so the control channel can read and drive it and eframe persists it. - -use serde::{Deserialize, Serialize}; - -use materialcraft_engine::CameraPrefs; - -use crate::docking::Dock; -use crate::theme::{Accent, Brightness}; - -/// Preferences (Edit ▸ Preferences). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Prefs { - /// UI language code (`i18n::LANGUAGES`). - pub language: String, - pub brightness: Brightness, - pub accent: Accent, - pub ui_scale: f32, - /// Largest node output while editing (0 = full size). - pub preview_size: u32, - /// Minutes between autosaves of a modified package (0 = off). - pub autosave_minutes: u32, - /// Show node thumbnails in the graph. - pub thumbnails: bool, - /// Library tiles: large icons or a list. - pub library_list: bool, - /// Open the home screen when the app starts. - pub show_home: bool, - /// 3D view camera: pan limit and speed. - pub camera: CameraPrefs, -} - -impl Default for Prefs { - fn default() -> Self { - Prefs { - language: crate::i18n::os_language().into(), - brightness: Brightness::default(), - accent: Accent::default(), - ui_scale: 1.0, - preview_size: 512, - autosave_minutes: 5, - thumbnails: true, - library_list: false, - show_home: true, - camera: CameraPrefs::default(), - } - } -} - -/// Which dialogs are open. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Windows { - pub new_graph: bool, - pub export: bool, - pub about: bool, - pub preferences: bool, - pub shortcuts: bool, - pub home: bool, -} - -/// The graph view's camera: the graph point at the view's top-left corner, and the zoom. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct GraphCamera { - pub pan: [f32; 2], - pub zoom: f32, -} - -impl Default for GraphCamera { - fn default() -> Self { - GraphCamera { pan: [-60.0, -60.0], zoom: 0.8 } - } -} - -/// The 2D view's camera: image zoom (1 = one image pixel per point) and center offset. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImageCamera { - pub zoom: f32, - pub offset: [f32; 2], - /// Fit the image to the view (until the user zooms). - pub fit: bool, -} - -impl Default for ImageCamera { - fn default() -> Self { - ImageCamera { zoom: 1.0, offset: [0.0, 0.0], fit: true } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct UiState { - pub dock: Dock, - pub prefs: Prefs, - pub windows: Windows, - pub graph_camera: GraphCamera, - pub image_camera: ImageCamera, - /// Library: the selected category path ("" = all) and the search text. - pub library_category: String, - pub library_search: String, - /// Recently opened or saved packages, newest first. - pub recent: Vec<String>, - /// New graph dialog fields. - pub new_graph_template: String, - pub new_graph_name: String, - pub new_graph_size: u32, - /// Export dialog fields. - pub export_dir: String, - pub export_format: String, - pub export_depth: u32, - /// Export size in pixels; 0 = the graph's own size. - pub export_size: u32, - pub export_pattern: String, - /// Frame the whole graph on the next frame. - #[serde(skip)] - pub frame_all: bool, -} - -impl Default for UiState { - fn default() -> Self { - UiState { - dock: Dock::default(), - prefs: Prefs::default(), - windows: Windows::default(), - graph_camera: GraphCamera::default(), - image_camera: ImageCamera::default(), - library_category: String::new(), - library_search: String::new(), - recent: Vec::new(), - new_graph_template: "pbr".into(), - new_graph_name: "New_graph".into(), - new_graph_size: 1024, - export_dir: String::new(), - export_format: "png".into(), - export_depth: 0, - export_size: 0, - export_pattern: "$(graph)_$(identifier)".into(), - frame_all: true, - } - } -} - -impl UiState { - /// Remember `path` at the top of the recent list. - pub fn add_recent(&mut self, path: &str) { - self.recent.retain(|p| p != path); - self.recent.insert(0, path.to_string()); - self.recent.truncate(12); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn camera_prefs_persist_and_default_when_missing() { - // Preferences saved before the camera settings existed still load, with the defaults. - let old: Prefs = serde_json::from_value(serde_json::json!({"uiScale": 1.25})).unwrap(); - assert_eq!(old.camera, CameraPrefs::default()); - assert_eq!(old.ui_scale, 1.25); - let p = Prefs { camera: CameraPrefs { pan_limit: 8.0, pan_speed: 0.5 }, ..Prefs::default() }; - let v = serde_json::to_value(&p).unwrap(); - assert_eq!(v["camera"], serde_json::json!({"panLimit": 8.0, "panSpeed": 0.5})); - assert_eq!(serde_json::from_value::<Prefs>(v).unwrap(), p); - } -} diff --git a/crates/ui-egui/src/state/graph_camera.rs b/crates/ui-egui/src/state/graph_camera.rs new file mode 100644 index 00000000..9f9a9654 --- /dev/null +++ b/crates/ui-egui/src/state/graph_camera.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +/// The graph view's camera: the graph point at the view's top-left corner, and the zoom +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GraphCamera { + pub pan: [f32; 2], + pub zoom: f32, +} + +impl Default for GraphCamera { + fn default() -> Self { + GraphCamera { pan: [-60.0, -60.0], zoom: 0.8 } + } +} diff --git a/crates/ui-egui/src/state/image_camera.rs b/crates/ui-egui/src/state/image_camera.rs new file mode 100644 index 00000000..b74dfd88 --- /dev/null +++ b/crates/ui-egui/src/state/image_camera.rs @@ -0,0 +1,16 @@ +use serde::{Deserialize, Serialize}; + +/// The 2D view's camera: image zoom (1 = one image pixel per point) and center offset +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImageCamera { + pub zoom: f32, + pub offset: [f32; 2], + /// Fit the image to the view (until the user zooms) + pub fit: bool, +} + +impl Default for ImageCamera { + fn default() -> Self { + ImageCamera { zoom: 1.0, offset: [0.0, 0.0], fit: true } + } +} diff --git a/crates/ui-egui/src/state/mod.rs b/crates/ui-egui/src/state/mod.rs new file mode 100644 index 00000000..b6fca109 --- /dev/null +++ b/crates/ui-egui/src/state/mod.rs @@ -0,0 +1,10 @@ +mod prefs; +pub use prefs::Prefs; +mod windows; +pub use windows::Windows; +mod graph_camera; +pub use graph_camera::GraphCamera; +mod image_camera; +pub use image_camera::ImageCamera; +mod ui_state; +pub use ui_state::UiState; diff --git a/crates/ui-egui/src/state/prefs.rs b/crates/ui-egui/src/state/prefs.rs new file mode 100644 index 00000000..2a6e0c50 --- /dev/null +++ b/crates/ui-egui/src/state/prefs.rs @@ -0,0 +1,64 @@ +use serde::{Deserialize, Serialize}; + +use crate::theme::{Accent, Brightness}; +use materialcraft_engine::CameraPrefs; + +/// Preferences (Edit ▸ Preferences) +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Prefs { + /// UI language code (`i18n::LANGUAGES`) + pub language: String, + pub brightness: Brightness, + pub accent: Accent, + pub ui_scale: f32, + /// Largest node output while editing (0 = full size) + pub preview_size: u32, + /// Minutes between autosaves of a modified package (0 = off) + pub autosave_minutes: u32, + /// Show node thumbnails in the graph + pub thumbnails: bool, + pub snap_to_grid: bool, + /// Library tiles: large icons or a list + pub library_list: bool, + /// Open the home screen when the app starts + pub show_home: bool, + /// 3D view camera: pan limit and speed + pub camera: CameraPrefs, +} + +impl Default for Prefs { + fn default() -> Self { + Prefs { + language: crate::i18n::os_language().into(), + brightness: Brightness::default(), + accent: Accent::default(), + ui_scale: 1.0, + preview_size: 512, + autosave_minutes: 5, + thumbnails: true, + snap_to_grid: true, + library_list: false, + show_home: true, + camera: CameraPrefs::default(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn camera_prefs_persist_and_default_when_missing() { + // Missing preferences use their defaults + let old: Prefs = serde_json::from_value(serde_json::json!({"uiScale": 1.25})).unwrap(); + assert_eq!(old.camera, CameraPrefs::default()); + assert_eq!(old.ui_scale, 1.25); + assert!(old.snap_to_grid); + let p = Prefs { camera: CameraPrefs { pan_limit: 8.0, pan_speed: 0.5 }, ..Prefs::default() }; + let v = serde_json::to_value(&p).unwrap(); + assert_eq!(v["camera"], serde_json::json!({"panLimit": 8.0, "panSpeed": 0.5})); + assert_eq!(serde_json::from_value::<Prefs>(v).unwrap(), p); + } +} diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs new file mode 100644 index 00000000..a124b356 --- /dev/null +++ b/crates/ui-egui/src/state/ui_state.rs @@ -0,0 +1,68 @@ +use serde::{Deserialize, Serialize}; + +use super::{GraphCamera, ImageCamera, Prefs, Windows}; +use crate::docking::Dock; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct UiState { + pub dock: Dock, + pub prefs: Prefs, + pub windows: Windows, + pub graph_camera: GraphCamera, + pub image_camera: ImageCamera, + /// Library: the selected category path ("" = all) and the search text + pub library_category: String, + pub library_search: String, + /// Recently opened or saved packages, newest first + pub recent: Vec<String>, + /// New graph dialog fields + pub new_graph_kind: materialcraft_engine::core::GraphKind, + pub new_graph_template: String, + pub new_graph_name: String, + pub new_graph_size: u32, + /// Export dialog fields + pub export_dir: String, + pub export_format: String, + pub export_depth: u32, + /// Export size in pixels; 0 = the graph's own size + pub export_size: u32, + pub export_pattern: String, + /// Frame the whole graph on the next frame + #[serde(skip)] + pub frame_all: bool, +} + +impl Default for UiState { + fn default() -> Self { + UiState { + dock: Dock::default(), + prefs: Prefs::default(), + windows: Windows::default(), + graph_camera: GraphCamera::default(), + image_camera: ImageCamera::default(), + library_category: String::new(), + library_search: String::new(), + recent: Vec::new(), + new_graph_kind: materialcraft_engine::core::GraphKind::Material, + new_graph_template: "pbr".into(), + new_graph_name: "New_graph".into(), + new_graph_size: 1024, + export_dir: String::new(), + export_format: "png".into(), + export_depth: 0, + export_size: 0, + export_pattern: "$(graph)_$(identifier)".into(), + frame_all: true, + } + } +} + +impl UiState { + /// Remember `path` at the top of the recent list + pub fn add_recent(&mut self, path: &str) { + self.recent.retain(|p| p != path); + self.recent.insert(0, path.to_string()); + self.recent.truncate(12); + } +} diff --git a/crates/ui-egui/src/state/windows.rs b/crates/ui-egui/src/state/windows.rs new file mode 100644 index 00000000..c7cce011 --- /dev/null +++ b/crates/ui-egui/src/state/windows.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; + +/// Which dialogs are open +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Windows { + pub new_graph: bool, + pub export: bool, + pub about: bool, + pub preferences: bool, + pub shortcuts: bool, + pub home: bool, +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index cf513196..9b16b401 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,24 +1,20 @@ -//! Textures for node thumbnails (from cooked outputs) and the library's node previews (each node -//! cooked at a small size on sample inputs: the library pictures are made by MaterialCraft itself, -//! no icon files). - use std::collections::{BTreeMap, HashMap}; use std::sync::mpsc::Receiver; use egui::{ColorImage, TextureHandle, TextureOptions}; use materialcraft_engine::image::{Image, Kind}; -use materialcraft_engine::nodes::{Ctx, catalog, resolve_params}; +use materialcraft_engine::nodes::{CookContext, catalog, resolve_params}; -/// Rendered previews by id: (id, RGBA8 pixels). +/// Rendered previews by id: (id, RGBA8 pixels) pub type Previews = Vec<(String, Vec<u8>)>; -/// Side of node thumbnails and library previews, in pixels. +/// Side of node thumbnails and library previews, in pixels pub const THUMB: u32 = 96; -const LIB: u32 = 72; +const LIBRARY_PREVIEW_SIZE: u32 = 72; #[derive(Default)] pub struct Thumbs { - /// (cook key, port) → texture and the frame it was last used. + /// (cook key, port) → texture and the frame it was last used nodes: HashMap<(u64, usize), (TextureHandle, u64)>, library: HashMap<String, TextureHandle>, library_rx: Option<Receiver<Previews>>, @@ -26,14 +22,18 @@ pub struct Thumbs { frame: u64, } -/// An image as an egui texture image (sRGB display, `side` px). +/// An image as an egui texture image (sRGB display, `side` px) pub fn color_image(img: &Image, side: u32) -> ColorImage { let small = img.resize(side, side, true); ColorImage::from_rgba_unmultiplied([side as usize, side as usize], &small.to_rgba8_display()) } impl Thumbs { - /// The thumbnail of a node output, uploaded on first use. + pub fn clear_nodes(&mut self) { + self.nodes.clear(); + } + + /// The thumbnail of a node output, uploaded on first use pub fn node(&mut self, ctx: &egui::Context, key: u64, port: usize, img: &Image) -> egui::TextureId { let frame = self.frame; if let Some((t, f)) = self.nodes.get_mut(&(key, port)) { @@ -46,7 +46,7 @@ impl Thumbs { id } - /// Once per frame: forget thumbnails unused for a few seconds; collect library previews. + /// Once per frame: forget thumbnails unused for a few seconds; collect library previews pub fn tick(&mut self, ctx: &egui::Context) { self.frame += 1; let f = self.frame; @@ -57,14 +57,14 @@ impl Thumbs { && let Ok(list) = rx.try_recv() { for (id, rgba) in list { - let img = ColorImage::from_rgba_unmultiplied([LIB as usize, LIB as usize], &rgba); - self.library.insert(id.clone(), ctx.load_texture(format!("lib-{id}"), img, TextureOptions::LINEAR)); + let img = ColorImage::from_rgba_unmultiplied([LIBRARY_PREVIEW_SIZE as usize, LIBRARY_PREVIEW_SIZE as usize], &rgba); + self.library.insert(id.clone(), ctx.load_texture(format!("library-{id}"), img, TextureOptions::LINEAR)); } self.library_rx = None; } } - /// The library preview of node `def` (generated in the background on first use). + /// The library preview of node `def` (generated in the background on first use) pub fn library(&mut self, ctx: &egui::Context, def: &str) -> Option<egui::TextureId> { if !self.library_started { self.library_started = true; @@ -74,9 +74,11 @@ impl Thumbs { } } -/// Sample inputs for previews: a cloud height, a colored version and its normal map. +/// Sample inputs for previews: a wave height, a colored version and its normal map fn sample_inputs() -> (Image, Image, Image) { - let gray = Image::generate_uv(LIB, LIB, Kind::Gray, |u, v| [materialcraft_engine::nodes::noise::fbm(u, v, 3.0, 5, 0.5, 11), 0.0, 0.0, 0.0]); + let gray = Image::generate_uv(LIBRARY_PREVIEW_SIZE, LIBRARY_PREVIEW_SIZE, Kind::Gray, |u, v| { + [0.5 + 0.25 * (u * std::f32::consts::TAU).sin() + 0.25 * (v * std::f32::consts::TAU).cos(), 0.0, 0.0, 0.0] + }); let color = gray.map(Kind::Color, |p| [0.15 + 0.7 * p[0], 0.35 + 0.3 * p[0], 0.8 - 0.5 * p[0], 1.0]); let normal = materialcraft_engine::nodes::atomic::height_to_normal(&gray, 4.0, false, true, false); (gray, color, normal) @@ -96,7 +98,7 @@ fn previews() -> Previews { .iter() .enumerate() .map(|(i, p)| { - // Masks and secondary inputs stay empty so the main effect shows. + // Masks and secondary inputs stay empty so the main effect shows if i > 0 && !matches!(def.id, "blend" | "height_blend" | "normal_blend" | "rgba_merge") { return None; } @@ -112,11 +114,20 @@ fn previews() -> Previews { }) .collect(); let params = resolve_params(def, &BTreeMap::new()); - let ctx = Ctx { w: LIB, h: LIB, seed: 3, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + let ctx = CookContext { + w: LIBRARY_PREVIEW_SIZE, + h: LIBRARY_PREVIEW_SIZE, + seed: 3, + tile: true, + inputs: &inputs, + params: ¶ms, + resource: &no_res, + vars: &vars, + }; if let Ok(imgs) = (def.cook)(&ctx) && let Some(img) = imgs.first() { - out.push((def.id.to_string(), img.resize(LIB, LIB, true).to_rgba8_display())); + out.push((def.id.to_string(), img.resize(LIBRARY_PREVIEW_SIZE, LIBRARY_PREVIEW_SIZE, true).to_rgba8_display())); } } out diff --git a/crates/ui-egui/src/toast.rs b/crates/ui-egui/src/toast.rs new file mode 100644 index 00000000..2c7475e9 --- /dev/null +++ b/crates/ui-egui/src/toast.rs @@ -0,0 +1,30 @@ +use crate::{MaterialCraftApp, theme}; + +pub struct Toast { + pub text: String, + pub error: bool, + pub until: f64, +} + +pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { + if app.toasts.is_empty() { + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + let tk = theme::Tokens::get(ctx); + egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| { + for t in &app.toasts { + egui::Frame::NONE + .fill(tk.panel) + .stroke(egui::Stroke::new(1.0, if t.error { tk.danger } else { tk.accent })) + .corner_radius(theme::CARD_RADIUS) + .shadow(ui.visuals().popup_shadow) + .inner_margin(egui::Margin::symmetric(10, 6)) + .show(ui, |ui| { + ui.set_max_width(380.0); + ui.label(egui::RichText::new(&t.text).color(tk.text_strong)); + }); + ui.add_space(4.0); + } + }); +} diff --git a/crates/ui-egui/src/user_directory.rs b/crates/ui-egui/src/user_directory.rs new file mode 100644 index 00000000..2a5fc2fb --- /dev/null +++ b/crates/ui-egui/src/user_directory.rs @@ -0,0 +1,6 @@ +/// `Documents/MaterialCraft/<sub>` in the user's home folder +#[cfg(not(target_arch = "wasm32"))] +pub fn user_dir(sub: &str) -> std::path::PathBuf { + let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into()); + std::path::Path::new(&home).join("Documents").join("MaterialCraft").join(sub) +} diff --git a/crates/ui-egui/src/value_editor.rs b/crates/ui-egui/src/value_editor.rs new file mode 100644 index 00000000..575a9b4c --- /dev/null +++ b/crates/ui-egui/src/value_editor.rs @@ -0,0 +1,57 @@ +use egui::Ui; +use materialcraft_engine::core::Value; + +/// Edit a function value within the available width +pub(crate) fn show(ui: &mut Ui, value: &mut Value) -> bool { + ui.horizontal_wrapped(|ui| match value { + Value::Float(value) => float(ui, value, "Value"), + Value::Float2(values) => floats(ui, values, &["X", "Y"]), + Value::Float3(values) => floats(ui, values, &["X", "Y", "Z"]), + Value::Float4(values) => floats(ui, values, &["X", "Y", "Z", "W"]), + Value::Color(values) => floats(ui, values, &["Red", "Green", "Blue", "Alpha"]), + Value::Int(value) => integer(ui, value, "Value"), + Value::Int2(values) => integers(ui, values), + Value::Int3(values) => integers(ui, values), + Value::Int4(values) => integers(ui, values), + Value::Bool(value) => { + let response = ui.checkbox(value, ""); + crate::widgets::name(&response, egui::Role::CheckBox, "Value"); + response.changed() + } + Value::Text(value) => { + let response = ui.add(egui::TextEdit::singleline(value).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, "Value"); + response.changed() + } + _ => false, + }) + .inner +} + +fn float(ui: &mut Ui, value: &mut f32, label: &str) -> bool { + let response = ui.add(egui::DragValue::new(value).speed(0.01).max_decimals(3)); + crate::widgets::name(&response, egui::Role::SpinButton, label); + response.changed() +} + +fn floats(ui: &mut Ui, values: &mut [f32], labels: &[&str]) -> bool { + let mut changed = false; + for (value, label) in values.iter_mut().zip(labels) { + changed |= float(ui, value, label); + } + changed +} + +fn integer(ui: &mut Ui, value: &mut i32, label: &str) -> bool { + let response = ui.add(egui::DragValue::new(value).speed(0.1)); + crate::widgets::name(&response, egui::Role::SpinButton, label); + response.changed() +} + +fn integers(ui: &mut Ui, values: &mut [i32]) -> bool { + let mut changed = false; + for (value, label) in values.iter_mut().zip(["X", "Y", "Z", "W"]) { + changed |= integer(ui, value, label); + } + changed +} diff --git a/crates/ui-egui/src/value_input_editor.rs b/crates/ui-egui/src/value_input_editor.rs new file mode 100644 index 00000000..356a5adf --- /dev/null +++ b/crates/ui-egui/src/value_input_editor.rs @@ -0,0 +1,54 @@ +use egui::Ui; +use materialcraft_engine::core::{Node, ValueType}; +use serde_json::json; + +use crate::MaterialCraftApp; + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, node: &Node) { + ui.collapsing("Value inputs", |ui| { + for (identifier, value_type) in &node.input_values { + ui.horizontal(|ui| { + ui.label(materialcraft_engine::eval::value_input_label(identifier)); + ui.label(value_type.label()); + + if ui.small_button("Remove").clicked() { + app.run("graph.node.value_input", json!({"id": node.id.0, "name": identifier, "remove": true})); + } + }); + } + + ui.menu_button("Add value input", |ui| { + for value_type in ValueType::ALL { + if ui.button(value_type.label()).clicked() { + let name = (1..=65).map(|index| format!("value{index}")).find(|name| !node.input_values.contains_key(name)); + + if let Some(name) = name { + app.run("graph.node.value_input", json!({"id": node.id.0, "name": name, "type": value_type.label()})); + } + + ui.close(); + } + } + }); + }); +} + +pub(crate) fn default_value(app: &mut MaterialCraftApp, ui: &mut Ui, node: &Node) { + use materialcraft_engine::core::Value; + let mut value = node.params.get("default").cloned().unwrap_or(Value::Float(0.0)); + let mut kind = ValueType::of(&value).unwrap_or(ValueType::Float); + let before = kind; + egui::ComboBox::from_label("Value type").selected_text(kind.label()).show_ui(ui, |ui| { + for candidate in ValueType::ALL { + ui.selectable_value(&mut kind, candidate, candidate.label()); + } + }); + let mut changed = kind != before; + if changed { + value = kind.default_value(); + } + changed |= crate::value_editor::show(ui, &mut value); + if changed { + app.run("graph.node.param", json!({"id": node.id.0, "param": "default", "value": value})); + } +} diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index cc52172c..7b6a625e 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -33,7 +33,7 @@ fn histogram(px: &[u8], channels: usize) -> Vec<[u32; BINS]> { } pub fn title(app: &MaterialCraftApp) -> String { - let name = app.session.view2d_image().and_then(|(id, _)| app.session.graph().ok()?.node(id).ok().map(crate::graph_view::node_label)); + let name = app.session.view2d_image().and_then(|(id, _)| app.session.graph().ok()?.node(id).ok().map(crate::graph::node_label)); format!("{} - {}", name.unwrap_or_default(), tr("2D View")) } @@ -223,7 +223,7 @@ fn draw_histogram(st: &mut View2dState, p: &egui::Painter, rect: Rect, key: u64, #[cfg(not(target_arch = "wasm32"))] fn save_image(app: &mut MaterialCraftApp) { let Some((id, img)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else { return }; - let name = app.session.graph().ok().and_then(|g| g.node(id).ok().map(crate::graph_view::node_label)).unwrap_or_else(|| "image".into()); + let name = app.session.graph().ok().and_then(|g| g.node(id).ok().map(crate::graph::node_label)).unwrap_or_else(|| "image".into()); let Some(path) = rfd::FileDialog::new() .set_file_name(format!("{name}.png")) .add_filter("PNG", &["png"]) diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index f33e7b04..ff96e0b5 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -1,13 +1,9 @@ -//! Files in the browser: File ▸ Open and Import bitmap use the browser's file picker (the bytes -//! arrive on a later frame through [`poll`]); Save and Export outputs are downloads. The desktop -//! uses native dialogs and the path-based engine commands instead (`windows::file_action`). - use std::sync::{Mutex, PoisonError}; use crate::MaterialCraftApp; use crate::i18n::tr; -/// What a picked file is for. +/// What a picked file is for #[derive(Clone, Copy, PartialEq)] #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] enum Pick { @@ -16,10 +12,10 @@ enum Pick { Mesh, } -/// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose). +/// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose) static INBOX: Mutex<Vec<(String, Vec<u8>, Pick)>> = Mutex::new(Vec::new()); -/// Load files that arrived since the last frame. Call once per frame. +/// Load files that arrived since the last frame. Call once per frame pub fn poll(app: &mut MaterialCraftApp) { let picked = std::mem::take(&mut *INBOX.lock().unwrap_or_else(PoisonError::into_inner)); for (name, bytes, pick) in picked { @@ -31,7 +27,7 @@ pub fn poll(app: &mut MaterialCraftApp) { } } -/// Show a mesh file's bytes in the 3D view. +/// Show a mesh file's bytes in the 3D view fn mesh(app: &mut MaterialCraftApp, name: &str, bytes: &[u8]) { match app.session.load_mesh_bytes(name, bytes) { Ok(()) => app.toast(format!("{} {name}", tr("Showing")), false), @@ -39,7 +35,7 @@ fn mesh(app: &mut MaterialCraftApp, name: &str, bytes: &[u8]) { } } -/// 3D view ▸ Scene ▸ Load mesh: a native dialog on the desktop, the file picker in the browser. +/// 3D view ▸ Scene ▸ Load mesh: a native dialog on the desktop, the file picker in the browser pub fn load_mesh(app: &mut MaterialCraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { @@ -55,7 +51,7 @@ pub fn load_mesh(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } -/// Open a package or import an image (by extension unless `bitmap` forces an image). +/// Open a package or import an image (by extension unless `bitmap` forces an image) pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool) { let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); if materialcraft_engine::formats::mesh::MESH_EXTENSIONS.contains(&ext.as_str()) { @@ -65,7 +61,7 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool if bitmap || materialcraft_engine::formats::IMAGE_EXTENSIONS.contains(&ext.as_str()) { match materialcraft_engine::file_cmds::add_resource(&mut app.session, name, bytes, None) { Ok(res) => { - crate::graph_view::add_node_near_selection(app, "bitmap"); + crate::graph::add_node_near_selection(app, "bitmap"); if let Some(id) = app.session.selection.last().copied() { app.run("graph.node.param", serde_json::json!({"id": id.0, "param": "resource", "value": res})); } @@ -77,6 +73,7 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool } match materialcraft_engine::file_cmds::open_bytes(&mut app.session, &bytes, Some(name.to_string())) { Ok(()) => { + app.close_subgraph_after("file.open"); app.ui.frame_all = true; app.toast(format!("{} {name}", tr("Opened")), false); crate::windows::after_open(app); @@ -85,16 +82,15 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool } } -/// A file dropped on the window: a package opens, an image becomes a Bitmap node (in the -/// browser the bytes arrive on a later frame). +/// A file dropped on the window: a package opens, an image becomes a Bitmap node (in the browser the bytes arrive on a later frame) pub fn dropped(app: &mut MaterialCraftApp, ctx: &egui::Context, file: &egui::DroppedFileHandle) { let name = file.path().file_name().and_then(|n| n.to_str()).unwrap_or("dropped").to_string(); #[cfg(not(target_arch = "wasm32"))] { let _ = ctx; let lower = name.to_ascii_lowercase(); - if (lower.ends_with(".sbs") || lower.ends_with(".mcraft")) && file.path().is_file() { - // Open from the path so an SBS package finds the bitmaps kept next to it. + if lower.ends_with(".sbs") && file.path().is_file() { + // Open from the path so an SBS package finds the bitmaps kept next to it crate::windows::open_path(app, &file.path().display().to_string()); return; } @@ -117,7 +113,7 @@ pub fn dropped(app: &mut MaterialCraftApp, ctx: &egui::Context, file: &egui::Dro } } -/// A zip of `(name, bytes)` files (export downloads several maps at once). +/// A zip of `(name, bytes)` files (export downloads several maps at once) pub fn zip_files(files: &[(String, Vec<u8>)]) -> Result<Vec<u8>, String> { use std::io::Write as _; let mut buf = std::io::Cursor::new(Vec::new()); @@ -157,22 +153,22 @@ mod web { }); } - /// File ▸ Open: a package, picked in the browser. + /// File ▸ Open: a package, picked in the browser pub fn open(ctx: &egui::Context) { pick(ctx, "MaterialCraft package or material", crate::windows::OPEN_EXTS, Pick::Package); } - /// 3D view ▸ Scene ▸ Load mesh. + /// 3D view ▸ Scene ▸ Load mesh pub fn pick_mesh(ctx: &egui::Context) { pick(ctx, "Meshes", materialcraft_engine::formats::mesh::MESH_EXTENSIONS, Pick::Mesh); } - /// File ▸ Import bitmap. + /// File ▸ Import bitmap pub fn import_bitmap(ctx: &egui::Context) { pick(ctx, "Images", materialcraft_engine::formats::IMAGE_EXTENSIONS, Pick::Bitmap); } - /// File ▸ Save: download the package as `<name>.sbs` (bitmaps embedded). + /// File ▸ Save: download the package as `<name>.sbs` (bitmaps embedded) pub fn save(app: &mut MaterialCraftApp) { let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); match materialcraft_engine::file_cmds::save_bytes(&app.session).map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { @@ -184,7 +180,7 @@ mod web { } } - /// File ▸ Export material: download the open graph as `<graph>.mcmat`. + /// File ▸ Export material: download the open graph as `<graph>.mcmat` pub fn export_material(app: &mut MaterialCraftApp) { use materialcraft_engine::material_cmds::{MaterialOptions, material_bytes}; let name = format!("{}.mcmat", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default())); @@ -194,7 +190,7 @@ mod web { } } - /// Export outputs: one file downloads as is, several as `<graph>_outputs.zip`. + /// Export outputs: one file downloads as is, several as `<graph>_outputs.zip` pub fn export(app: &mut MaterialCraftApp, params: &serde_json::Value) { let result = materialcraft_engine::file_cmds::export_params(&app.session, params) .and_then(|(gi, ext, pattern, depth, size)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth, size)) @@ -215,7 +211,7 @@ mod web { } } - /// Start a browser download of `bytes` named `name` (Blob + a temporary `<a download>`). + /// Start a browser download of `bytes` named `name` (Blob + a temporary `<a download>`) pub fn download(name: &str, bytes: &[u8]) -> Result<(), String> { let js = |e: wasm_bindgen::JsValue| format!("{e:?}"); let window = web_sys::window().ok_or("no window")?; @@ -232,7 +228,7 @@ mod web { document.body().ok_or("no body")?.append_child(&a).map_err(js)?; a.click(); a.remove(); - // Revoke once the click has been dispatched; the download keeps its own reference. + // Revoke once the click has been dispatched; the download keeps its own reference let revoke = wasm_bindgen::closure::Closure::once_into_js(move || { web_sys::Url::revoke_object_url(&url).ok(); }); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 6ade5c3f..b5c356f9 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,13 +1,12 @@ -//! Dialogs (new graph, export outputs, preferences, shortcuts, about, home), the console and -//! history panels, file actions behind the File menu, and the function editor. +//! Dialogs (new graph, export outputs, preferences, shortcuts, about, home), the console and history panels, file actions behind the File menu, and the function editor use std::collections::HashMap; use std::sync::mpsc::Receiver; use egui::{Color32, RichText, TextureHandle, Ui, vec2}; use egui_phosphor::regular as icon; +use materialcraft_engine::core::FunctionGraph; use materialcraft_engine::core::NodeId; -use materialcraft_engine::core::function::FnGraph; use materialcraft_engine::formats::material::MATERIAL_EXT; use serde_json::{Value, json}; @@ -15,7 +14,7 @@ use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::{Accent, Brightness, Tokens}; -/// Template previews for the New graph dialog (rendered in the background on first open). +/// Template previews for the New graph dialog (rendered in the background on first open) #[derive(Default)] pub struct TemplatePreviews { tex: HashMap<String, TextureHandle>, @@ -31,13 +30,13 @@ fn render_templates() -> crate::thumbs::Previews { let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, height_scale: 0.0, ..Default::default() }; materialcraft_engine::samples::TEMPLATES .iter() - .map(|(id, _)| { + .filter_map(|(id, _)| { let mut s = materialcraft_engine::Session::new(materialcraft_engine::core::Package::new("t")); - s.pkg.graphs.push(materialcraft_engine::samples::template(id, "t", 8)); + s.pkg.graphs.push(materialcraft_engine::samples::template(id, "t", 8).ok()?); s.preview_size = Some(256); s.cook(); let maps = materialcraft_render::Maps::from_usages(s.material_maps()); - (id.to_string(), materialcraft_render::render(&scene, &maps, &light, &settings, PREVIEW, PREVIEW)) + Some((id.to_string(), materialcraft_render::render(&scene, &maps, &light, &settings, PREVIEW, PREVIEW))) }) .collect() } @@ -111,81 +110,52 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui } fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) { + use materialcraft_engine::core::GraphKind; + let mut open = true; let mut create = false; - modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(640.0, 490.0), |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width(400.0); - ui.label(RichText::new(tr("Templates")).strong()); - // Three rows of templates without scrolling. - egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| { - for row in materialcraft_engine::samples::TEMPLATES.chunks(4) { - ui.horizontal(|ui| { - for (id, label) in row { - let on = app.ui.new_graph_template == *id; - let (r, resp) = ui.allocate_exact_size(vec2(94.0, 124.0), egui::Sense::click()); - crate::widgets::name(&resp, egui::Role::ListItem, label); - if on { - ui.painter().rect_filled(r, 6.0, tk.row_selected); - ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Inside); - } else if resp.hovered() { - ui.painter().rect_filled(r, 6.0, tk.row_hover); - } - let img = egui::Rect::from_min_size(r.min + vec2(7.0, 6.0), vec2(80.0, 80.0)); - match TEMPLATES.with(|t| t.borrow_mut().get(ui.ctx(), id)) { - Some(t) => { - ui.painter().image(t, img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); - } - None => { - ui.painter().circle_filled(img.center(), 36.0, tk.row); - } - } - let g = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tk.text, 90.0); - ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text); - if resp.clicked() { - app.ui.new_graph_template = id.to_string(); - app.ui.new_graph_name = label.replace(' ', "_"); - } - if resp.double_clicked() { - create = true; - } - } - }); - } - }); + modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(440.0, 290.0), |ui| { + ui.horizontal(|ui| { + ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Material, tr("Graph")); + ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Function, tr("Function Graph")); + }); + ui.add_space(12.0); + ui.label(tr("Graph name")); + let name = ui.text_edit_singleline(&mut app.ui.new_graph_name); + crate::widgets::name(&name, egui::Role::TextInput, "Graph name"); + + if app.ui.new_graph_kind == GraphKind::Material { + ui.add_space(8.0); + crate::widgets::combo(ui, tr("Template"), app.ui.new_graph_template.clone(), |ui| { + for (id, label) in materialcraft_engine::samples::TEMPLATES { + ui.selectable_value(&mut app.ui.new_graph_template, id.to_string(), tr(label)); + } }); - ui.separator(); - ui.vertical(|ui| { - ui.label(RichText::new(tr("Graph name")).strong()); - ui.text_edit_singleline(&mut app.ui.new_graph_name); - ui.add_space(8.0); - ui.label(RichText::new(tr("Size")).strong()); - let r = egui::ComboBox::from_id_salt("new-size").selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| { - for s in [256u32, 512, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_graph_size, s, format!("{s} px")); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Size"); - ui.add_space(8.0); - ui.label(RichText::new(tr("Create graph in")).strong()); - ui.label(&app.session.pkg.name); - ui.add_space(20.0); - ui.horizontal(|ui| { - if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() { - create = true; - } - if ui.button(tr("Cancel")).clicked() { - app.ui.windows.new_graph = false; - } - }); + let size = egui::ComboBox::from_label(tr("Size")).selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| { + for size in [256u32, 512, 1024, 2048, 4096] { + ui.selectable_value(&mut app.ui.new_graph_size, size, format!("{size} px")); + } }); + crate::widgets::name(&size.response, egui::Role::ComboBox, "Size"); + } + + ui.add_space(12.0); + ui.label(format!("{}: {}", tr("Package"), app.session.pkg.name)); + ui.add_space(16.0); + ui.horizontal(|ui| { + if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() { + create = true; + } + if ui.button(tr("Cancel")).clicked() { + app.ui.windows.new_graph = false; + } }); }); + if create { - let p = json!({"template": app.ui.new_graph_template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size}); - if app.run("file.new", p).is_some() { + let parameters = + json!({"kind": app.ui.new_graph_kind, "template": app.ui.new_graph_template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size}); + if app.run("file.new", parameters).is_some() { app.ui.frame_all = true; open = false; } @@ -392,7 +362,7 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) { modal(ctx, "home", tr("Home"), &mut open, vec2(760.0, 470.0), |ui| { let tk = Tokens::get(ui.ctx()); ui.horizontal_top(|ui| { - // Left rail: actions and links. + // Left rail: actions and links ui.vertical(|ui| { ui.set_width(150.0); if ui.add(crate::widgets::primary_button(ui, tr("New graph"))).clicked() { @@ -510,12 +480,11 @@ pub fn history(app: &mut MaterialCraftApp, ui: &mut Ui) { }); } -/// The function parameter of a pixel/value processor: a button opening the function graph -/// editor, and the function as JSON for copy and paste. -pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, f: &FnGraph) { +/// The function parameter of a pixel/value processor: a button opening the function graph editor, and the function as JSON for copy and paste +pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, f: &FunctionGraph) { let tk = Tokens::get(ui.ctx()); if ui.add(crate::widgets::primary_button(ui, &format!("{} {}", icon::FLOW_ARROW, tr("Edit function graph...")))).clicked() { - app.fn_editor = Some(crate::function_editor::FnEditor::new(node, param)); + app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Parameter(param.to_string()))); } ui.label(RichText::new(format!("{} {}", f.nodes.len(), tr("function nodes"))).size(10.5).color(tk.text_dim)); let id = egui::Id::unique(("fn-edit", node.0, param)); @@ -526,7 +495,7 @@ pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p } ui.horizontal(|ui| { if ui.button(tr("Apply")).clicked() { - match serde_json::from_str::<FnGraph>(&text) { + match serde_json::from_str::<FunctionGraph>(&text) { Ok(g) => { let v = serde_json::to_value(materialcraft_engine::core::Value::Function(Box::new(g))).unwrap_or(Value::Null); app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v})); @@ -542,10 +511,10 @@ pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p }); } -/// Extensions File ▸ Open reads: SBS (the main format) and `.mcraft` packages, and materials (their source package). -pub const OPEN_EXTS: &[&str] = &["sbs", "mcraft", MATERIAL_EXT]; +/// Extensions File ▸ Open reads: SBS packages, and materials (their source package) +pub const OPEN_EXTS: &[&str] = &["sbs", MATERIAL_EXT]; -/// After a package opened with warnings (an SBS file using nodes MaterialCraft lacks, say), bring the Console forward. +/// After a package opened with warnings (an SBS file using nodes MaterialCraft lacks, say), bring the Console forward pub fn after_open(app: &mut MaterialCraftApp) { let warning_count = app.session.load_warnings.len(); if warning_count > 0 { @@ -554,7 +523,7 @@ pub fn after_open(app: &mut MaterialCraftApp) { } } -/// File menu actions that need a file dialog. Returns true when handled. +/// File menu actions that need a file dialog. Returns true when handled pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] let _ = ctx; @@ -577,12 +546,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } "file.save" | "file.saveAs" => { let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); - if let Some(p) = rfd::FileDialog::new() - .set_file_name(name) - .add_filter("SBS package", &["sbs"]) - .add_filter("MaterialCraft package (older format)", &["mcraft"]) - .save_file() - { + if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("SBS package", &["sbs"]).save_file() { let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string()); if app.run("file.save", json!({"path": path})).is_some() { app.ui.add_recent(&path); @@ -614,7 +578,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> && let Some(r) = app.run("file.importBitmap", json!({"path": p.display().to_string()})) { let name = r["name"].as_str().unwrap_or_default().to_string(); - crate::graph_view::add_node_near_selection(app, "bitmap"); + crate::graph::add_node_near_selection(app, "bitmap"); if let Some(id) = app.session.selection.last().copied() { app.run("graph.node.param", json!({"id": id.0, "param": "resource", "value": name})); } @@ -637,7 +601,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } } -/// Open a package from a path (recent list, command line). +/// Open a package from a path (recent list, command line) #[cfg(not(target_arch = "wasm32"))] pub fn open_path(app: &mut MaterialCraftApp, path: &str) { if app.run("file.open", json!({"path": path})).is_some() { diff --git a/crates/ui-egui/tests/numeric_input.rs b/crates/ui-egui/tests/numeric_input.rs index ec027f90..5679841d 100644 --- a/crates/ui-egui/tests/numeric_input.rs +++ b/crates/ui-egui/tests/numeric_input.rs @@ -1,4 +1,4 @@ -//! Exact numeric edits must survive intervening frames and reach engine parameters. +//! Exact numeric edits must survive intervening frames and reach engine parameters use egui::{Event, Key, Modifiers, vec2}; use egui_kittest::{ Harness, @@ -47,11 +47,11 @@ fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32 } } #[test] -fn scale_x_commits_on_enter_and_focus_loss_with_undo() { +fn offset_x_commits_on_enter_and_focus_loss_with_undo() { for enter in [true, false] { let (mut h, id) = harness(false); - focus_x(&mut h, 1); - type_text(&mut h, "4"); + focus_x(&mut h, 0); + type_text(&mut h, "0.4"); if enter { h.key_press(Key::Enter); h.step(); @@ -60,13 +60,13 @@ fn scale_x_commits_on_enter_and_focus_loss_with_undo() { h.step(); } h.run_steps(5); - assert_eq!(pair(&h, id, "scale"), [4.0, 1.0], "Scale X did not persist (Enter={enter})"); + assert_eq!(pair(&h, id, "offset"), [0.4, 0.0], "Offset X did not persist (Enter={enter})"); h.state_mut().run("edit.undo", json!({})).unwrap(); h.run_steps(3); - assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]); + assert_eq!(pair(&h, id, "offset"), [0.0, 0.0]); h.state_mut().run("edit.redo", json!({})).unwrap(); h.run_steps(3); - assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + assert_eq!(pair(&h, id, "offset"), [0.4, 0.0]); } } #[test] @@ -80,13 +80,12 @@ fn a_negative_decimal_can_be_typed_across_frames() { h.step(); h.run_steps(4); assert_eq!(pair(&h, id, "offset"), [-0.5, 0.0]); - assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]); } #[test] fn clicking_the_canvas_and_switching_nodes_keep_the_right_values() { let (mut h, id) = harness(false); - focus_x(&mut h, 1); - type_text(&mut h, "4"); + focus_x(&mut h, 0); + type_text(&mut h, "0.4"); let pos = h.state().graph.view.left_top() + vec2(20.0, 20.0); h.event(Event::PointerMoved(pos)); h.step(); @@ -96,17 +95,17 @@ fn clicking_the_canvas_and_switching_nodes_keep_the_right_values() { } h.run_steps(4); assert!(h.state().session.selection.is_empty()); - assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + assert_eq!(pair(&h, id, "offset"), [0.4, 0.0]); h.state_mut().run("graph.select", json!({"ids": [id.0]})).unwrap(); h.run_steps(4); - focus_x(&mut h, 1); - type_text(&mut h, "5"); + focus_x(&mut h, 0); + type_text(&mut h, "0.5"); let other = NodeId(h.state_mut().run("graph.node.add", json!({"def":"transformation","at":[300,0]})).unwrap()["id"].as_u64().unwrap()); h.run_steps(4); h.key_press(Key::Enter); h.step(); - assert_eq!(pair(&h, id, "scale"), [5.0, 1.0]); - assert_eq!(pair(&h, other, "scale"), [1.0, 1.0], "an edit leaked into the newly selected node"); + assert_eq!(pair(&h, id, "offset"), [0.5, 0.0]); + assert_eq!(pair(&h, other, "offset"), [0.0, 0.0], "an edit leaked into the newly selected node"); } #[test] @@ -158,15 +157,15 @@ fn integer_input_and_slider_track_both_update_the_node() { #[test] #[ignore = "requires an offscreen GPU"] -fn exact_scale_screenshot() { +fn exact_offset_screenshot() { let (mut h, id) = harness(true); - focus_x(&mut h, 1); - type_text(&mut h, "4"); + focus_x(&mut h, 0); + type_text(&mut h, "0.4"); h.key_press(Key::Enter); h.step(); h.run_steps(8); - assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]); + assert_eq!(pair(&h, id, "offset"), [0.4, 0.0]); let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("scale-x-4.png")).unwrap(); + h.render().unwrap().save(dir.join("offset-x-4.png")).unwrap(); } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 33cae147..e9108890 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1,13 +1,9 @@ -//! Offscreen renders of the real UI (no window): `MC_SNAPSHOT_DIR=<dir> cargo test -p -//! materialcraft-ui-egui --release --test snapshot -- --ignored --nocapture` writes PNGs of a few -//! scenes. Used to check UI changes visually and to make the README screenshots. - use std::time::Duration; use egui::vec2; use egui_kittest::{ Harness, - kittest::{By, Queryable}, + kittest::{By, NodeT, Queryable}, }; use materialcraft_ui_egui::{MaterialCraftApp, UiState}; use serde_json::json; @@ -22,7 +18,7 @@ fn harness(app: MaterialCraftApp, w: f32, h: f32) -> Harness<'static, MaterialCr ) } -/// Run frames until background work (cooks, previews) settles. +/// Run frames until background work (cooks, previews) settles fn settle(h: &mut Harness<'static, MaterialCraftApp>, frames: usize) { for _ in 0..frames { h.step(); @@ -57,7 +53,7 @@ fn explorer_export_opens_the_clicked_graph() { } } -/// The startup graph stays empty through real UI frames; templates are still available on demand. +/// The startup graph stays empty through real UI frames; templates are still available on demand #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn empty_startup_can_create_a_template() { @@ -73,7 +69,7 @@ fn empty_startup_can_create_a_template() { } h.get_by_label("New graph...").click(); settle(&mut h, 4); - h.get_by_label("Brick wall").click(); + h.get_by_label("Atomic sample").click(); settle(&mut h, 4); h.get_by_label("Create").click(); settle(&mut h, 40); @@ -96,29 +92,21 @@ fn snapshots() { let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); let mut h = harness(app, 1600.0, 960.0); settle(&mut h, 40); - // Select a node so the properties panel shows parameters. + // Select a node so the properties panel shows parameters let id = h.state().session.graph().unwrap().nodes[0].id; h.state_mut().run("graph.select", json!({"ids": [id.0]})); - h.state_mut().run("view.2d", json!({"node": 16, "histogram": true})); + let preview = h.state().session.graph().unwrap().nodes.iter().find(|node| node.def == "blur").unwrap().id; + h.state_mut().run("view.2d", json!({"node": preview.0, "histogram": true})); settle(&mut h, 30); save(&mut h, &dir, "workspace"); - for (tpl, name) in - [("wood", "wood"), ("rusty_metal", "rusty-metal"), ("stone_tiles", "stone-tiles"), ("fabric", "fabric"), ("ground", "ground"), ("lava", "lava")] - { - h.state_mut().run("file.new", json!({"template": tpl, "size": 1024})); - h.state_mut().ui.frame_all = true; - settle(&mut h, 40); - save(&mut h, &dir, name); - } h.state_mut().ui.windows.new_graph = true; settle(&mut h, 40); save(&mut h, &dir, "new-graph"); h.state_mut().ui.windows.new_graph = false; - // A cut-out material in the 3D view (an opacity output), a reroute dot pulled out of a wire - // and another wire selected; then the alpha channel view. - h.state_mut().run("file.new", json!({"template": "wood", "size": 512})); - let holes = h.state_mut().run("graph.node.add", json!({"def": "grid_lines", "at": [0, -260]})).unwrap()["id"].as_u64().unwrap(); + // A cut-out material in the 3D view (an opacity output), a reroute dot pulled out of a wire and another wire selected; then the alpha channel view + h.state_mut().run("file.new", json!({"template": "atomics", "size": 512})); + let holes = h.state_mut().run("graph.node.add", json!({"def": "pixel_processor", "at": [0, -260]})).unwrap()["id"].as_u64().unwrap(); let out = h.state_mut().run("graph.node.add", json!({"def": "output", "at": [420, -260], "connectFrom": {"node": holes}, "params": {"usage": 7}})).unwrap() ["id"] .as_u64() @@ -135,57 +123,58 @@ fn snapshots() { save(&mut h, &dir, "alpha-channel"); h.state_mut().run("view.3d", json!({"alphaView": false, "scene": "rounded_cube"})); - // A pixel processor drawing rings, with its function graph open. + // A pixel processor drawing rings, with its function graph open h.state_mut().run("file.new", json!({"template": "empty", "name": "Rings"})); let f = json!({"t": "function", "v": {"nodes": [ - {"id": 1, "op": "get_pos", "pos": [0, 0]}, + {"id": 1, "op": "get_float2", "value": {"t": "text", "v": "$pos"}, "pos": [0, 0]}, {"id": 2, "op": "const_float2", "value": {"t": "float2", "v": [0.5, 0.5]}, "pos": [0, 110]}, {"id": 3, "op": "sub", "inputs": [1, 2], "pos": [170, 40]}, - {"id": 4, "op": "length", "inputs": [3], "pos": [340, 40]}, - {"id": 5, "op": "const_float", "value": {"t": "float", "v": 60.0}, "pos": [340, 130]}, + {"id": 8, "op": "dot", "inputs": [3, 3], "pos": [340, 40]}, + {"id": 4, "op": "sqrt", "inputs": [8], "pos": [340, -80]}, + {"id": 5, "op": "const_float1", "value": {"t": "float", "v": 60.0}, "pos": [340, 130]}, {"id": 6, "op": "mul", "inputs": [4, 5], "pos": [510, 60]}, {"id": 7, "op": "sin", "inputs": [6], "pos": [680, 60]} ], "output": 7}}); - let id = h.state_mut().run("graph.node.add", json!({"def": "pixel_processor", "at": [0, 0], "params": {"output": 1}})).unwrap()["id"].as_u64().unwrap(); + let id = + h.state_mut().run("graph.node.add", json!({"def": "pixel_processor", "at": [0, 0], "params": {"color_mode": false}})).unwrap()["id"].as_u64().unwrap(); h.state_mut().run("graph.node.param", json!({"id": id, "param": "function", "value": f})); let out = h.state_mut().run("graph.node.add", json!({"def": "output", "connectFrom": {"node": id}, "params": {"usage": 4}})).unwrap()["id"].as_u64().unwrap(); let _ = out; h.state_mut().run("graph.select", json!({"ids": [id]})); h.state_mut().run("view.2d", json!({"node": id})); - h.state_mut().fn_editor = Some(materialcraft_ui_egui::function_editor::FnEditor::new(materialcraft_engine::core::NodeId(id), "function")); + h.state_mut().function_editor = Some(materialcraft_ui_egui::function::FunctionEditor::new( + materialcraft_engine::core::NodeId(id), + materialcraft_ui_egui::function::FunctionTarget::Parameter("function".into()), + )); h.state_mut().ui.frame_all = true; settle(&mut h, 40); save(&mut h, &dir, "function-editor"); - h.state_mut().fn_editor = None; + h.state_mut().function_editor = None; - // The Levels editor: the input histogram under the transfer curve, with its handles. - h.state_mut().run("file.new", json!({"template": "stone_tiles", "size": 512})); - let levels = { - let g = h.state().session.graph().unwrap(); - g.nodes.iter().find(|n| n.def == "levels" && g.connections.iter().any(|c| c.to == n.id)).map(|n| n.id.0) - }; - if let Some(id) = levels { - h.state_mut().run("graph.select", json!({"ids": [id]})); - h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_low", "value": 0.3})); - h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_mid", "value": 0.35})); - h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_high", "value": 0.85})); - h.state_mut().run("view.2d", json!({"node": id})); - } + h.state_mut().run("file.newAtomicSample", json!({})).unwrap(); + let input = h.state().session.graph().unwrap().nodes.iter().find(|node| node.def == "pixel_processor").unwrap().id; + let id = h.state_mut().run("graph.node.add", json!({"def": "levels", "connectFrom": {"node": input.0}})).unwrap()["id"].as_u64().unwrap(); + h.state_mut().run("graph.select", json!({"ids": [id]})).unwrap(); + h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_low", "value": 0.3})).unwrap(); + h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_mid", "value": 0.35})).unwrap(); + h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_high", "value": 0.85})).unwrap(); + h.state_mut().run("view.2d", json!({"node": id})).unwrap(); h.state_mut().ui.frame_all = true; settle(&mut h, 40); save(&mut h, &dir, "levels-editor"); - // An SBS file with nodes MaterialCraft doesn't have: placeholders on the canvas, the warnings - // in the Console, which comes forward by itself. - let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs/all_nodes.sbs"); - materialcraft_ui_egui::windows::open_path(h.state_mut(), sample.to_str().unwrap()); + h.state_mut().run("file.newAtomicSample", json!({})); + h.state_mut().ui.frame_all = true; settle(&mut h, 60); - save(&mut h, &dir, "sbs-warnings"); + save(&mut h, &dir, "atomic-sample"); + let pattern = h.state().session.graph().unwrap().nodes.iter().find(|node| node.def == "fx_map").unwrap().id; + h.state_mut().pattern_editor = Some(materialcraft_ui_egui::pattern::PatternEditor::new(h.state().session.graph, pattern)); + settle(&mut h, 20); + save(&mut h, &dir, "pattern-editor"); } -/// Steady-state UI build time per frame with each panel closed in turn (release): -/// `cargo test -p materialcraft-ui-egui --release --test snapshot perf -- --ignored --nocapture`. +/// Steady-state UI build time per frame with each panel closed in turn (release): `cargo test -p materialcraft-ui-egui --release --test snapshot perf -- --ignored --nocapture` #[test] #[ignore] fn perf() { @@ -209,3 +198,382 @@ fn perf() { settle(&mut h, 3); } } + +#[test] +#[ignore = "requires an offscreen GPU"] +fn graph_context_menu_has_flat_node_list() { + let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 8); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Input Value")).click_secondary(); + settle(&mut harness, 3); + let directory = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from); + if let Some(directory) = &directory { + std::fs::create_dir_all(directory).unwrap(); + save(&mut harness, directory, "graph-context-menu"); + } + + for label in [ + "Add Comment", + "Add Frame", + "Add Navigation pin", + "Add Dot node", + "View outputs in 3D view", + "Reset and view outputs in 3D view", + "View output in 2D view", + "Compute nodes thumbnails", + "Clear nodes thumbnails", + "Save package", + "Paste without link", + "Previous pin", + "Next pin", + "Delete and relink", + "Duplicate selection without link", + "Select upstream nodes", + "Select downstream nodes", + "Disable selection", + ] { + assert!(harness.query_all(By::new().label_contains(label)).next().is_some(), "missing {label}"); + } + + harness.get_by_label("Add node").click(); + settle(&mut harness, 3); + harness.key_press(egui::Key::S); + settle(&mut harness, 3); + let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); + assert!(!harness.get_all(button("SVG")).last().unwrap().accesskit_node().is_disabled()); + assert!(!harness.get_all(button("Sharpen")).last().unwrap().accesskit_node().is_disabled()); + assert!(harness.get_all(button("Grayscale Conversion")).last().unwrap().accesskit_node().is_disabled()); + if let Some(directory) = &directory { + save(&mut harness, directory, "flat-add-node-menu"); + } + + let before_clear = harness.state().session.pkg.clone(); + harness.key_press(egui::Key::Backspace); + settle(&mut harness, 3); + assert!(!harness.get_all(button("Grayscale Conversion")).last().unwrap().accesskit_node().is_disabled()); + assert_eq!(harness.state().session.pkg, before_clear); + + for _ in 0..2 { + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + } + let graph = harness.state().session.graph().unwrap(); + let selected = graph.nodes.iter().find(|node| node.def == "fx_map").unwrap().id; + let other = graph.nodes.iter().find(|node| node.def != "fx_map").unwrap().id; + harness.state_mut().run("graph.select", json!({"ids": [selected.0, other.0]})); + harness.state_mut().ui.frame_all = true; + settle(&mut harness, 3); + assert!(harness.query_all(By::new().label("Edit FX-Map graph")).next().is_none()); + let position = harness.state().graph.rects.iter().find(|(id, _)| *id == selected).unwrap().1.center(); + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + settle(&mut harness, 3); + if let Some(directory) = &directory { + save(&mut harness, directory, "pattern-node-context-menu"); + } + assert!( + harness.query_all(By::new().label_contains("Edit graph")).next().is_some(), + "selection: {:?}, target: {selected:?}, position: {position:?}", + harness.state().session.selection + ); + assert_eq!(harness.state().session.selection.last(), Some(&selected)); + + harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("Edit graph")).click(); + settle(&mut harness, 3); + assert_eq!(harness.state().pattern_editor.as_ref().map(|editor| editor.node), Some(selected)); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Window).label("FX-Map graph")).next().is_none()); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Canvas).label("FX-Map graph")).next().is_some()); + assert_eq!(harness.state().graph.rects.len(), 3); + let mut graph = match &harness.state().session.graph().unwrap().node(selected).unwrap().params["pattern"] { + materialcraft_engine::core::Value::PatternGraph(graph) => (**graph).clone(), + _ => panic!("missing pattern"), + }; + let dot = graph.add(materialcraft_engine::core::PatternNodeKind::Dot).unwrap(); + graph.nodes[0].children[1] = Some(dot); + graph.nodes[3].position = [288.0, 240.0]; + graph.nodes[3].children[0] = Some(graph.nodes[2].id); + let quadrant_id = graph.nodes[2].id; + harness.state_mut().run("graph.pattern.set", json!({"id": selected.0, "pattern": graph})).unwrap(); + settle(&mut harness, 3); + let quadrant = harness.state().graph.rects.iter().find(|(id, _)| id.0 == u64::from(quadrant_id)).unwrap().1.center(); + harness.event(egui::Event::PointerMoved(quadrant)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: quadrant, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + settle(&mut harness, 3); + assert!(harness.query_all(By::new().label("Pattern size")).next().is_some()); + if let Some(directory) = &directory { + save(&mut harness, directory, "pattern-graph-editor"); + } + let parent = harness.state().session.graph().unwrap().name.clone(); + harness.get(By::new().role(egui::accesskit::Role::Button).label(&parent)).click(); + settle(&mut harness, 3); + assert!(harness.state().pattern_editor.is_none()); + + harness.state_mut().run("file.new", json!({"template": "empty"})).unwrap(); + harness.state_mut().run("graph.node.add", json!({"def": "fx_map"})).unwrap(); + harness.state_mut().ui.frame_all = true; + harness.event(egui::Event::PointerGone); + settle(&mut harness, 3); + assert_eq!(harness.state().graph.ports.len(), 3); + if let Some(directory) = &directory { + save(&mut harness, directory, "default-pattern-inputs"); + } + let position = harness.state().graph.rects[0].1.center(); + harness.event(egui::Event::PointerMoved(position)); + settle(&mut harness, 3); + if let Some(directory) = &directory { + save(&mut harness, directory, "hovered-pattern-inputs"); + } + + harness.state_mut().ui.dock.focus(materialcraft_ui_egui::docking::Panel::Graph); + harness.key_press_modifiers(egui::Modifiers::CTRL | egui::Modifiers::COMMAND, egui::Key::E); + settle(&mut harness, 3); + assert_eq!(harness.state().graph.rects.len(), 1); + assert_eq!(harness.state().graph.ports.len(), 5); + harness.event(egui::Event::PointerGone); + settle(&mut harness, 3); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Button).label("Quadrant")).next().is_some()); + if let Some(directory) = &directory { + save(&mut harness, directory, "default-pattern-root"); + } + let position = harness.state().graph.rects[0].1.center(); + harness.event(egui::Event::PointerMoved(position)); + settle(&mut harness, 3); + if let Some(directory) = &directory { + save(&mut harness, directory, "hovered-pattern-root"); + } + + harness.get_all(By::new().role(egui::accesskit::Role::Button).label("Quadrant")).last().unwrap().click(); + settle(&mut harness, 3); + let blank = harness.state().graph.view.left_bottom() + vec2(12.0, -12.0); + click_canvas(&mut harness, blank); + if let Some(directory) = &directory { + save(&mut harness, directory, "deselected-pattern-properties"); + } + harness.get_all(By::new().role(egui::accesskit::Role::Button).label("Quadrant")).last().unwrap().click_secondary(); + settle(&mut harness, 3); + harness.get_by_label("Add node").click(); + settle(&mut harness, 3); + harness.key_press(egui::Key::S); + settle(&mut harness, 3); + if let Some(directory) = &directory { + save(&mut harness, directory, "filtered-pattern-menu"); + } + assert!(!harness.get_all(button("Switch")).last().unwrap().accesskit_node().is_disabled()); + assert!(harness.query_all(button("Quadrant")).any(|node| node.accesskit_node().is_disabled())); + assert!(harness.query_all(button("Iterate")).any(|node| node.accesskit_node().is_disabled())); + + harness.key_press(egui::Key::Enter); + settle(&mut harness, 3); + let owner = harness.state().pattern_editor.as_ref().unwrap().node; + let materialcraft_engine::core::Value::PatternGraph(pattern) = &harness.state().session.graph().unwrap().node(owner).unwrap().params["pattern"] else { + panic!("missing pattern"); + }; + + assert_eq!(pattern.nodes.len(), 2); + assert_eq!(pattern.nodes[1].kind, materialcraft_engine::core::PatternNodeKind::Switch); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn annotations_and_function_graph_creation() { + use materialcraft_engine::core::{FunctionGraph, GraphKind, Value}; + + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("graph.node.add", json!({"def": "uniform", "at": [64, 64]})).unwrap(); + let frame = + app.run("graph.frame.add", json!({"rect": [0, -64, 500, 404], "title": "Frame", "description": "Frame descriptions appear inside the frame and wrap as the frame is resized. Nodes and comments move together with this frame."})).unwrap()["id"].as_u64().unwrap(); + let comment = app.run("graph.comment.add", json!({"at": [64, 240], "text": "Comment"})).unwrap()["id"].as_u64().unwrap(); + app.run("graph.annotation.select", json!({"kind": "frame", "id": frame})); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 8); + assert!(harness.query_all(By::new().label("Frame title")).next().is_some()); + assert!(harness.query_all(By::new().label("Title Visible")).next().is_some()); + save(&mut harness, &directory, "selected-frame-properties"); + + harness.state_mut().run("graph.annotation.select", json!({"kind": "comment", "id": comment})); + settle(&mut harness, 3); + assert!(harness.query_all(By::new().label("Comment description")).next().is_some()); + assert!(harness.query_all(By::new().label("Frame title")).next().is_none()); + save(&mut harness, &directory, "plain-comment-properties"); + + let processor = harness.state_mut().run("graph.node.add", json!({"def": "value_processor", "at": [256, 64]})).unwrap()["id"].as_u64().unwrap(); + harness.state_mut().run("graph.node.value_input", json!({"id": processor, "name": "roughness_scale", "type": "Float"})); + let value = harness.state_mut().run("graph.node.add", json!({"def": "input_value", "at": [64, 440]})).unwrap()["id"].as_u64().unwrap(); + harness.state_mut().run("graph.connect", json!({"from": value, "to": processor, "toPort": "value1"})).unwrap(); + harness.state_mut().run("graph.select", json!({"ids": [processor]})); + settle(&mut harness, 3); + harness.get_by_label("Value inputs").click(); + settle(&mut harness, 3); + assert!(harness.query_all(By::new().label("Value 1")).next().is_some()); + assert!(harness.query_all(By::new().label("Roughness Scale")).next().is_some()); + save(&mut harness, &directory, "processor-port-labels"); + + let inspection = materialcraft_ui_egui::control::handle(harness.state_mut(), &egui::Context::default(), "ui.inspect", &json!({})); + let ports = inspection["result"]["ports"].as_array().unwrap(); + assert!(ports.iter().any(|port| port["node"] == processor && port["port"] == "value1" && port["label"] == "Value 1 (Float)")); + assert!(ports.iter().any(|port| port["node"] == processor && port["port"] == "roughness_scale" && port["label"] == "Roughness Scale (Float)")); + + harness.state_mut().ui.windows.new_graph = true; + settle(&mut harness, 3); + harness.get_by_label("Function Graph").click(); + settle(&mut harness, 3); + save(&mut harness, &directory, "new-function-graph"); + harness.get_by_label("Create").click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.graph().unwrap().kind(), GraphKind::Function); + + let mut function = FunctionGraph::default(); + let first = function.add_constant(Value::Float(2.0)); + let second = function.add_constant(Value::Float(3.0)); + let output = function.add("mul", &[first, second], None); + function.output = Some(output); + function.nodes[1].pos = [0.0, 128.0]; + function.nodes[2].pos = [256.0, 64.0]; + let condition = function.add_constant(Value::Bool(true)); + let branch = function.add("ifelse", &[condition, output, second], None); + function.nodes[3].pos = [256.0, -128.0]; + function.nodes[4].pos = [512.0, 64.0]; + function.output = Some(branch); + harness.state_mut().run("graph.function.set", json!({"function": function})); + harness.state_mut().ui.frame_all = true; + settle(&mut harness, 5); + save(&mut harness, &directory, "standalone-function-graph"); + let inspection = materialcraft_ui_egui::control::handle(harness.state_mut(), &egui::Context::default(), "ui.inspect", &json!({})); + let ports = inspection["result"]["ports"].as_array().unwrap(); + assert!(ports.iter().any(|port| port["node"] == branch && port["port"] == "1" && port["label"] == "If")); + assert!(ports.iter().any(|port| port["node"] == branch && port["port"] == "output" && port["label"] == "Output")); + + let position = harness.state().graph.view.right_bottom() - vec2(20.0, 20.0); + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + settle(&mut harness, 3); + save(&mut harness, &directory, "function-context-menu"); + harness.get_by_label("Add node").click(); + settle(&mut harness, 3); + for label in ["Float", "Float2", "Multiply", "While loop"] { + assert!(harness.query_all(By::new().label(label)).next().is_some(), "missing {label}"); + } + save(&mut harness, &directory, "flat-function-node-menu"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn function_cards_and_dot_share_the_regular_graph_style() { + use materialcraft_engine::core::{FunctionGraph, Value}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.new", json!({"kind": "function", "name": "Function_cards"})).unwrap(); + let mut function = FunctionGraph::default(); + let value = function.add_constant(Value::Float4([1.0, 0.5, 0.25, 1.0])); + let dot = function.add("passthrough", &[value], None); + let multiply = function.add("mul", &[dot, dot], None); + function.nodes[0].pos = [0.0, 0.0]; + function.nodes[1].pos = [224.0, 64.0]; + function.nodes[2].pos = [416.0, 0.0]; + function.output = Some(multiply); + app.run("graph.function.set", json!({"function": function})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 5); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Button).label("Dot")).next().is_some()); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, "function-cards-and-dot"); + harness.get_all(By::new().role(egui::accesskit::Role::Button).label("Multiply")).last().unwrap().click(); + settle(&mut harness, 3); + let blank = harness.state().graph.view.left_bottom() + vec2(12.0, -12.0); + click_canvas(&mut harness, blank); + save(&mut harness, &directory, "deselected-function-properties"); + + let position = harness.state().graph.view.right_bottom() - vec2(20.0, 20.0); + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + settle(&mut harness, 3); + harness.get_by_label("Add node").click(); + settle(&mut harness, 3); + save(&mut harness, &directory, "grouped-function-menu"); + harness.key_press(egui::Key::M); + settle(&mut harness, 3); + save(&mut harness, &directory, "filtered-function-menu"); + assert!(harness.get_all(By::new().role(egui::accesskit::Role::Button).label("Boolean")).last().unwrap().accesskit_node().is_disabled()); + harness.key_press(egui::Key::Enter); + settle(&mut harness, 3); + let function = harness.state().session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.nodes.len(), 4); + let added = function.nodes.last().unwrap(); + assert!(materialcraft_engine::nodes::function::definition(&added.op).unwrap().label.starts_with('M')); +} + +fn click_canvas(harness: &mut Harness<'static, MaterialCraftApp>, position: egui::Pos2) { + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + settle(harness, 3); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn named_outputs_open_properties_and_preview_only_on_double_click() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let source = app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0]})).unwrap()["id"].as_u64().unwrap(); + let output = app + .run( + "graph.node.add", + json!({ + "def": "output", "at": [224, 0], "connectFrom": {"node": source}, "params": {"identifier": "base_color"} + }), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + app.run("view.2d", json!({"node": source})).unwrap(); + app.session.cook(); + let material = app.session.material_maps().into_iter().map(|(name, image)| (name, image.data.clone())).collect::<Vec<_>>(); + 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(output)]); + assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(source))); + assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); + assert!(!harness.state().graph.ports.iter().any(|port| port.node.0 == output && port.output)); + + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, "named-output-properties"); + let start = harness.ctx.input(|input| input.time) + 1.0; + for (index, pressed) in [true, false, true, false].into_iter().enumerate() { + harness.input_mut().time = Some(start + index as f64 * 0.05); + harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + settle(&mut harness, 3); + assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(output))); + 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::<Vec<_>>(); + assert_eq!(current, material); + save(&mut harness, &directory, "named-output-preview"); +} diff --git a/docs/architecture.md b/docs/architecture.md index 96f8b9e6..b6b05ed4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -7,20 +7,18 @@ them). Everything below the UI is plain Rust with no UI toolkit and builds for `wasm32-unknown-unknown`. ```text -L0 core document model: Package → Graph → Node / Connection / Frame / Comment / Pin / ExposedParam; +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 geom meshes, primitives (rounded cube, sphere, cylinder, plane, torus, material ball), BVH, camera -L1 nodes the node library: NodeDef (ports, parameters, category, cook fn) for 227 nodes, the - tileable noise primitives, shared image ops (blur, EDT, HSL, blend modes) and the - function-graph compiler/evaluator for pixel and value processors +L1 nodes 30 main-graph entries (NodeDefinition), 85 function operations, four pattern node kinds; + shared image operations and iterative function/pattern execution L2 eval cooking: topological order, output sizes (relative to input / parent, absolute, preview cap), parameter resolution (defaults, overrides, bindings to exposed inputs), the content-addressed LRU cache, graph instances (sub-graphs, recursion-guarded) -L2 formats .sbs packages (the main format, sbs.rs), .mcraft packages (zip: package.json + - resources/), .mcmat portable materials, bitmap - decode, texture encode (PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR at 8/16/32 bits), atomic writes +L2 formats native .sbs packages, .mcmat portable materials, bitmap/SVG decode, + texture encode (PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR), atomic writes L3 engine Session (package, open graph, selection, 2D/3D view state, snapshot undo, cache), the command registry, inspect, sample materials and graph templates L3 render the 3D view: BVH ray casts, parallax occlusion from the height output, GGX PBR with @@ -76,26 +74,16 @@ histogram editor with range handles on top of its sliders ([levels-editor.md](le ## Files -SBS (`.sbs`, `formats/src/sbs.rs`) is the main project format: XML with the package's graphs, nodes, -wires, parameters, graph inputs and outputs, frames and comments, and bitmaps embedded as -zlib/base64 data. MaterialCraft writes the SBS data plus, in a trailing XML comment, its own exact -copy of the package with a hash of the `<content>` it belongs to; reading uses the exact copy while -the hash matches (so nothing MaterialCraft-specific is lost) and the SBS data otherwise. Reading never -fails on what MaterialCraft lacks: atomic filters map to atomic nodes, library nodes map by name, -instances of graphs in the same file become graph instances, and anything else becomes a -`missing_node` placeholder (`core::MISSING_NODE`) that keeps its ports, wires and raw SBS parameters, -cooks to a soft error, and is written back unchanged. Every gap is a warning in -`Session::load_warnings`, the Console (`Session::warn`) and `session.inspect` (`package.warnings`). -Bitmaps an SBS file keeps next to it load from its folder only (`file_cmds::linked_files`). +SBS is the project format. The codec writes native filters, ports, parameters, function graphs, +pattern graphs and resources directly, without a private payload. Unsupported imports produce +warnings; unknown nodes remain placeholders. Library reference loading is not part of the current +primitive workflow. `.mcraft` is no longer supported. -A `.mcraft` package (the older format, still read and written: packages opened from a `.mcraft` -save back to it) is a zip: `package.json` (the serde `Package`, format version 1) and -`resources/<name>` for embedded bitmaps. Node parameters are stored only where they differ from the -catalog defaults, so new defaults reach old files and files stay small. +See [atomic-workflow.md](atomic-workflow.md) for the tested scope and remaining limitations. ## Other apps -A `.mcmat` portable material (`formats/src/material.rs`, `engine/src/material_cmds.rs`) holds a +A `.mcmat` portable material (`formats/src/material/`, `engine/src/material_cmds.rs`) holds a graph's cooked maps, its portable exposed inputs, presets and input nodes, and the source package. TextureCraft paints with it and re-cooks it by running `materialcraft-cli run <package> file.exportMaterial {path, size, values, inputs}`: the apps share the file format and the command diff --git a/docs/atomic-workflow.md b/docs/atomic-workflow.md new file mode 100644 index 00000000..a7380038 --- /dev/null +++ b/docs/atomic-workflow.md @@ -0,0 +1,107 @@ +# Primitive editing and native SBS + +MaterialCraft is a clean-room implementation. The Rust catalog contains only native primitives +and graph input/output items. SBS library nodes belong in SBS graphs; their former Rust +implementations have been removed. + +## Try it + +Choose **File → New → Atomic sample**, or open [`examples/atomic_sample.sbs`](../examples/atomic_sample.sbs). +The sample connects a value input to a multiplication function, feeds that value into a pixel +function, combines its gradient with an iterated pattern, and blurs the result. It has an image +output and a value output. + +Use the library or Space search to add primitives and drag between ports to connect them. +Select a Value Processor or Pixel Processor and choose **Edit function** in Properties. +The function editor supports adding operations, editing constants, wiring ports and choosing +the result. Select an FX-Map and press **Ctrl+E**, or right-click it and choose **Edit graph**. +This enters its subgraph in the main canvas. Add Quadrant, Switch, Iterate or vertical Dot nodes, drag from +bottom ports to top ports, and choose **Set as root** from a node’s context menu. Alt-click a port +to disconnect it. Selected-node parameters appear in Properties. Click the parent breadcrumb +or press **Alt+Left** to return. Positions and connections are saved in SBS. + +New FX-Map nodes start with a Quadrant root. Their main-graph inputs start with Background and +Input image 0; connecting an image exposes the next image input. Inputs appear progressively as they are connected; connected pins stay visible. Main and Function Graph pin names appear on node hover. Internal FX-Map pins have no visible names. + +Value inputs on processors have explicit types. A connection with an incompatible type is +rejected. All edits use engine commands and support undo. Save and reopen through the usual +File commands. + +The same sample is available through `file.newAtomicSample`. Regenerate the file with: + +```sh +cargo +1.96.0 run -p materialcraft-engine --release --example atomic_sample -- examples/atomic_sample.sbs +``` + +## Catalog + +| Context | Entries | +|---|---:| +| Main graph | 26 native primitives, including processors and reroute, plus 4 input/output items | +| Functions | 85 native operations | +| FX-Map graph | Quadrant (`paramset`), Switch (`markov2`), Iterate (`addnode`), Dot (`passthrough`) | + +Image primitives have individual files in `crates/nodes/src/atomic/`. Function evaluation and +pattern traversal have separate modules. Document types each live in their own file under +`crates/core/src/`. SBS parsing and writing live under `crates/formats/src/sbs/`. + +## Files and execution + +The saved document is native SBS XML: filters, graph bridges, typed value ports, function nodes, +pattern nodes, parameters and resources. There is no private package comment or embedded JSON +document. `.mcraft` read/write support has been removed. Portable `.mcmat` materials now contain +`source.sbs` and use manifest version 2; older archives are rejected. + +Function graphs and pattern graphs use iterative traversal, detect cycles and enforce node and +execution budgets. A shared child in a DAG is legal. Exhausting a budget produces an error. +SBS library reference resolution is outside this change. + +## Current limits + +- Reopening the generated SBS in the reference application has not been verified +- Native IDs, ports and types are mapped, but numerical parity with the reference renderer has + not been established, including pattern shapes, blending, sampling and random sequences +- Text renders the original built-in stroke font; external font references produce an explicit + error. SVG supports vector geometry, without external images or font loading +- Some native parameter variants and package/editor metadata remain unsupported; import reports + unsupported parameters. This is not a lossless importer for arbitrary SBS files +Pixel Processor, Value Processor and FX-Map image inputs grow as connected, up to 256. + +The tests cover primitive cooking, native field round trips, scalar/vector values, wire type +checks, undo, embedded SVG, function control flow, cycle rejection and execution budgets. + +## Graph editing + +Node placement and dragging snap to the 32-unit grid by default. The graph toolbar and Tools +menu toggle snapping. Function nodes use the same setting. Opening an SBS preserves its saved +positions; snapping takes effect when nodes are placed or moved. + +A new Value Processor has a Float input named `value1` and a function that returns it. Its +separate `Image 0` input is for image sampling. Drag an Input Value output to the orange value +input on each processor to branch the output. Additional typed inputs can be added in Properties. Port labels display readable names such as +“Value 1” while preserving native identifiers such as `value1` for wiring and SBS files. +Reconnecting a wire is one undo step; an invalid drop leaves the original connection intact. + +The graph context menu offers a flat Add node list, annotations, output views, thumbnails, +saving, clipboard actions, navigation pins and selection actions. Paste and Duplicate retain +incoming links within their source graph; their “without link” variants retain only wires +between copied nodes. F5 clears thumbnails; Compute nodes thumbnails restores them. F2 and +Shift+F2 cycle through navigation pins. Pin names, positions and order persist as native SBS +canvas objects in both Graph and Function Graph files. + + +Frames select by their background, title or border and show an outer selection outline. Properties +edits title visibility, title, fill color and description. Comments are plain canvas text with a +Description property. Moving a frame carries enclosed nodes, comments, nested frames and navigation +pins by one shared offset, with one undo step. Resizing changes only the frame bounds. + +New graph creation offers **Graph** and **Function Graph**. Function Graphs are package items with +a flat operation menu, editable constants, typed native operations, wiring and a designated output +node. They save as native SBS `<function>` items and reopen in MaterialCraft. Calling other SBS +function graphs remains outside this change. The reference application's ability to reopen the +saved files still needs external verification. + +Function Graphs share the main canvas card geometry and styling, including compact Dot nodes. +The Graph, Function Graph and FX-Map Add node menus remain flat, with dividers between groups +and room to use the window height. Type a letter to enable names starting with it while keeping the full list visible; +Backspace clears the filter. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d4cbd120..1c09d6c3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -35,7 +35,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: | `bitmap.import {path, name?}` | headless | embed an image as a resource | | `outputs.export {dir, format?, pattern?, depth?, size?, graph?}` | headless | cook at full size and write every output | | `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii | -| `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts | +| `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's identifier, display label and screen position, fps, toasts | | `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click | | `ui.set {...}` | app | merge fields into the UI state | | `ui.input {events}` | app | synthetic input, below | @@ -68,6 +68,8 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | Command | Params | |---|---| | `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) | +| `graph.node.edit` | `{}` resolves the selected FX-Map to `{node, parameter}`; use `ui.menu.invoke` to enter its subgraph in the graph panel | +| `graph.pattern.set` | `{id, pattern}` replaces an FX-Map subgraph with cycle validation and undo | | `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` | | `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` | | `graph.wire.insertDot` | `{to, toPort, at?}`: split the wire feeding `to.toPort` with a reroute Dot node at `at` (graph point, default midway), selected | @@ -84,30 +86,39 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg ## Function graphs -Pixel and value processors carry a `function` parameter: `{"nodes": [{"id", "op", "inputs": [ids], -"value"?}], "output": id}`. Ops: constants (`const_float`, `const_float2/3/4`, `const_int`, -`const_bool`), variables (`get_pos` = normalized pixel position, `get_size`, `get_var` with -`value` = an exposed input id), samplers (`sample_gray`, `sample_color` with `value` = input index -0–3, input = a float2 position), vectors (`vec2/3/4`, `swizzle` with `value` = `"xy"` etc.), -casts, arithmetic (`add sub mul div mod neg dot`), logic and comparison (`and or not gt ge lt le eq -ne`), functions (`abs floor ceil frac sqrt exp log sin cos tan atan2 pow min max clamp lerp length -normalize rand noise`) and `if_else`. Values are 4-wide; scalars broadcast. +`file.new {"kind": "function", "name": "Calculation"}` creates a standalone Function Graph. +Omit `kind`, or use `"material"`, for a Graph. `graph.function.set {"function": {...}}` replaces +the active standalone function through one validated, undoable command. + +A function has `nodes` and an optional `output` node id. Each node has `id`, native `op`, +`inputs` (source ids or null for unwired ports), optional `value`, `type_code` and `pos`. +For example, `const_float1` supplies a scalar and `mul` multiplies its `a` and `b` inputs. +The catalog in `crates/nodes/src/function/catalog.rs` defines all native operation and port ids. +Processors and dynamic parameters use the same function representation. Graph validation and +execution use bounded iterative traversal and reject cycles. + +`graph.annotation.select {"kind": "frame"|"comment", "id": ...}` selects an annotation. +`graph.frame.edit` accepts `title`, `titleVisible`, `description`, `color` and `rect`. +`graph.frame.move {"id": ..., "by": [dx, dy], "snapToGrid": true}` moves enclosed nodes, +comments, nested frames and pins together. `graph.comment.edit` accepts `text`, `at` and `size`. +`session.inspect` includes annotation selection and the standalone function; `ui.inspect` +includes frame and comment rectangles for synthetic input. ## Portable materials (TextureCraft) A `.mcmat` portable material is a zip: `material.json` (manifest), `maps/<usage>.png` and -`source.mcraft` (the package). TextureCraft applies it as a fill layer and keeps the exposed inputs +`source.sbs` (the package). TextureCraft applies it as a fill layer and keeps the exposed inputs editable, re-cooking through `materialcraft-cli`. The format is a convention the two apps share; each has its own reader and writer (`crates/formats/src/material.rs` here), so keep them in step. ```json -{ "format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [2048, 2048], +{ "format": "craft-material", "version": 2, "name": "Brick wall", "graph": "Brick_wall", "size": [2048, 2048], "maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}], "parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0, "max": 1, "value": {"t": "float", "v": 0.8}}], "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}], - "source": "source.mcraft" } + "source": "source.sbs" } ``` - Usages: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive`, @@ -119,15 +130,15 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k - Inputs are the graph's input nodes. Mesh maps feed them by identifier: `ambientOcclusion`, `curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`, `opacity`, `colorMap`, `worldDirection`. -- Readers ignore unknown fields and refuse a `version` newer than they know. +- Readers ignore unknown fields and require manifest `version` 2. | Command | Params | |---|---| -| `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.mcraft file.exportMaterial {...}` to re-cook at its texture set's resolution with its own values and baked mesh maps | +| `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.sbs file.exportMaterial {...}` to re-cook at its texture set's resolution with its own values and baked mesh maps | | `file.sendToTextureCraft` | `{graph?}`: export into TextureCraft's library folder (`Documents/TextureCraft/library`), where its shelf lists it | | `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | -| `file.open` | opens `.sbs` (by content) and `.mcraft` packages, and a `.mcmat`'s source package, on its graph, with no file name. Returns `warnings`: what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders); also in `session.inspect` as `package.warnings` | -| `file.save` | `{path?}`: SBS unless the file is `.mcraft`; `.sbs` is appended when `path` has no package extension | +| `file.open` | opens native `.sbs` packages, and a `.mcmat`'s source package, on its graph, with no file name. Returns `warnings`: what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders); also in `session.inspect` as `package.warnings` | +| `file.save` | `{path?}`: native SBS; `.sbs` is appended when the path does not end in `.sbs` | ## MCP tools @@ -136,3 +147,7 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k `outputs_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`, `ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. `package_open` opens `.mcmat` files too; exporting one is CLI-only for now (the workspace sandbox refuses `file.*` commands). + +While an FX-Map subgraph is open, `ui.inspect.subgraph` identifies its owner and selection. Canvas +node IDs and ports refer to that embedded graph. `ui.menu.invoke` with `ui.graph.parent` returns +to the parent canvas. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index aeb5e28d..40d07b0b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,5 +1,9 @@ # File format parity +> The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and +> compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and +> [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. + > **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-04 · **Change:** major (SBS is the main project format) · **Target:** the professional node-based material workflow SBS packages are MaterialCraft's main project format (issue #49), read and written with its own diff --git a/docs/gaps.md b/docs/gaps.md index e3da2669..d5641762 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,5 +1,9 @@ # Gaps +> The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and +> compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and +> [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. + > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable `.mcmat` materials closed the published-archive gap) · **Target:** the professional node-based material workflow Every known shortfall, most important first. Pick from the top. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cea2a179..6f135be5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,5 +1,9 @@ # Parity with the reference workflow +> The assessment below predates the 2026-11-05 primitive rewrite. Its old library counts and +> compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and +> [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. + > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (Files 60% → 70%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) **Overall: ≈ 67%** of a material artist's daily workflow works end to end (engine + UI + diff --git a/examples/atomic_sample.sbs b/examples/atomic_sample.sbs new file mode 100644 index 00000000..6b22ab13 --- /dev/null +++ b/examples/atomic_sample.sbs @@ -0,0 +1 @@ +<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Atomic sample"/><formatVersion v="1.1.0.202401"/><updaterVersion v="1.1.0.202401"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><graph><identifier v="Atomic_sample"/><uid v="1000000002"/><graphtype v="material"/><paraminputs><paraminput><identifier v="brightness"/><uid v="1000000017"/><isConnectable v="1"/><type v="256"/><defaultValue><constantValueFloat1 v="0.35"/></defaultValue><defaultWidget><name v=""/><options/></defaultWidget></paraminput></paraminputs><graphOutputs><graphoutput><identifier v="height"/><uid v="1000000018"/><attributes><label v="height"/></attributes><usages><usage><components v="RGBA"/><name v="height"/></usage></usages><group v="Material"/><channels v="2"/></graphoutput><graphoutput><identifier v="brightness_value"/><uid v="1000000019"/><attributes><label v="brightness_value"/></attributes><usages><usage><components v="RGBA"/><name v="any"/></usage></usages><group v="Material"/><channels v="256"/></graphoutput></graphOutputs><compNodes><compNode><uid v="1000000003"/><GUILayout><gpos v="50 40 0"/></GUILayout><compOutputs><compOutput><uid v="1000000004"/><comptype v="256"/></compOutput></compOutputs><compImplementation><compInputBridge><entry v="1000000017"/><parameters></parameters></compInputBridge></compImplementation></compNode><compNode><uid v="1000000005"/><GUILayout><gpos v="250 40 0"/></GUILayout><inputValues><compInputValue><identifier v="brightness"/><type v="256"/></compInputValue></inputValues><compOutputs><compOutput><uid v="1000000006"/><comptype v="256"/></compOutput></compOutputs><connections><connection><identifier v="brightness"/><connRef v="1000000003"/><connRefOutput v="1000000004"/></connection></connections><compImplementation><compFilter><filter v="valueprocessor"/><parameters><parameter><name v="function"/><relativeTo v="0"/><paramValue><dynamicValue><rootnode v="1000000022"/><paramNodes><paramNode><uid v="1000000020"/><function v="get_float1"/><type v="256"/><GUILayout><gpos v="0 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="get_float1"/><constantValue><constantValueString v="brightness"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000021"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="140 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="2"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000022"/><function v="mul"/><type v="256"/><GUILayout><gpos v="280 0 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000020"/></connection><connection><identifier v="b"/><connRef v="1000000021"/></connection></connections></paramNode></paramNodes></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation></compNode><compNode><uid v="1000000007"/><GUILayout><gpos v="450 40 0"/></GUILayout><inputValues><compInputValue><identifier v="brightness"/><type v="256"/></compInputValue></inputValues><compOutputs><compOutput><uid v="1000000008"/><comptype v="2"/></compOutput></compOutputs><connections><connection><identifier v="brightness"/><connRef v="1000000005"/><connRefOutput v="1000000006"/></connection></connections><compImplementation><compFilter><filter v="pixelprocessor"/><parameters><parameter><name v="perpixel"/><relativeTo v="0"/><paramValue><dynamicValue><rootnode v="1000000026"/><paramNodes><paramNode><uid v="1000000023"/><function v="get_float2"/><type v="512"/><GUILayout><gpos v="0 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="get_float2"/><constantValue><constantValueString v="$pos"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000024"/><function v="swizzle1"/><type v="256"/><GUILayout><gpos v="140 0 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000023"/></connection></connections><funcDatas><funcData><name v="swizzle1"/><constantValue><constantValueInt32 v="0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000025"/><function v="get_float1"/><type v="256"/><GUILayout><gpos v="280 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="get_float1"/><constantValue><constantValueString v="brightness"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000026"/><function v="mul"/><type v="256"/><GUILayout><gpos v="420 0 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000024"/></connection><connection><identifier v="b"/><connRef v="1000000025"/></connection></connections></paramNode></paramNodes></dynamicValue></paramValue></parameter><parameter><name v="colorswitch"/><relativeTo v="0"/><paramValue><constantValueBool v="0"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode><compNode><uid v="1000000009"/><GUILayout><gpos v="450 260 0"/></GUILayout><compOutputs><compOutput><uid v="1000000010"/><comptype v="2"/></compOutput></compOutputs><compImplementation><compFilter><filter v="fxmaps"/><parameters><parameter><name v="colorswitch"/><relativeTo v="0"/><paramValue><constantValueBool v="0"/></paramValue></parameter><parameter><name v="background"/><relativeTo v="0"/><paramValue><constantValueFloat4 v="0 0 0 1"/></paramValue></parameter><parameter><name v="opacitymult"/><relativeTo v="0"/><paramValue><constantValueFloat1 v="1"/></paramValue></parameter></parameters><paramsGraphs><paramsGraph><name v=""/><uid v="1000000033"/><rootnode v="1000000027"/><paramsGraphDatas><paramsGraphData><uid v="1000000028"/><type v="addnode"/><parameters><parameter><name v="numberadded"/><relativeTo v="0"/><paramValue><constantValueInt32 v="8"/></paramValue></parameter><parameter><name v="randominherited"/><relativeTo v="0"/><paramValue><constantValueBool v="1"/></paramValue></parameter><parameter><name v="randomseed"/><relativeTo v="0"/><paramValue><constantValueInt32 v="0"/></paramValue></parameter></parameters></paramsGraphData><paramsGraphData><uid v="1000000030"/><type v="markov2"/><parameters><parameter><name v="randominherited"/><relativeTo v="0"/><paramValue><constantValueBool v="1"/></paramValue></parameter><parameter><name v="randomseed"/><relativeTo v="0"/><paramValue><constantValueInt32 v="0"/></paramValue></parameter><parameter><name v="switch"/><relativeTo v="0"/><paramValue><constantValueBool v="0"/></paramValue></parameter></parameters></paramsGraphData><paramsGraphData><uid v="1000000032"/><type v="paramset"/><parameters><parameter><name v="blendingmode"/><relativeTo v="0"/><paramValue><constantValueInt32 v="0"/></paramValue></parameter><parameter><name v="branchoffset"/><relativeTo v="0"/><paramValue><constantValueFloat2 v="0 0"/></paramValue></parameter><parameter><name v="frameoffset"/><paramValue><dynamicValue><rootnode v="1000000038"/><paramNodes><paramNode><uid v="1000000034"/><function v="get_float1"/><type v="256"/><GUILayout><gpos v="0 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="get_float1"/><constantValue><constantValueString v="$number"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000035"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="140 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.7853982"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000036"/><function v="mul"/><type v="256"/><GUILayout><gpos v="280 0 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000034"/></connection><connection><identifier v="b"/><connRef v="1000000035"/></connection></connections></paramNode><paramNode><uid v="1000000037"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="420 0 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.3"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000038"/><function v="cartesian"/><type v="512"/><GUILayout><gpos v="560 0 0"/></GUILayout><connections><connection><identifier v="rho"/><connRef v="1000000037"/></connection><connection><identifier v="theta"/><connRef v="1000000036"/></connection></connections></paramNode></paramNodes></dynamicValue></paramValue></parameter><parameter><name v="imagefiltering"/><relativeTo v="0"/><paramValue><constantValueInt32 v="1"/></paramValue></parameter><parameter><name v="imageindex"/><relativeTo v="0"/><paramValue><constantValueInt32 v="1"/></paramValue></parameter><parameter><name v="imagepremul"/><relativeTo v="0"/><paramValue><constantValueBool v="0"/></paramValue></parameter><parameter><name v="opacity"/><relativeTo v="0"/><paramValue><constantValueFloat4 v="0.5 0.5 0.5 1"/></paramValue></parameter><parameter><name v="patternrotation"/><relativeTo v="0"/><paramValue><constantValueFloat1 v="0"/></paramValue></parameter><parameter><name v="patternsize"/><relativeTo v="0"/><paramValue><constantValueFloat2 v="0.12 0.12"/></paramValue></parameter><parameter><name v="patternsuppl"/><relativeTo v="0"/><paramValue><constantValueFloat1 v="0"/></paramValue></parameter><parameter><name v="patterntype"/><relativeTo v="0"/><paramValue><constantValueInt32 v="3"/></paramValue></parameter><parameter><name v="randominherited"/><relativeTo v="0"/><paramValue><constantValueBool v="1"/></paramValue></parameter><parameter><name v="randomseed"/><relativeTo v="0"/><paramValue><constantValueInt32 v="0"/></paramValue></parameter></parameters></paramsGraphData></paramsGraphDatas><paramsGraphNodes><paramsGraphNode><uid v="1000000027"/><type v="addnode"/><data v="1000000028"/><GUILayout><gpos v="160 0 0"/></GUILayout><connections><connection><identifier v="output0"/><connRef v="1000000029"/></connection><connection><identifier v="output1"/><connRef v="1000000031"/></connection></connections></paramsGraphNode><paramsGraphNode><uid v="1000000029"/><type v="markov2"/><data v="1000000030"/><GUILayout><gpos v="0 192 0"/></GUILayout><connections><connection><identifier v="output1"/><connRef v="1000000031"/></connection></connections></paramsGraphNode><paramsGraphNode><uid v="1000000031"/><type v="paramset"/><data v="1000000032"/><GUILayout><gpos v="160 384 0"/></GUILayout><connections></connections></paramsGraphNode></paramsGraphNodes></paramsGraph></paramsGraphs></compFilter></compImplementation></compNode><compNode><uid v="1000000011"/><GUILayout><gpos v="650 40 0"/></GUILayout><compOutputs><compOutput><uid v="1000000012"/><comptype v="2"/></compOutput></compOutputs><connections><connection><identifier v="source"/><connRef v="1000000009"/><connRefOutput v="1000000010"/></connection><connection><identifier v="destination"/><connRef v="1000000007"/><connRefOutput v="1000000008"/></connection></connections><compImplementation><compFilter><filter v="blend"/><parameters><parameter><name v="blendingmode"/><relativeTo v="0"/><paramValue><constantValueInt32 v="1"/></paramValue></parameter><parameter><name v="opacitymult"/><relativeTo v="0"/><paramValue><constantValueFloat1 v="1"/></paramValue></parameter><parameter><name v="alphablending"/><relativeTo v="0"/><paramValue><constantValueBool v="1"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode><compNode><uid v="1000000013"/><GUILayout><gpos v="850 40 0"/></GUILayout><compOutputs><compOutput><uid v="1000000014"/><comptype v="2"/></compOutput></compOutputs><connections><connection><identifier v="input1"/><connRef v="1000000011"/><connRefOutput v="1000000012"/></connection></connections><compImplementation><compFilter><filter v="blur"/><parameters><parameter><name v="intensity"/><relativeTo v="0"/><paramValue><constantValueFloat1 v="1.5"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode><compNode><uid v="1000000015"/><GUILayout><gpos v="1050 40 0"/></GUILayout><connections><connection><identifier v="inputNodeOutput"/><connRef v="1000000013"/><connRefOutput v="1000000014"/></connection></connections><compImplementation><compOutputBridge><output v="1000000018"/></compOutputBridge></compImplementation></compNode><compNode><uid v="1000000016"/><GUILayout><gpos v="450 -160 0"/></GUILayout><connections><connection><identifier v="inputNodeOutput"/><connRef v="1000000005"/><connRefOutput v="1000000006"/></connection></connections><compImplementation><compOutputBridge><output v="1000000019"/></compOutputBridge></compImplementation></compNode></compNodes><baseParameters><parameter><name v="randomseed"/><relativeTo v="0"/><paramValue><constantValueInt32 v="0"/></paramValue></parameter></baseParameters><GUIObjects></GUIObjects><options><option><name v="defaultParentSize"/><value v="8x8"/></option></options><root><rootOutputs><rootOutput><output v="1000000018"/><format v="0"/><usertag v=""/></rootOutput><rootOutput><output v="1000000019"/><format v="0"/><usertag v=""/></rootOutput></rootOutputs></root></graph></content></package> From fe88ee5c4d5166ec4edc614dbbac62bc92603fa7 Mon Sep 17 00:00:00 2001 From: chasse20 <chasse20@gmail.com> Date: Fri, 6 Nov 2026 00:13:10 -0500 Subject: [PATCH 82/91] Unify graph editors and optimize material workflows --- Cargo.lock | 1 + crates/core/src/component_usage.rs | 81 ++ crates/core/src/graph.rs | 47 +- crates/core/src/graph_index.rs | 133 ++ crates/core/src/lib.rs | 6 + crates/core/src/material_channel.rs | 50 + crates/core/src/pattern_graph.rs | 32 +- crates/engine/src/alignment_commands.rs | 95 ++ crates/engine/src/commands.rs | 10 +- crates/engine/src/edit_cmds.rs | 2 +- crates/engine/src/embedded_clipboard.rs | 9 + crates/engine/src/embedded_edit_commands.rs | 88 ++ crates/engine/src/file_cmds.rs | 5 + crates/engine/src/function_commands.rs | 22 +- crates/engine/src/function_edit.rs | 105 ++ crates/engine/src/function_graph_target.rs | 80 ++ crates/engine/src/graph_cmds.rs | 43 +- .../engine/src/graph_edit/editable_graph.rs | 17 + .../engine/src/graph_edit/function_graph.rs | 45 + crates/engine/src/graph_edit/mod.rs | 9 + crates/engine/src/graph_edit/pattern_graph.rs | 47 + crates/engine/src/graph_edit/selection.rs | 127 ++ crates/engine/src/graph_grid.rs | 5 + crates/engine/src/graph_validation.rs | 50 + crates/engine/src/inspect.rs | 7 + crates/engine/src/lib.rs | 24 + crates/engine/src/material_cmds.rs | 11 +- crates/engine/src/material_preview.rs | 93 ++ .../engine/src/material_preview_commands.rs | 100 ++ crates/engine/src/material_source.rs | 62 + crates/engine/src/node_cmds.rs | 11 +- crates/engine/src/node_graph_commands.rs | 40 +- crates/engine/src/pattern_edit.rs | 114 ++ crates/engine/src/pattern_graph_commands.rs | 5 +- crates/engine/src/preview_cook.rs | 32 + crates/engine/src/selection_commands.rs | 191 +++ crates/engine/src/selection_target.rs | 51 + crates/engine/src/session.rs | 35 +- crates/engine/src/snapshot.rs | 1 + crates/engine/tests/atomics.rs | 31 +- crates/engine/tests/embedded_edit.rs | 319 +++++ crates/engine/tests/graph_alignment.rs | 93 ++ crates/engine/tests/graph_edit.rs | 130 ++ crates/engine/tests/material_preview.rs | 263 ++++ crates/engine/tests/optimization_perf.rs | 84 ++ crates/eval/src/cache_key.rs | 63 + crates/eval/src/graph_execution.rs | 419 +----- crates/eval/src/graph_instance.rs | 71 + crates/eval/src/graph_output.rs | 17 + crates/eval/src/lib.rs | 16 +- crates/eval/src/node_execution.rs | 158 +++ crates/eval/src/parameter.rs | 58 + crates/eval/src/port.rs | 88 +- crates/eval/src/ports.rs | 95 ++ crates/eval/src/prepared_graph.rs | 31 + crates/eval/src/tests.rs | 31 +- crates/eval/src/time.rs | 10 + crates/eval/src/value_execution.rs | 23 + crates/formats/src/material/archive.rs | 15 +- crates/formats/src/sbs/canvas.rs | 42 + crates/formats/src/sbs/component_usage.rs | 22 + crates/formats/src/sbs/input_bridge.rs | 1 + crates/formats/src/sbs/mod.rs | 8 +- crates/formats/src/sbs/output.rs | 10 - crates/formats/src/sbs/read.rs | 99 ++ crates/formats/src/sbs/sbs_reader.rs | 165 +-- crates/formats/src/sbs/sbs_value.rs | 17 +- crates/formats/src/sbs/sbs_writer.rs | 82 +- crates/formats/src/sbs/tests.rs | 64 +- crates/formats/src/sbs/type_code.rs | 22 +- crates/formats/src/sbs/write.rs | 66 + crates/nodes/src/atomic/input_color.rs | 2 + crates/nodes/src/atomic/input_grayscale.rs | 2 + crates/nodes/src/atomic/input_value.rs | 2 + crates/nodes/src/atomic/mod.rs | 2 - crates/nodes/src/atomic/output.rs | 4 +- crates/nodes/src/function/operation.rs | 16 +- crates/nodes/src/function/processor.rs | 3 +- crates/nodes/src/function/program.rs | 22 +- crates/nodes/src/function/tests.rs | 48 + crates/nodes/src/node_definition_builder.rs | 6 +- crates/render/Cargo.toml | 1 + crates/render/src/preview.rs | 22 +- crates/ui-egui/src/control.rs | 19 +- crates/ui-egui/src/cook.rs | 11 +- crates/ui-egui/src/cook_cancellation.test.rs | 7 +- crates/ui-egui/src/explorer.rs | 40 +- crates/ui-egui/src/function/actions.rs | 49 + crates/ui-egui/src/function/canvas.rs | 588 +-------- crates/ui-egui/src/function/context_menu.rs | 91 +- .../ui-egui/src/function/function_canvas.rs | 16 + crates/ui-egui/src/function/function_drag.rs | 3 +- .../ui-egui/src/function/function_editor.rs | 75 +- crates/ui-egui/src/function/function_port.rs | 9 + .../ui-egui/src/function/function_target.rs | 4 +- crates/ui-egui/src/function/geometry.rs | 51 + crates/ui-egui/src/function/input.rs | 125 ++ crates/ui-egui/src/function/library.rs | 21 +- crates/ui-egui/src/function/mod.rs | 13 +- crates/ui-egui/src/function/panel.rs | 13 + crates/ui-egui/src/function/properties.rs | 22 +- crates/ui-egui/src/function/render.rs | 214 +++ crates/ui-egui/src/function/selection.rs | 104 -- crates/ui-egui/src/graph/actions.rs | 31 +- crates/ui-egui/src/graph/annotation_canvas.rs | 23 +- crates/ui-egui/src/graph/annotation_input.rs | 72 +- crates/ui-egui/src/graph/canvas.rs | 1168 ++--------------- crates/ui-egui/src/graph/canvas_geometry.rs | 19 + crates/ui-egui/src/graph/canvas_tests.rs | 221 ++++ crates/ui-egui/src/graph/context_menu.rs | 38 +- crates/ui-egui/src/graph/edit_menu.rs | 40 + crates/ui-egui/src/graph/editor_actions.rs | 25 + crates/ui-egui/src/graph/editor_target.rs | 31 + crates/ui-egui/src/graph/gesture.rs | 13 + crates/ui-egui/src/graph/graph_camera.rs | 54 +- crates/ui-egui/src/graph/graph_drag.rs | 2 +- crates/ui-egui/src/graph/graph_parent.rs | 7 + crates/ui-egui/src/graph/grid.rs | 26 + crates/ui-egui/src/graph/input.rs | 249 ++++ crates/ui-egui/src/graph/interaction_tests.rs | 62 + crates/ui-egui/src/graph/mod.rs | 33 +- crates/ui-egui/src/graph/navigation.rs | 48 + crates/ui-egui/src/graph/node_selection.rs | 24 + crates/ui-egui/src/graph/node_style.rs | 85 ++ crates/ui-egui/src/graph/port_hit.rs | 16 + crates/ui-egui/src/graph/review_tests.rs | 343 +++++ crates/ui-egui/src/graph/search.rs | 100 ++ .../ui-egui/src/graph/selection_commands.rs | 11 + .../ui-egui/src/graph/subgraph_navigation.rs | 86 ++ crates/ui-egui/src/graph/toolbar.rs | 186 +++ crates/ui-egui/src/graph/wire_actions.rs | 52 + crates/ui-egui/src/graph/wire_geometry.rs | 52 + crates/ui-egui/src/graph_drag_payload.rs | 4 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/library.rs | 18 +- crates/ui-egui/src/material_craft_app.rs | 36 +- crates/ui-egui/src/material_preview_menu.rs | 44 + crates/ui-egui/src/menus.rs | 14 +- crates/ui-egui/src/pattern/actions.rs | 42 +- crates/ui-egui/src/pattern/canvas.rs | 131 +- crates/ui-egui/src/pattern/context_menu.rs | 68 +- crates/ui-egui/src/pattern/geometry.rs | 9 +- crates/ui-egui/src/pattern/input.rs | 121 +- crates/ui-egui/src/pattern/library.rs | 9 +- crates/ui-egui/src/pattern/mod.rs | 1 - crates/ui-egui/src/pattern/pattern_drag.rs | 4 +- crates/ui-egui/src/pattern/pattern_editor.rs | 45 +- crates/ui-egui/src/pattern/properties.rs | 44 +- crates/ui-egui/src/pattern/selection.rs | 88 -- crates/ui-egui/src/properties.rs | 810 ------------ crates/ui-egui/src/property/curve.rs | 93 ++ crates/ui-egui/src/property/gradient.rs | 101 ++ crates/ui-egui/src/property/graph.rs | 184 +++ crates/ui-egui/src/property/input.rs | 45 + crates/ui-egui/src/property/mod.rs | 69 + crates/ui-egui/src/property/node.rs | 157 +++ crates/ui-egui/src/property/parameter.rs | 214 +++ crates/ui-egui/src/property/section.rs | 29 + crates/ui-egui/src/view3d.rs | 49 +- crates/ui-egui/src/windows.rs | 2 +- crates/ui-egui/tests/snapshot.rs | 360 ++++- docs/architecture.md | 81 +- docs/control-protocol.md | 72 +- 163 files changed, 8130 insertions(+), 4038 deletions(-) create mode 100644 crates/core/src/component_usage.rs create mode 100644 crates/core/src/graph_index.rs create mode 100644 crates/core/src/material_channel.rs create mode 100644 crates/engine/src/alignment_commands.rs create mode 100644 crates/engine/src/embedded_clipboard.rs create mode 100644 crates/engine/src/embedded_edit_commands.rs create mode 100644 crates/engine/src/function_edit.rs create mode 100644 crates/engine/src/function_graph_target.rs create mode 100644 crates/engine/src/graph_edit/editable_graph.rs create mode 100644 crates/engine/src/graph_edit/function_graph.rs create mode 100644 crates/engine/src/graph_edit/mod.rs create mode 100644 crates/engine/src/graph_edit/pattern_graph.rs create mode 100644 crates/engine/src/graph_edit/selection.rs create mode 100644 crates/engine/src/graph_validation.rs create mode 100644 crates/engine/src/material_preview.rs create mode 100644 crates/engine/src/material_preview_commands.rs create mode 100644 crates/engine/src/material_source.rs create mode 100644 crates/engine/src/pattern_edit.rs create mode 100644 crates/engine/src/preview_cook.rs create mode 100644 crates/engine/src/selection_commands.rs create mode 100644 crates/engine/src/selection_target.rs create mode 100644 crates/engine/tests/embedded_edit.rs create mode 100644 crates/engine/tests/graph_alignment.rs create mode 100644 crates/engine/tests/graph_edit.rs create mode 100644 crates/engine/tests/material_preview.rs create mode 100644 crates/engine/tests/optimization_perf.rs create mode 100644 crates/eval/src/graph_instance.rs create mode 100644 crates/eval/src/graph_output.rs create mode 100644 crates/eval/src/node_execution.rs create mode 100644 crates/eval/src/parameter.rs create mode 100644 crates/eval/src/ports.rs create mode 100644 crates/eval/src/prepared_graph.rs create mode 100644 crates/eval/src/time.rs create mode 100644 crates/eval/src/value_execution.rs create mode 100644 crates/formats/src/sbs/component_usage.rs create mode 100644 crates/formats/src/sbs/read.rs create mode 100644 crates/formats/src/sbs/write.rs create mode 100644 crates/ui-egui/src/function/actions.rs create mode 100644 crates/ui-egui/src/function/function_canvas.rs create mode 100644 crates/ui-egui/src/function/function_port.rs create mode 100644 crates/ui-egui/src/function/geometry.rs create mode 100644 crates/ui-egui/src/function/input.rs create mode 100644 crates/ui-egui/src/function/panel.rs create mode 100644 crates/ui-egui/src/function/render.rs delete mode 100644 crates/ui-egui/src/function/selection.rs create mode 100644 crates/ui-egui/src/graph/canvas_geometry.rs create mode 100644 crates/ui-egui/src/graph/canvas_tests.rs create mode 100644 crates/ui-egui/src/graph/edit_menu.rs create mode 100644 crates/ui-egui/src/graph/editor_actions.rs create mode 100644 crates/ui-egui/src/graph/editor_target.rs create mode 100644 crates/ui-egui/src/graph/gesture.rs create mode 100644 crates/ui-egui/src/graph/graph_parent.rs create mode 100644 crates/ui-egui/src/graph/grid.rs create mode 100644 crates/ui-egui/src/graph/input.rs create mode 100644 crates/ui-egui/src/graph/navigation.rs create mode 100644 crates/ui-egui/src/graph/node_style.rs create mode 100644 crates/ui-egui/src/graph/review_tests.rs create mode 100644 crates/ui-egui/src/graph/search.rs create mode 100644 crates/ui-egui/src/graph/selection_commands.rs create mode 100644 crates/ui-egui/src/graph/subgraph_navigation.rs create mode 100644 crates/ui-egui/src/graph/toolbar.rs create mode 100644 crates/ui-egui/src/graph/wire_actions.rs create mode 100644 crates/ui-egui/src/graph/wire_geometry.rs create mode 100644 crates/ui-egui/src/graph_drag_payload.rs create mode 100644 crates/ui-egui/src/material_preview_menu.rs delete mode 100644 crates/ui-egui/src/pattern/selection.rs delete mode 100644 crates/ui-egui/src/properties.rs create mode 100644 crates/ui-egui/src/property/curve.rs create mode 100644 crates/ui-egui/src/property/gradient.rs create mode 100644 crates/ui-egui/src/property/graph.rs create mode 100644 crates/ui-egui/src/property/input.rs create mode 100644 crates/ui-egui/src/property/mod.rs create mode 100644 crates/ui-egui/src/property/node.rs create mode 100644 crates/ui-egui/src/property/parameter.rs create mode 100644 crates/ui-egui/src/property/section.rs diff --git a/Cargo.lock b/Cargo.lock index f6d72648..69db9d50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2463,6 +2463,7 @@ dependencies = [ name = "materialcraft-render" version = "0.1.2" dependencies = [ + "materialcraft-core", "materialcraft-geom", "materialcraft-image", "rayon", diff --git a/crates/core/src/component_usage.rs b/crates/core/src/component_usage.rs new file mode 100644 index 00000000..5c0c6ac1 --- /dev/null +++ b/crates/core/src/component_usage.rs @@ -0,0 +1,81 @@ +/// Input/output semantics shared by node properties, SBS and texture exports +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ComponentUsage { + pub id: &'static str, + pub label: &'static str, +} + +impl ComponentUsage { + pub const ANY: Self = Self { id: "any", label: "Any" }; + pub const ANY_INDEX: u32 = 9; + + // Existing indices are saved in documents; append new entries without reordering + pub const ALL: &'static [Self] = &[ + Self { id: "baseColor", label: "Base color" }, + Self { id: "normal", label: "Normal" }, + Self { id: "roughness", label: "Roughness" }, + Self { id: "metallic", label: "Metallic" }, + Self { id: "height", label: "Height" }, + Self { id: "ambientOcclusion", label: "Ambient occlusion" }, + Self { id: "emissive", label: "Emissive" }, + Self { id: "opacity", label: "Opacity" }, + Self { id: "specular", label: "Specular" }, + Self::ANY, + Self { id: "diffuse", label: "Diffuse" }, + Self { id: "glossiness", label: "Glossiness" }, + Self { id: "specularLevel", label: "Specular level" }, + Self { id: "specularEdgeColor", label: "Specular edge color" }, + Self { id: "anisotropyLevel", label: "Anisotropy level" }, + Self { id: "anisotropyAngle", label: "Anisotropy angle" }, + Self { id: "IOR", label: "Index of refraction" }, + Self { id: "scattering", label: "Scattering" }, + Self { id: "scatteringColor", label: "Scattering color" }, + Self { id: "scatteringDistance", label: "Scattering distance" }, + Self { id: "scatteringDistanceScale", label: "Scattering distance scale" }, + Self { id: "transmissive", label: "Transmissive" }, + Self { id: "translucency", label: "Translucency" }, + Self { id: "absorptionColor", label: "Absorption color" }, + Self { id: "absorptionDistance", label: "Absorption distance" }, + Self { id: "coatOpacity", label: "Coat opacity" }, + Self { id: "coatColor", label: "Coat color" }, + Self { id: "coatRoughness", label: "Coat roughness" }, + Self { id: "coatSpecularLevel", label: "Coat specular level" }, + Self { id: "coatNormal", label: "Coat normal" }, + Self { id: "coatIOR", label: "Coat index of refraction" }, + Self { id: "sheenOpacity", label: "Sheen opacity" }, + Self { id: "sheenColor", label: "Sheen color" }, + Self { id: "sheenRoughness", label: "Sheen roughness" }, + Self { id: "reflection", label: "Reflection" }, + Self { id: "displacement", label: "Displacement" }, + Self { id: "ambient", label: "Ambient" }, + Self { id: "mask", label: "Mask" }, + Self { id: "blendingmask", label: "Blending mask" }, + Self { id: "bump", label: "Bump" }, + Self { id: "user0", label: "User 0" }, + Self { id: "user1", label: "User 1" }, + Self { id: "user2", label: "User 2" }, + Self { id: "user3", label: "User 3" }, + Self { id: "user4", label: "User 4" }, + Self { id: "user5", label: "User 5" }, + Self { id: "user6", label: "User 6" }, + Self { id: "user7", label: "User 7" }, + ]; + + pub const LABELS: &'static [&'static str] = &{ + let mut labels = [""; Self::ALL.len()]; + let mut index = 0; + while index < labels.len() { + labels[index] = Self::ALL[index].label; + index += 1; + } + labels + }; + + pub fn from_index(index: u32) -> Self { + Self::ALL.get(index as usize).copied().unwrap_or(Self::ANY) + } + + pub fn index(id: &str) -> u32 { + Self::ALL.iter().position(|usage| usage.id.eq_ignore_ascii_case(id.trim())).map_or(Self::ANY_INDEX, |index| index as u32) + } +} diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs index be25cac4..b54d43eb 100644 --- a/crates/core/src/graph.rs +++ b/crates/core/src/graph.rs @@ -138,58 +138,17 @@ impl Graph { } pub fn topo_order(&self) -> Vec<NodeId> { - let mut indeg: BTreeMap<NodeId, usize> = self.nodes.iter().map(|n| (n.id, 0)).collect(); - for c in &self.connections { - if let Some(d) = indeg.get_mut(&c.to) - && self.nodes.iter().any(|n| n.id == c.from) - { - *d += 1; - } - } - let mut ready: Vec<NodeId> = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect(); - let mut out = Vec::with_capacity(self.nodes.len()); - while let Some(n) = ready.pop() { - out.push(n); - for c in self.connections.iter().filter(|c| c.from == n) { - if let Some(d) = indeg.get_mut(&c.to) { - *d = d.saturating_sub(1); - if *d == 0 { - ready.push(c.to); - } - } - } - } - out + crate::GraphIndex::new(self).topo_order() } /// Every node upstream of `id` (not including it) pub fn upstream(&self, id: NodeId) -> Vec<NodeId> { - let mut out = Vec::new(); - let mut stack = vec![id]; - while let Some(n) = stack.pop() { - for c in self.connections.iter().filter(|c| c.to == n) { - if !out.contains(&c.from) { - out.push(c.from); - stack.push(c.from); - } - } - } - out + crate::GraphIndex::new(self).upstream(id) } /// Every node downstream of `id` (not including it) pub fn downstream(&self, id: NodeId) -> Vec<NodeId> { - let mut out = Vec::new(); - let mut stack = vec![id]; - while let Some(n) = stack.pop() { - for c in self.connections.iter().filter(|c| c.from == n) { - if !out.contains(&c.to) { - out.push(c.to); - stack.push(c.to); - } - } - } - out + crate::GraphIndex::new(self).downstream(id) } /// The value of exposed input `id` (its default when unset) diff --git a/crates/core/src/graph_index.rs b/crates/core/src/graph_index.rs new file mode 100644 index 00000000..56354b17 --- /dev/null +++ b/crates/core/src/graph_index.rs @@ -0,0 +1,133 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use crate::{Connection, Graph, Node, NodeId}; + +/// Borrowed lookups for one graph operation, rebuilt when the graph changes +pub struct GraphIndex<'a> { + nodes: BTreeMap<NodeId, &'a Node>, + incoming: BTreeMap<NodeId, Vec<&'a Connection>>, + outgoing: BTreeMap<NodeId, Vec<&'a Connection>>, +} + +impl<'a> GraphIndex<'a> { + pub fn new(graph: &'a Graph) -> Self { + let mut nodes = BTreeMap::new(); + for node in &graph.nodes { + nodes.entry(node.id).or_insert(node); + } + + let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new(); + let mut outgoing: BTreeMap<_, Vec<_>> = BTreeMap::new(); + for connection in &graph.connections { + incoming.entry(connection.to).or_default().push(connection); + outgoing.entry(connection.from).or_default().push(connection); + } + + Self { nodes, incoming, outgoing } + } + + pub fn node(&self, id: NodeId) -> Option<&'a Node> { + self.nodes.get(&id).copied() + } + + pub fn incoming(&self, id: NodeId) -> &[&'a Connection] { + self.incoming.get(&id).map_or(&[], Vec::as_slice) + } + + pub fn input_of(&self, id: NodeId, port: &str) -> Option<&'a Connection> { + self.incoming(id).iter().copied().find(|connection| connection.to_port == port) + } + + pub fn topo_order(&self) -> Vec<NodeId> { + let mut degrees: BTreeMap<_, _> = self.nodes.keys().map(|id| (*id, 0usize)).collect(); + for (id, connections) in &self.incoming { + if let Some(degree) = degrees.get_mut(id) { + *degree = connections.iter().filter(|connection| self.nodes.contains_key(&connection.from)).count(); + } + } + + let mut ready: Vec<_> = degrees.iter().filter(|(_, degree)| **degree == 0).map(|(id, _)| *id).collect(); + let mut ordered = Vec::with_capacity(self.nodes.len()); + while let Some(id) = ready.pop() { + ordered.push(id); + for connection in self.outgoing.get(&id).into_iter().flatten() { + if let Some(degree) = degrees.get_mut(&connection.to) { + *degree = degree.saturating_sub(1); + if *degree == 0 { + ready.push(connection.to); + } + } + } + } + + ordered + } + + pub fn upstream(&self, id: NodeId) -> Vec<NodeId> { + self.connected(id, true) + } + + pub fn downstream(&self, id: NodeId) -> Vec<NodeId> { + self.connected(id, false) + } + + pub fn required_nodes(&self, roots: &[NodeId]) -> BTreeSet<NodeId> { + let mut required: BTreeSet<_> = roots.iter().copied().collect(); + let mut pending = roots.to_vec(); + while let Some(id) = pending.pop() { + for connection in self.incoming(id) { + if required.insert(connection.from) { + pending.push(connection.from); + } + } + } + + required + } + + fn connected(&self, root: NodeId, upstream: bool) -> Vec<NodeId> { + let adjacency = if upstream { &self.incoming } else { &self.outgoing }; + + let mut visited = BTreeSet::new(); + let mut connected = Vec::new(); + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + for connection in adjacency.get(&id).into_iter().flatten() { + let next = if upstream { connection.from } else { connection.to }; + + if visited.insert(next) { + connected.push(next); + pending.push(next); + } + } + } + + connected + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn traversal_preserves_document_order_and_dangling_edge_behavior() { + let mut graph = Graph::new("Traversal"); + let first = graph.add_node("uniform", [0.0; 2]); + let second = graph.add_node("dot", [0.0; 2]); + let third = graph.add_node("blend", [0.0; 2]); + let fourth = graph.add_node("dot", [0.0; 2]); + for (from, to, port) in [(first, second, "input"), (first, third, "foreground"), (second, third, "background"), (NodeId(99), fourth, "input")] { + graph.connections.push(Connection { from, from_port: "output".into(), to, to_port: port.into() }); + } + let index = GraphIndex::new(&graph); + assert_eq!(index.topo_order(), [fourth, first, second, third]); + assert_eq!(index.upstream(third), [first, second]); + assert_eq!(index.downstream(first), [second, third]); + assert_eq!(index.required_nodes(&[third, fourth]), BTreeSet::from([first, second, third, fourth, NodeId(99)])); + assert_eq!(index.input_of(third, "background").unwrap().from, second); + + graph.connections.push(Connection { from: third, from_port: "output".into(), to: first, to_port: "input".into() }); + assert_eq!(GraphIndex::new(&graph).topo_order(), [fourth]); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 71f876e2..3ec6fb6a 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -5,6 +5,7 @@ mod attributes; mod base_parameters; mod color; mod comment; +mod component_usage; mod connection; mod core_error; mod curve; @@ -16,7 +17,9 @@ mod function_node; mod gradient; mod gradient_key; mod graph; +mod graph_index; mod graph_kind; +mod material_channel; mod missing_node; mod node; mod node_id; @@ -37,6 +40,7 @@ pub use attributes::Attributes; pub use base_parameters::BaseParameters; pub use color::{linear_to_srgb, parse_color, srgb_to_linear}; pub use comment::Comment; +pub use component_usage::ComponentUsage; pub use connection::Connection; pub use core_error::CoreError; pub use curve::Curve; @@ -48,7 +52,9 @@ pub use function_node::FunctionNode; pub use gradient::Gradient; pub use gradient_key::GradientKey; pub use graph::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2}; +pub use graph_index::GraphIndex; pub use graph_kind::GraphKind; +pub use material_channel::MaterialChannel; pub use missing_node::{MISSING_NODE, missing_ports}; pub use node::Node; pub use node_id::NodeId; diff --git a/crates/core/src/material_channel.rs b/crates/core/src/material_channel.rs new file mode 100644 index 00000000..d29a81bd --- /dev/null +++ b/crates/core/src/material_channel.rs @@ -0,0 +1,50 @@ +use serde::{Deserialize, Serialize}; + +/// Texture channels supported by the material preview +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MaterialChannel { + BaseColor, + Normal, + Roughness, + Metallic, + Height, + AmbientOcclusion, + Emissive, + Opacity, +} + +impl MaterialChannel { + pub const ALL: [Self; 8] = + [Self::BaseColor, Self::Normal, Self::Roughness, Self::Metallic, Self::Height, Self::AmbientOcclusion, Self::Emissive, Self::Opacity]; + + pub fn id(self) -> &'static str { + match self { + Self::BaseColor => "baseColor", + Self::Normal => "normal", + Self::Roughness => "roughness", + Self::Metallic => "metallic", + Self::Height => "height", + Self::AmbientOcclusion => "ambientOcclusion", + Self::Emissive => "emissive", + Self::Opacity => "opacity", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::BaseColor => "Base color", + Self::Normal => "Normal", + Self::Roughness => "Roughness", + Self::Metallic => "Metallic", + Self::Height => "Height", + Self::AmbientOcclusion => "Ambient occlusion", + Self::Emissive => "Emissive", + Self::Opacity => "Opacity", + } + } + + pub fn from_id(id: &str) -> Option<Self> { + Self::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(id)).or_else(|| id.eq_ignore_ascii_case("diffuse").then_some(Self::BaseColor)) + } +} diff --git a/crates/core/src/pattern_graph.rs b/crates/core/src/pattern_graph.rs index fcb80550..d0275a82 100644 --- a/crates/core/src/pattern_graph.rs +++ b/crates/core/src/pattern_graph.rs @@ -22,7 +22,15 @@ impl PatternGraph { return Err("pattern graph exceeds the 4096-node limit".into()); } - let id = (1..=4097).find(|id| self.nodes.iter().all(|node| node.id != *id)).ok_or("no available pattern node id")?; + let mut occupied = [false; 4097]; + for node in &self.nodes { + if let Some(slot) = occupied.get_mut(node.id.saturating_sub(1) as usize) + && node.id != 0 + { + *slot = true; + } + } + let id = occupied.iter().position(|occupied| !occupied).ok_or("no available pattern node id")? as u32 + 1; self.nodes.push(PatternNode { id, kind, @@ -76,3 +84,25 @@ impl PatternGraph { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn allocation_reuses_the_lowest_hole_and_ignores_out_of_range_ids() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let template = graph.nodes[0].clone(); + graph.nodes = [0, 2, 4097, u32::MAX].map(|id| PatternNode { id, ..template.clone() }).to_vec(); + assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 1); + assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 3); + graph.nodes.retain(|node| node.id != 2); + assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 2); + assert_eq!(graph.root, Some(1)); + + graph.nodes.resize(4096, template); + let before = graph.clone(); + assert!(graph.add(PatternNodeKind::Dot).is_err()); + assert_eq!(graph, before); + } +} diff --git a/crates/engine/src/alignment_commands.rs b/crates/engine/src/alignment_commands.rs new file mode 100644 index 00000000..168f18ce --- /dev/null +++ b/crates/engine/src/alignment_commands.rs @@ -0,0 +1,95 @@ +use crate::commands::{CommandSpec, bad, has_graph, strp}; +use crate::selection_target::SelectionTarget; +use crate::{Result, Session, cmd}; +use materialcraft_core::Value; +use serde_json::Value as Json; + +pub(crate) fn specs() -> Vec<CommandSpec> { + vec![cmd!( + "graph.align", + "Align nodes", + [], + None, + "{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?: required for Function/FX-Map, pattern?: owner node id, function?: FunctionGraphTarget, graph?: owning graph index}", + has_graph, + align + )] +} + +fn align(session: &mut Session, parameters: &Json) -> Result<Json> { + let mode = strp(parameters, "mode").unwrap_or("left"); + let ids: Vec<u64> = parameters + .get("ids") + .and_then(Json::as_array) + .map(|ids| ids.iter().filter_map(Json::as_u64).collect()) + .unwrap_or_else(|| session.selection.iter().map(|id| id.0).collect()); + let target = SelectionTarget::resolve(session, parameters)?; + if target.is_some() && parameters.get("ids").and_then(Json::as_array).is_none() { + return Err(bad("graph.align", "ids are required for a Function Graph or FX-Map")); + } + match target { + Some(SelectionTarget::Function(target)) => { + let mut graph = target.current(session)?.clone(); + align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.pos)).collect(), &ids, mode)?; + crate::graph_validation::function(&graph).map_err(|error| bad("graph.align", error))?; + session.edit("Align nodes", |session| target.replace(session, graph))?; + } + Some(SelectionTarget::Pattern(owner)) => { + let mut graph = SelectionTarget::pattern(session, owner)?.clone(); + align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.position)).collect(), &ids, mode)?; + crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.align", error))?; + session.edit("Align nodes", |session| { + session.graph_mut()?.node_mut(owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(()) + })?; + } + None => { + session.edit("Align nodes", |session| { + align_selected(session.graph_mut()?.nodes.iter_mut().map(|node| (node.id.0, &mut node.pos)).collect(), &ids, mode) + })?; + } + } + Ok(Json::Null) +} + +fn align_selected(mut positions: Vec<(u64, &mut [f32; 2])>, ids: &[u64], mode: &str) -> Result<()> { + let present: std::collections::BTreeSet<_> = positions.iter().map(|(id, _)| *id).collect(); + if let Some(id) = ids.iter().find(|id| !present.contains(id)) { + return Err(bad("graph.align", format!("no node {id}"))); + } + let selected: std::collections::BTreeSet<_> = ids.iter().copied().collect(); + positions.retain(|(id, _)| selected.contains(id)); + align_positions(positions.into_iter().map(|(_, position)| position).collect(), mode) +} + +fn align_positions(mut positions: Vec<&mut [f32; 2]>, mode: &str) -> Result<()> { + let axis = match mode { + "left" | "right" | "hcenter" | "hdistribute" => 0, + "top" | "bottom" | "vcenter" | "vdistribute" => 1, + other => return Err(bad("graph.align", format!("unknown mode `{other}`"))), + }; + + if positions.len() < 2 { + return Ok(()); + } + + let minimum = positions.iter().map(|position| position[axis]).fold(f32::MAX, f32::min); + let maximum = positions.iter().map(|position| position[axis]).fold(f32::MIN, f32::max); + if mode.ends_with("distribute") { + positions.sort_by(|left, right| left[axis].total_cmp(&right[axis])); + let step = (maximum - minimum) / (positions.len() - 1) as f32; + for (index, position) in positions.iter_mut().enumerate() { + position[axis] = minimum + step * index as f32; + } + } else { + let value = match mode { + "left" | "top" => minimum, + "right" | "bottom" => maximum, + _ => (minimum + maximum) * 0.5, + }; + for position in positions { + position[axis] = value; + } + } + Ok(()) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 0d955979..8c7089f1 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -51,7 +51,9 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::atomic_sample_commands::specs()); v.extend(crate::material_cmds::specs()); v.extend(crate::edit_cmds::specs()); + v.extend(crate::embedded_edit_commands::specs()); v.extend(crate::graph_cmds::specs()); + v.extend(crate::alignment_commands::specs()); v.extend(crate::annotation_commands::specs()); v.extend(crate::frame_commands::specs()); v.extend(crate::function_commands::specs()); @@ -62,6 +64,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::connection_commands::specs()); v.extend(crate::value_input_commands::specs()); v.extend(crate::view_cmds::specs()); + v.extend(crate::material_preview_commands::specs()); v.extend(crate::wire_cmds::specs()); v }) @@ -74,6 +77,9 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// Run a command by id with JSON params (empty params = defaults, never a dialog) pub fn execute(s: &mut Session, id: &str, params: &J) -> Result<J> { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if let Some(result) = crate::selection_commands::execute(s, id, params) { + return result; + } (spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let result = (spec.run)(s, params)?; if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) { @@ -90,7 +96,9 @@ pub fn list(s: &Session, filter: Option<&str>) -> J { command_specs() .iter() .filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f))) - .map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok()})) + .map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": if crate::selection_commands::supports(c.id) { + format!("{}; optional function: FunctionGraphTarget or pattern: owner node id, graph: owning graph index; embedded targets use explicit ids; copy returns clip", c.params) + } else { c.params.to_string() }, "enabled": crate::selection_commands::enabled(s, c.id, &J::Null).unwrap_or_else(|| (c.enabled)(s).is_ok())})) .collect(), ) } diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index fcc8ac6e..92cbdddb 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -126,7 +126,7 @@ fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32; map.insert(n.id, id); let mut c = n.clone(); c.id = id; - c.pos = crate::graph_grid::snap_position([n.pos[0] + shift[0], n.pos[1] + shift[1]], snap); + c.pos = crate::graph_grid::translate(n.pos, shift, snap); g.nodes.push(c); } for c in &clip.connections { diff --git a/crates/engine/src/embedded_clipboard.rs b/crates/engine/src/embedded_clipboard.rs new file mode 100644 index 00000000..10e77585 --- /dev/null +++ b/crates/engine/src/embedded_clipboard.rs @@ -0,0 +1,9 @@ +use materialcraft_core::{FunctionNode, PatternNode}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum EmbeddedClipboard { + Function { source: String, nodes: Vec<FunctionNode> }, + Pattern { source: String, nodes: Vec<PatternNode> }, +} diff --git a/crates/engine/src/embedded_edit_commands.rs b/crates/engine/src/embedded_edit_commands.rs new file mode 100644 index 00000000..71eb2d72 --- /dev/null +++ b/crates/engine/src/embedded_edit_commands.rs @@ -0,0 +1,88 @@ +use crate::{ + FunctionEdit, FunctionGraphTarget, PatternEdit, Result, Session, cmd, + commands::{CommandSpec, bad, has_graph}, +}; + +use materialcraft_core::{NodeId, Value}; +use serde_json::{Value as Json, json}; + +pub(crate) fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + "graph.function.edit", + "Edit function node", + [], + None, + "{target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}, edit: {action: add|move|connect|value|output, ...}, merge?: false}", + has_graph, + function + ), + cmd!( + "graph.pattern.edit", + "Edit FX-Map node", + [], + None, + "{id: owner, edit: {action: add|move|connect|disconnect|root|value, ...}, merge?: false}", + has_graph, + pattern + ), + cmd!("edit.finish", "Finish edit gesture", [], None, "{} ends the current undo group", crate::commands::always, |session, _| { + session.finish_edit(); + Ok(Json::Null) + }), + ] +} + +fn commit(session: &mut Session, label: &str, key: Option<String>, run: impl FnOnce(&mut Session) -> Result<Json>) -> Result<Json> { + match key { + Some(key) => session.edit_merged(&key, label, run), + None => session.edit(label, run), + } +} + +fn function(session: &mut Session, parameters: &Json) -> Result<Json> { + let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"}))) + .map_err(|error| bad("graph.function.edit", error.to_string()))?; + let edit: FunctionEdit = + serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.edit", error.to_string()))?; + let current = target.current(session)?; + if let FunctionEdit::Add { operation, .. } = &edit + && !target.available_operations(session).any(|definition| definition.id == operation) + { + return Err(bad("graph.function.edit", "this operation is not available in the target function graph")); + } + let mut graph = current.clone(); + let result = edit.apply(&mut graph).map_err(|error| bad("graph.function.edit", error))?; + crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.edit", error))?; + let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true)) + .then(|| edit.merge_key()) + .flatten() + .map(|key| format!("function:{}:{target:?}:{key}", session.graph)); + commit(session, "Edit Function Graph", key, |session| { + target.replace(session, graph)?; + Ok(result) + }) +} + +fn pattern(session: &mut Session, parameters: &Json) -> Result<Json> { + let id = NodeId(parameters.get("id").and_then(Json::as_u64).ok_or_else(|| bad("graph.pattern.edit", "id is required"))?); + let node = session.graph()?.node(id)?; + if node.def != "fx_map" { + return Err(bad("graph.pattern.edit", "the node is not an FX-Map")); + } + let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| ¶meter.default)); + let Some(Value::PatternGraph(graph)) = value else { return Err(bad("graph.pattern.edit", "missing FX-Map graph")) }; + let mut graph = (**graph).clone(); + let edit: PatternEdit = + serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.edit", error.to_string()))?; + let result = edit.apply(&mut graph).map_err(|error| bad("graph.pattern.edit", error))?; + crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.edit", error))?; + let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true)) + .then(|| edit.merge_key()) + .flatten() + .map(|key| format!("pattern:{}:{}:{key}", session.graph, id.0)); + commit(session, "Edit FX-Map graph", key, |session| { + session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(result) + }) +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0837b5a8..6d99b63a 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -83,6 +83,7 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> { }; session.pkg.graphs.push(graph); session.graph = session.pkg.graphs.len() - 1; + session.open_material_preview(); session.selection.clear(); session.annotation_selection = None; session.view2d.node = None; @@ -101,9 +102,12 @@ fn new_package(s: &mut Session, p: &J) -> Result<J> { pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) { s.pkg = pkg; s.clipboard = None; + s.embedded_clipboard = None; s.clear_decoded(); s.path = path; s.graph = 0; + s.material_preview = crate::MaterialPreview::for_graph(&s.pkg, 0); + s.clear_preview_results(); s.selection.clear(); s.annotation_selection = None; s.view2d.node = None; @@ -130,6 +134,7 @@ pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option<Strin let (manifest, source) = materialcraft_formats::material::read_material(bytes)?; replace_package(session, materialcraft_formats::sbs::read_sbs(&source, "source.sbs", &|_| None)?.pkg, None); session.graph = session.pkg.graph_by_name(&manifest.graph).map_or(0, |(index, _)| index); + session.open_material_preview(); return Ok(()); } diff --git a/crates/engine/src/function_commands.rs b/crates/engine/src/function_commands.rs index 9a776c5e..2f4b9bb5 100644 --- a/crates/engine/src/function_commands.rs +++ b/crates/engine/src/function_commands.rs @@ -1,23 +1,31 @@ use crate::commands::{CommandSpec, bad, has_graph}; -use crate::{Result, Session, cmd}; +use crate::{FunctionGraphTarget, Result, Session, cmd}; use materialcraft_core::FunctionGraph; use serde_json::{Value as Json, json}; pub(crate) fn specs() -> Vec<CommandSpec> { - vec![cmd!("graph.function.set", "Edit Function Graph", [], None, "{function} replaces the current function graph", has_graph, set)] + vec![cmd!( + "graph.function.set", + "Edit Function Graph", + [], + None, + "{function, target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}} replaces a function graph", + has_graph, + set + )] } fn set(session: &mut Session, parameters: &Json) -> Result<Json> { - if session.graph()?.function.is_none() { - return Err(bad("graph.function.set", "the current graph is not a Function Graph")); - } + let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"}))) + .map_err(|error| bad("graph.function.set", error.to_string()))?; + target.current(session)?; let graph: FunctionGraph = serde_json::from_value(parameters.get("function").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.set", error.to_string()))?; - materialcraft_nodes::function::node_types(&graph).map_err(|error| bad("graph.function.set", error))?; + crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.set", error))?; session.edit("Edit Function Graph", |session| { - session.graph_mut()?.function = Some(graph); + target.replace(session, graph)?; Ok(json!({})) }) } diff --git a/crates/engine/src/function_edit.rs b/crates/engine/src/function_edit.rs new file mode 100644 index 00000000..24494325 --- /dev/null +++ b/crates/engine/src/function_edit.rs @@ -0,0 +1,105 @@ +use materialcraft_core::{FunctionGraph, FunctionNode, Value}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value as Json, json}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "camelCase")] +pub enum FunctionEdit { + Add { + operation: String, + at: [f32; 2], + #[serde(default)] + snap: bool, + }, + Move { + ids: Vec<u32>, + by: [f32; 2], + #[serde(default)] + snap: bool, + }, + Connect { + from: u32, + to: u32, + input: usize, + }, + Value { + id: u32, + value: Value, + }, + Output { + id: u32, + }, +} + +impl FunctionEdit { + pub(crate) fn apply(&self, graph: &mut FunctionGraph) -> Result<Json, String> { + match self { + Self::Add { operation, at, snap } => { + if graph.nodes.len() >= 4096 { + return Err("the function exceeds the 4096-node limit".into()); + } + let definition = materialcraft_nodes::function::definition(operation).ok_or("unknown function operation")?; + let id = graph.next_id(); + graph.nodes.push(FunctionNode { + id, + type_code: 0, + op: operation.clone(), + inputs: vec![None; definition.inputs.len()], + value: materialcraft_nodes::function::default_value(operation), + pos: crate::graph_grid::snap_position(*at, *snap), + }); + if graph.output.is_none() { + graph.output = Some(id); + } + return Ok(json!({"id": id})); + } + Self::Move { ids, by, snap } => { + for id in ids { + if graph.node(*id).is_none() { + return Err(format!("no function node {id}")); + } + } + for node in &mut graph.nodes { + if ids.contains(&node.id) { + node.pos = crate::graph_grid::translate(node.pos, *by, *snap); + } + } + } + Self::Connect { from, to, input } => { + if from == to || graph.node(*from).is_none() { + return Err("invalid function source".into()); + } + let node = graph.nodes.iter_mut().find(|node| node.id == *to).ok_or("missing function destination")?; + let count = materialcraft_nodes::function::definition(&node.op).map_or(0, |definition| definition.inputs.len()); + if *input >= count { + return Err("invalid function input".into()); + } + node.inputs.resize(count, None); + if let Some(slot) = node.inputs.get_mut(*input) { + *slot = Some(*from); + } + } + Self::Value { id, value } => { + let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing function node")?; + if node.value.is_none() { + return Err("the operation has no editable value".into()); + } + node.value = Some(value.clone()); + } + Self::Output { id } => { + if graph.node(*id).is_none() { + return Err("missing output node".into()); + } + graph.output = Some(*id); + } + } + Ok(Json::Null) + } + + pub(crate) fn merge_key(&self) -> Option<String> { + match self { + Self::Value { id, .. } => Some(format!("value:{id}")), + _ => None, + } + } +} diff --git a/crates/engine/src/function_graph_target.rs b/crates/engine/src/function_graph_target.rs new file mode 100644 index 00000000..883355ad --- /dev/null +++ b/crates/engine/src/function_graph_target.rs @@ -0,0 +1,80 @@ +use crate::{Result, Session, commands::bad}; +use materialcraft_core::{FunctionGraph, NodeId, Value}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum FunctionGraphTarget { + #[default] + Graph, + Parameter { + node: NodeId, + parameter: String, + }, + Dynamic { + node: NodeId, + parameter: String, + }, + Pattern { + owner: NodeId, + node: u32, + parameter: String, + }, +} + +impl FunctionGraphTarget { + pub fn available_operations(&self, session: &Session) -> impl Iterator<Item = &'static materialcraft_nodes::function::FunctionDefinition> + use<> { + let value_processor = matches!(self, Self::Parameter { node, parameter } + if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor")); + materialcraft_nodes::function::FUNCTIONS.iter().filter(move |operation| !value_processor || !matches!(operation.id, "samplelum" | "samplecol")) + } + + pub fn current<'a>(&self, session: &'a Session) -> Result<&'a FunctionGraph> { + let document = session.graph()?; + let value = match self { + Self::Graph => return document.function.as_ref().ok_or_else(|| bad("graph.function.edit", "no Function Graph is open")), + Self::Dynamic { node, parameter } => { + return document.node(*node)?.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing parameter function")); + } + Self::Parameter { node, parameter } => { + let node = document.node(*node)?; + node.params.get(parameter).or_else(|| materialcraft_nodes::find(&node.def)?.param(parameter).map(|parameter| ¶meter.default)) + } + Self::Pattern { owner, node, parameter } => { + let Some(Value::PatternGraph(graph)) = document.node(*owner)?.params.get("pattern") else { + return Err(bad("graph.function.edit", "missing FX-Map graph")); + }; + + graph.nodes.iter().find(|candidate| candidate.id == *node).and_then(|node| node.parameters.get(parameter)) + } + }; + + match value { + Some(Value::Function(graph)) => Ok(graph), + _ => Err(bad("graph.function.edit", "missing function")), + } + } + + pub(crate) fn replace(&self, session: &mut Session, function: FunctionGraph) -> Result<()> { + self.current(session)?; + let document = session.graph_mut()?; + match self { + Self::Graph => document.function = Some(function), + Self::Dynamic { node, parameter } => { + document.node_mut(*node)?.functions.insert(parameter.clone(), function); + } + Self::Parameter { node, parameter } => { + document.node_mut(*node)?.params.insert(parameter.clone(), Value::Function(Box::new(function))); + } + Self::Pattern { owner, node, parameter } => { + let Some(Value::PatternGraph(graph)) = document.node_mut(*owner)?.params.get_mut("pattern") else { + return Err(bad("graph.function.edit", "missing FX-Map graph")); + }; + + let node = graph.nodes.iter_mut().find(|candidate| candidate.id == *node).ok_or_else(|| bad("graph.function.edit", "missing FX-Map node"))?; + node.parameters.insert(parameter.clone(), Value::Function(Box::new(function))); + } + } + Ok(()) + } +} diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 9edee5c1..852fff2c 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -51,7 +51,6 @@ pub(crate) fn specs() -> Vec<CommandSpec> { cmd!("graph.select", "Select nodes", [], None, "{ids, add?: bool}", has_graph, select), cmd!("graph.selectUpstream", "Select upstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, true)), cmd!("graph.selectDownstream", "Select downstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, false)), - cmd!("graph.align", "Align nodes", [], None, "{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?}", has_selection, align), cmd!( "graph.createFromSelection", "Create graph from selection", @@ -79,6 +78,7 @@ fn graph_index(s: &Session, p: &J) -> Result<usize> { fn open(s: &mut Session, p: &J) -> Result<J> { let i = graph_index(s, p)?; s.graph = i; + s.open_material_preview(); s.selection.clear(); s.annotation_selection = None; s.view2d.node = None; @@ -110,7 +110,10 @@ fn delete(s: &mut Session, p: &J) -> Result<J> { let i = graph_index(s, p)?; s.edit("Delete graph", |s| { s.pkg.graphs.remove(i); + s.material_preview.remove_graph(i); + s.clear_preview_results(); s.clipboard = None; + s.embedded_clipboard = None; s.graph = s.graph.min(s.pkg.graphs.len().saturating_sub(1)); s.selection.clear(); s.annotation_selection = None; @@ -126,6 +129,7 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> { g.name = s.pkg.unique_graph_name(&g.name); s.pkg.graphs.push(g); s.graph = s.pkg.graphs.len() - 1; + s.open_material_preview(); s.selection.clear(); s.annotation_selection = None; Ok(json!({"graph": s.graph})) @@ -350,41 +354,6 @@ fn select_stream(s: &mut Session, p: &J, up: bool) -> Result<J> { Ok(json!({"selected": s.selection.len()})) } -fn align(s: &mut Session, p: &J) -> Result<J> { - let ids = ids_param(s, "graph.align", p)?; - let mode = strp(p, "mode").unwrap_or("left").to_string(); - s.edit("Align nodes", |s| { - let g = s.graph_mut()?; - let mut nodes: Vec<&mut materialcraft_core::Node> = g.nodes.iter_mut().filter(|n| ids.contains(&n.id)).collect(); - if nodes.len() < 2 { - return Ok(J::Null); - } - let xs: Vec<f32> = nodes.iter().map(|n| n.pos[0]).collect(); - let ys: Vec<f32> = nodes.iter().map(|n| n.pos[1]).collect(); - let (minx, maxx) = (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max)); - let (miny, maxy) = (ys.iter().copied().fold(f32::MAX, f32::min), ys.iter().copied().fold(f32::MIN, f32::max)); - match mode.as_str() { - "left" => nodes.iter_mut().for_each(|n| n.pos[0] = minx), - "right" => nodes.iter_mut().for_each(|n| n.pos[0] = maxx), - "top" => nodes.iter_mut().for_each(|n| n.pos[1] = miny), - "bottom" => nodes.iter_mut().for_each(|n| n.pos[1] = maxy), - "hcenter" => nodes.iter_mut().for_each(|n| n.pos[0] = (minx + maxx) * 0.5), - "vcenter" => nodes.iter_mut().for_each(|n| n.pos[1] = (miny + maxy) * 0.5), - "hdistribute" | "vdistribute" => { - let k = usize::from(mode == "vdistribute"); - nodes.sort_by(|a, b| a.pos[k].total_cmp(&b.pos[k])); - let (lo, hi) = if k == 0 { (minx, maxx) } else { (miny, maxy) }; - let step = (hi - lo) / (nodes.len() - 1) as f32; - for (i, n) in nodes.iter_mut().enumerate() { - n.pos[k] = lo + step * i as f32; - } - } - other => return Err(bad("graph.align", format!("unknown mode `{other}`"))), - } - Ok(J::Null) - }) -} - fn from_selection(s: &mut Session, p: &J) -> Result<J> { let ids = ids_param(s, "graph.createFromSelection", p)?; let base = strp(p, "name").unwrap_or("Sub_graph").to_string(); @@ -415,7 +384,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result<J> { } let ident = format!("output_{}", outputs.len() + 1); let id = sub.add_node("output", [rect[0] + rect[2] + 80.0, rect[1] + outputs.len() as f32 * 120.0]); - let usage = materialcraft_nodes::atomic::USAGE_IDS.len() as u32 - 1; + let usage = materialcraft_core::ComponentUsage::ANY_INDEX; sub.node_mut(id)?.params.extend([("identifier".to_string(), Value::Text(ident.clone())), ("usage".to_string(), Value::Enum(usage))]); sub.connect(c.from, &c.from_port, id, "input")?; outputs.push((c.from, c.from_port.clone(), ident)); diff --git a/crates/engine/src/graph_edit/editable_graph.rs b/crates/engine/src/graph_edit/editable_graph.rs new file mode 100644 index 00000000..b34f4164 --- /dev/null +++ b/crates/engine/src/graph_edit/editable_graph.rs @@ -0,0 +1,17 @@ +/// The data access needed by shared function and pattern editing operations +pub trait EditableGraph { + type Node: Clone; + + const LINKS_ARE_INPUTS: bool; + const RELINK: bool; + + fn nodes(&self) -> &[Self::Node]; + fn nodes_mut(&mut self) -> &mut Vec<Self::Node>; + fn id(node: &Self::Node) -> u32; + fn position(node: &mut Self::Node) -> &mut [f32; 2]; + fn links(node: &Self::Node) -> &[Option<u32>]; + fn links_mut(node: &mut Self::Node) -> &mut [Option<u32>]; + fn result(&mut self) -> &mut Option<u32>; + fn check_capacity(&self, additional: usize) -> Result<(), String>; + fn insert(&mut self, node: Self::Node) -> Result<u32, String>; +} diff --git a/crates/engine/src/graph_edit/function_graph.rs b/crates/engine/src/graph_edit/function_graph.rs new file mode 100644 index 00000000..eba3947f --- /dev/null +++ b/crates/engine/src/graph_edit/function_graph.rs @@ -0,0 +1,45 @@ +use super::EditableGraph; +use materialcraft_core::{FunctionGraph, FunctionNode}; + +impl EditableGraph for FunctionGraph { + type Node = FunctionNode; + + const LINKS_ARE_INPUTS: bool = true; + const RELINK: bool = true; + + fn nodes(&self) -> &[FunctionNode] { + &self.nodes + } + fn nodes_mut(&mut self) -> &mut Vec<FunctionNode> { + &mut self.nodes + } + fn id(node: &FunctionNode) -> u32 { + node.id + } + fn position(node: &mut FunctionNode) -> &mut [f32; 2] { + &mut node.pos + } + fn links(node: &FunctionNode) -> &[Option<u32>] { + &node.inputs + } + fn links_mut(node: &mut FunctionNode) -> &mut [Option<u32>] { + &mut node.inputs + } + fn result(&mut self) -> &mut Option<u32> { + &mut self.output + } + + fn check_capacity(&self, additional: usize) -> Result<(), String> { + if self.nodes.len().saturating_add(additional) > 4096 { + return Err("function exceeds the 4096-node limit".into()); + } + Ok(()) + } + + fn insert(&mut self, mut node: FunctionNode) -> Result<u32, String> { + let id = self.next_id(); + node.id = id; + self.nodes.push(node); + Ok(id) + } +} diff --git a/crates/engine/src/graph_edit/mod.rs b/crates/engine/src/graph_edit/mod.rs new file mode 100644 index 00000000..1215fe96 --- /dev/null +++ b/crates/engine/src/graph_edit/mod.rs @@ -0,0 +1,9 @@ +//! Editing rules shared by Function Graphs and FX-Map graphs + +mod editable_graph; +mod function_graph; +mod pattern_graph; +mod selection; + +pub use editable_graph::EditableGraph; +pub use selection::{enabled, read, remove, run}; diff --git a/crates/engine/src/graph_edit/pattern_graph.rs b/crates/engine/src/graph_edit/pattern_graph.rs new file mode 100644 index 00000000..fd98af8d --- /dev/null +++ b/crates/engine/src/graph_edit/pattern_graph.rs @@ -0,0 +1,47 @@ +use super::EditableGraph; +use materialcraft_core::{PatternGraph, PatternNode}; + +impl EditableGraph for PatternGraph { + type Node = PatternNode; + + const LINKS_ARE_INPUTS: bool = false; + const RELINK: bool = false; + + fn nodes(&self) -> &[PatternNode] { + &self.nodes + } + fn nodes_mut(&mut self) -> &mut Vec<PatternNode> { + &mut self.nodes + } + fn id(node: &PatternNode) -> u32 { + node.id + } + fn position(node: &mut PatternNode) -> &mut [f32; 2] { + &mut node.position + } + fn links(node: &PatternNode) -> &[Option<u32>] { + &node.children + } + fn links_mut(node: &mut PatternNode) -> &mut [Option<u32>] { + &mut node.children + } + fn result(&mut self) -> &mut Option<u32> { + &mut self.root + } + + fn check_capacity(&self, additional: usize) -> Result<(), String> { + if self.nodes.len().saturating_add(additional) > 4096 { + return Err("pattern graph exceeds the 4096-node limit".into()); + } + Ok(()) + } + + fn insert(&mut self, mut node: PatternNode) -> Result<u32, String> { + let id = self.add(node.kind)?; + node.id = id; + if let Some(destination) = self.nodes.last_mut() { + *destination = node; + } + Ok(id) + } +} diff --git a/crates/engine/src/graph_edit/selection.rs b/crates/engine/src/graph_edit/selection.rs new file mode 100644 index 00000000..9037d42a --- /dev/null +++ b/crates/engine/src/graph_edit/selection.rs @@ -0,0 +1,127 @@ +use super::EditableGraph; +use std::collections::{BTreeMap, BTreeSet}; + +pub fn enabled<G: EditableGraph>(selection: &[u32], clipboard: &[G::Node], command: &str) -> Option<bool> { + Some(match command { + "graph.select" | "edit.selectAll" | "edit.selectNone" => true, + "edit.paste" | "edit.pasteWithoutLinks" => !clipboard.is_empty(), + "edit.copy" | "edit.cut" | "edit.delete" | "edit.duplicate" | "edit.duplicateWithoutLinks" | "graph.selectUpstream" | "graph.selectDownstream" => { + !selection.is_empty() + } + "edit.deleteRelink" => G::RELINK && !selection.is_empty(), + "graph.node.disable" => false, + _ => return None, + }) +} + +pub fn run<G: EditableGraph>( + graph: &mut G, + selection: &mut Vec<u32>, + clipboard: &mut Vec<G::Node>, + command: &str, + at: [f32; 2], + snap: bool, +) -> Result<bool, String> { + if read(graph, selection, clipboard, command) { + return Ok(false); + } + match command { + "edit.cut" => { + *clipboard = selected::<G>(graph, selection); + return Ok(remove(graph, selection, false)); + } + "edit.delete" | "edit.deleteRelink" => return Ok(remove(graph, selection, G::RELINK && command == "edit.deleteRelink")), + "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { + let duplicate = command.starts_with("edit.duplicate"); + let mut nodes = if duplicate { selected::<G>(graph, selection) } else { clipboard.clone() }; + graph.check_capacity(nodes.len())?; + let anchor = nodes.first_mut().map_or([0.0; 2], |node| *G::position(node)); + let offset = if duplicate { [32.0; 2] } else { [at[0] - anchor[0], at[1] - anchor[1]] }; + let present: BTreeSet<_> = graph.nodes().iter().map(G::id).collect(); + let mut ids = BTreeMap::new(); + for mut node in nodes { + let original = G::id(&node); + let position = G::position(&mut node); + *position = crate::graph_grid::translate(*position, offset, snap); + ids.insert(original, graph.insert(node)?); + } + let inserted: BTreeSet<_> = ids.values().copied().collect(); + for node in graph.nodes_mut().iter_mut().filter(|node| inserted.contains(&G::id(node))) { + for link in G::links_mut(node) { + *link = link.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks") && present.contains(&id)).then_some(id))); + } + } + *selection = ids.values().copied().collect(); + return Ok(!ids.is_empty()); + } + _ => {} + } + Ok(false) +} + +fn selected<G: EditableGraph>(graph: &G, selection: &[u32]) -> Vec<G::Node> { + let selection: BTreeSet<_> = selection.iter().copied().collect(); + graph.nodes().iter().filter(|node| selection.contains(&G::id(node))).cloned().collect() +} + +pub fn remove<G: EditableGraph>(graph: &mut G, selection: &mut Vec<u32>, relink: bool) -> bool { + let selection_set: BTreeSet<_> = selection.iter().copied().collect(); + let replacements: BTreeMap<_, _> = graph + .nodes() + .iter() + .filter(|node| selection_set.contains(&G::id(node))) + .map(|node| (G::id(node), if relink { G::links(node).first().copied().flatten() } else { None })) + .collect(); + graph.nodes_mut().retain(|node| !selection_set.contains(&G::id(node))); + for node in graph.nodes_mut() { + for link in G::links_mut(node) { + let mut seen = BTreeSet::new(); + while let Some(id) = *link { + let Some(replacement) = replacements.get(&id) else { break }; + + if !seen.insert(id) { + *link = None; + break; + } + *link = *replacement; + } + } + } + if graph.result().is_some_and(|id| selection_set.contains(&id)) { + *graph.result() = None; + } + selection.clear(); + !replacements.is_empty() +} + +/// Apply selection and copy actions without cloning or mutating the graph +pub fn read<G: EditableGraph>(graph: &G, selection: &mut Vec<u32>, clipboard: &mut Vec<G::Node>, command: &str) -> bool { + match command { + "edit.selectAll" => *selection = graph.nodes().iter().map(G::id).collect(), + "edit.selectNone" => selection.clear(), + "graph.select" => {} + "edit.copy" => *clipboard = selected::<G>(graph, selection), + "graph.selectUpstream" | "graph.selectDownstream" => { + let follow_links = (command == "graph.selectUpstream") == G::LINKS_ARE_INPUTS; + let mut neighbors: BTreeMap<u32, Vec<u32>> = BTreeMap::new(); + for node in graph.nodes() { + for link in G::links(node).iter().flatten() { + let (from, to) = if follow_links { (G::id(node), *link) } else { (*link, G::id(node)) }; + neighbors.entry(from).or_default().push(to); + } + } + let mut visited = BTreeSet::new(); + let mut pending = selection.clone(); + while let Some(id) = pending.pop() { + if visited.insert(id) + && let Some(next) = neighbors.get(&id) + { + pending.extend(next); + } + } + *selection = visited.into_iter().collect(); + } + _ => return false, + } + true +} diff --git a/crates/engine/src/graph_grid.rs b/crates/engine/src/graph_grid.rs index 4d659811..c4550a04 100644 --- a/crates/engine/src/graph_grid.rs +++ b/crates/engine/src/graph_grid.rs @@ -6,3 +6,8 @@ pub fn snap_position(position: [f32; 2], enabled: bool) -> [f32; 2] { if enabled { (coordinate / GRID_SPACING).round() * GRID_SPACING } else { coordinate } }) } + +/// Apply the same movement and snapping rule during a drag preview and its commit +pub fn translate(position: [f32; 2], offset: [f32; 2], snap: bool) -> [f32; 2] { + snap_position([position[0] + offset[0], position[1] + offset[1]], snap) +} diff --git a/crates/engine/src/graph_validation.rs b/crates/engine/src/graph_validation.rs new file mode 100644 index 00000000..aaec2841 --- /dev/null +++ b/crates/engine/src/graph_validation.rs @@ -0,0 +1,50 @@ +use materialcraft_core::{FunctionGraph, PatternGraph, Value}; + +fn function_structure(graph: &FunctionGraph) -> Result<(), String> { + materialcraft_nodes::function::node_types(graph)?; + if graph.nodes.iter().any(|node| node.pos.iter().any(|coordinate| !coordinate.is_finite())) { + return Err("function node positions must be finite".into()); + } + Ok(()) +} + +pub(crate) fn pattern(graph: &PatternGraph) -> Result<(), String> { + pattern_structure(graph)?; + values(graph.nodes.iter().flat_map(|node| node.parameters.values())) +} + +pub(crate) fn function(graph: &FunctionGraph) -> Result<(), String> { + function_structure(graph)?; + values(graph.nodes.iter().filter_map(|node| node.value.as_ref())) +} + +pub(crate) fn value(value: &Value) -> Result<(), String> { + values(std::iter::once(value)) +} + +fn values<'a>(values: impl Iterator<Item = &'a Value>) -> Result<(), String> { + // Nested graph values are checked without recursive traversal + let mut pending: Vec<_> = values.collect(); + while let Some(value) = pending.pop() { + match value { + Value::Function(graph) => { + function_structure(graph)?; + pending.extend(graph.nodes.iter().filter_map(|node| node.value.as_ref())); + } + Value::PatternGraph(graph) => { + pattern_structure(graph)?; + pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values())); + } + _ => {} + } + } + Ok(()) +} + +fn pattern_structure(graph: &PatternGraph) -> Result<(), String> { + graph.validate()?; + if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) { + return Err("pattern node positions must be finite".into()); + } + Ok(()) +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 82a0adb5..5658d5e4 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -61,6 +61,13 @@ pub fn session(s: &Session, graph: Option<usize>) -> J { "selection": s.selection.iter().map(|i| i.0).collect::<Vec<_>>(), "view2d": s.view2d, "view3d": s.view3d, + "material3d": { + "assignments": s.material_preview, + "channels": s.material_preview.sources(&s.pkg).into_iter().map(|(channel, source)| { + let image = s.material_image(&source); + json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())}) + }).collect::<Vec<_>>(), + }, "previewSize": s.preview_size, "camera": s.camera, "cookMs": s.cooked.ms, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fea2ea0f..a2a8846f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,10 +1,26 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod material_preview; +mod material_preview_commands; +mod material_source; +mod preview_cook; +pub use material_preview::MaterialPreview; +pub use material_source::MaterialSource; +pub use preview_cook::PreviewCook; + +mod alignment_commands; +mod embedded_clipboard; +mod graph_validation; +pub mod selection_commands; +mod selection_target; +pub use embedded_clipboard::EmbeddedClipboard; +pub use selection_target::SelectionTarget; pub mod commands; pub mod edit_cmds; pub mod file_cmds; pub mod graph_cmds; +pub mod graph_edit; pub mod graph_grid; pub mod inspect; pub mod material_cmds; @@ -59,3 +75,11 @@ mod pattern_graph_commands; mod snapshot; pub use annotation_selection::AnnotationSelection; pub use frame_contents::FrameContents; + +mod embedded_edit_commands; +mod function_edit; +mod function_graph_target; +mod pattern_edit; +pub use function_edit::FunctionEdit; +pub use function_graph_target::FunctionGraphTarget; +pub use pattern_edit::PatternEdit; diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index 3de28a46..f19d8c15 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use serde_json::{Value as J, json}; +use materialcraft_core::ComponentUsage; use materialcraft_core::Graph; #[cfg(any(test, not(target_arch = "wasm32")))] use materialcraft_core::Value; @@ -10,7 +11,6 @@ use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Pa use materialcraft_formats::{Depth, encode}; #[cfg(test)] use materialcraft_image::Image; -use materialcraft_nodes::atomic::USAGE_IDS; #[cfg(not(target_arch = "wasm32"))] use crate::commands::u64p; @@ -83,7 +83,14 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec size = [img.w, img.h]; } if entries.is_empty() { - return Err(bad("file.exportMaterial", format!("graph `{}` has no outputs with a material usage ({})", g.name, USAGE_IDS.join(", ")))); + return Err(bad( + "file.exportMaterial", + format!( + "graph `{}` has no outputs with a material usage ({})", + g.name, + ComponentUsage::ALL.iter().filter(|usage| **usage != ComponentUsage::ANY).map(|usage| usage.id).collect::<Vec<_>>().join(", ") + ), + )); } let manifest = Manifest { format: FORMAT.into(), diff --git a/crates/engine/src/material_preview.rs b/crates/engine/src/material_preview.rs new file mode 100644 index 00000000..ba56c6b7 --- /dev/null +++ b/crates/engine/src/material_preview.rs @@ -0,0 +1,93 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::hash::{Hash, Hasher}; + +use materialcraft_core::{MaterialChannel, Package}; +use materialcraft_image::Image; +use serde::{Deserialize, Serialize}; + +use crate::{MaterialSource, Session}; + +/// Automatic graph outputs with explicit channel overrides +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MaterialPreview { + pub graph: Option<usize>, + pub channels: BTreeMap<MaterialChannel, MaterialSource>, +} + +impl MaterialPreview { + pub fn for_graph(package: &Package, graph: usize) -> Self { + Self { graph: package.graphs.get(graph).filter(|graph| graph.function.is_none()).map(|_| graph), channels: BTreeMap::new() } + } + + pub fn sources(&self, package: &Package) -> BTreeMap<MaterialChannel, MaterialSource> { + let mut sources = BTreeMap::new(); + if let Some(index) = self.graph + && let Some(graph) = package.graphs.get(index) + { + for node in graph.nodes.iter().filter(|node| node.def == "output") { + let source = MaterialSource { graph: index, node: node.id, port: "output".into() }; + if let Some(channel) = MaterialChannel::from_id(materialcraft_eval::output_usage(node)) + && source.is_image(package) + { + sources.entry(channel).or_insert(source); + } + } + } + sources.extend(self.channels.clone()); + sources + } + + pub fn graphs(&self) -> BTreeSet<usize> { + self.graph.into_iter().chain(self.channels.values().map(|source| source.graph)).collect() + } + + pub(crate) fn remove_graph(&mut self, graph: usize) { + self.graph = self.graph.filter(|index| *index != graph).map(|index| if index > graph { index - 1 } else { index }); + self.channels.retain(|_, source| source.graph != graph); + for source in self.channels.values_mut() { + if source.graph > graph { + source.graph -= 1; + } + } + } +} + +impl Session { + /// Show a material graph on open, retaining the material while editing functions + pub(crate) fn open_material_preview(&mut self) { + if self.graph().is_ok_and(|graph| graph.function.is_none()) { + self.material_preview = MaterialPreview::for_graph(&self.pkg, self.graph); + } + } + + pub(crate) fn clear_preview_results(&mut self) { + self.cooked_graph = None; + self.material_cooked.clear(); + } + + pub fn material_image(&self, source: &MaterialSource) -> Option<&Image> { + let port = source.port_index(&self.pkg)?; + let cooked = self.preview_cooked(source.graph)?; + cooked.image(source.node, port) + } + + fn preview_cooked(&self, graph: usize) -> Option<&materialcraft_eval::Cooked> { + if self.cooked_graph == Some(graph) { Some(&self.cooked) } else { self.material_cooked.get(&graph) } + } + + /// Assigned image channels, including sources outside the open graph + pub fn material_maps(&self) -> Vec<(&'static str, &Image)> { + self.material_preview.sources(&self.pkg).into_iter().filter_map(|(channel, source)| Some((channel.id(), self.material_image(&source)?))).collect() + } + + /// Assignment and cooked content both invalidate the rendered preview + pub fn material_key(&self) -> u64 { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + for (channel, source) in self.material_preview.sources(&self.pkg) { + let result = self.preview_cooked(source.graph).and_then(|cooked| cooked.nodes.get(&source.node)); + let port = source.port_index(&self.pkg); + (channel, &source, port, result.map(|result| result.key)).hash(&mut hash); + } + hash.finish() + } +} diff --git a/crates/engine/src/material_preview_commands.rs b/crates/engine/src/material_preview_commands.rs new file mode 100644 index 00000000..bc6f5e88 --- /dev/null +++ b/crates/engine/src/material_preview_commands.rs @@ -0,0 +1,100 @@ +use materialcraft_core::{MaterialChannel, NodeId}; +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad, boolp, has_graph, u64p}; +use crate::{MaterialPreview, MaterialSource, Result, Session, cmd}; + +pub(crate) fn specs() -> Vec<CommandSpec> { + vec![ + cmd!( + "view.3d.outputs", + "View outputs in 3D view", + ["Tools"], + None, + "{graph?: index or name, reset?: bool} assigns image outputs by usage; reset clears other assignments without moving the camera", + has_graph, + outputs + ), + cmd!( + "view.3d.assign", + "View output in 3D view", + [], + None, + "{graph?: index or name, node?: selected node, port?: index or identifier, channel: baseColor|normal|roughness|metallic|height|ambientOcclusion|emissive|opacity, reset?: bool}", + has_graph, + assign + ), + cmd!("view.3d.clear", "Clear material assignments", [], None, "{} clears the material without resetting the scene or camera", always, |session, _| { + session.material_preview = MaterialPreview::default(); + session.dirty = true; + Ok(Value::Null) + }), + ] +} + +fn graph_index(session: &Session, parameters: &Value, command: &str) -> Result<usize> { + let graph = match parameters.get("graph") { + None => session.graph, + Some(Value::String(name)) => session.pkg.graph_by_name(name).map(|(index, _)| index).ok_or_else(|| bad(command, format!("no graph `{name}`")))?, + Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad(command, "graph must be an index or name"))?, + }; + if session.pkg.graph(graph)?.function.is_some() { + return Err(bad(command, "a Function Graph has no material image outputs")); + } + Ok(graph) +} + +fn outputs(session: &mut Session, parameters: &Value) -> Result<Value> { + let graph = graph_index(session, parameters, "view.3d.outputs")?; + let material = MaterialPreview::for_graph(&session.pkg, graph); + let sources = material.sources(&session.pkg); + if sources.is_empty() { + return Err(bad("view.3d.outputs", "no image outputs have supported material usages; assign an image to a channel with View in 3D view")); + } + if boolp(parameters, "reset") == Some(true) { + session.material_preview = material; + } else { + session.material_preview.channels.extend(sources); + } + session.dirty = true; + Ok(json!(session.material_preview)) +} + +fn assign(session: &mut Session, parameters: &Value) -> Result<Value> { + const COMMAND: &str = "view.3d.assign"; + let graph = graph_index(session, parameters, COMMAND)?; + let channel = parameters + .get("channel") + .and_then(Value::as_str) + .and_then(MaterialChannel::from_id) + .ok_or_else(|| bad(COMMAND, "choose a supported material channel"))?; + let node = match parameters.get("node") { + Some(_) => NodeId(u64p(parameters, "node").ok_or_else(|| bad(COMMAND, "node must be an ID"))?), + None if graph == session.graph => *session.selection.last().ok_or_else(|| bad(COMMAND, "select a node or supply its ID"))?, + None => return Err(bad(COMMAND, "node is required for another graph")), + }; + let source_graph = session.pkg.graph(graph)?; + let source_node = source_graph.node(node)?; + let ports = if source_node.def == "output" { + vec!["output".to_string()] + } else { + materialcraft_eval::ports(&session.pkg, source_graph, source_node).1.into_iter().map(|port| port.id).collect() + }; + let port = match parameters.get("port") { + None => ports.first(), + Some(Value::String(name)) => ports.iter().find(|port| *port == name), + Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).and_then(|index| ports.get(index)), + } + .cloned() + .ok_or_else(|| bad(COMMAND, "no such image output port"))?; + let source = MaterialSource { graph, node, port }; + if !source.is_image(&session.pkg) { + return Err(bad(COMMAND, "the 3D view needs an image, not a scalar, vector or unresolved output")); + } + if boolp(parameters, "reset") == Some(true) { + session.material_preview = MaterialPreview::default(); + } + session.material_preview.channels.insert(channel, source); + session.dirty = true; + Ok(json!(session.material_preview)) +} diff --git a/crates/engine/src/material_source.rs b/crates/engine/src/material_source.rs new file mode 100644 index 00000000..f6ac8be9 --- /dev/null +++ b/crates/engine/src/material_source.rs @@ -0,0 +1,62 @@ +use materialcraft_core::{NodeId, Package}; +use serde::{Deserialize, Serialize}; + +/// An image assigned to a material channel, independent of editor selection +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct MaterialSource { + pub graph: usize, + pub node: NodeId, + pub port: String, +} + +impl MaterialSource { + pub fn is_image(&self, package: &Package) -> bool { + let mut graph_index = self.graph; + let mut node_id = self.node; + let mut port = self.port.clone(); + let mut visited = std::collections::BTreeSet::new(); + loop { + if !visited.insert((graph_index, node_id, port.clone())) { + return false; + } + let Some(graph) = package.graphs.get(graph_index) else { return false }; + let Ok(node) = graph.node(node_id) else { return false }; + + match node.def.as_str() { + "output" | "dot" => { + let Some(connection) = graph.input_of(node_id, "input") else { return true }; + + node_id = connection.from; + port = connection.from_port.clone(); + } + "graph_instance" => { + let Some((index, graph)) = materialcraft_eval::instance_graph(package, node) else { return false }; + let Some(output) = graph.nodes.iter().find(|node| node.def == "output" && materialcraft_eval::identifier(node) == port) else { + return false; + }; + + graph_index = index; + node_id = output.id; + port = "output".into(); + } + _ => { + return materialcraft_eval::ports(package, graph, node) + .1 + .iter() + .any(|output| output.id == port && output.kind != materialcraft_nodes::PortKind::Value) + && materialcraft_nodes::output_value_type(graph, node_id).is_ok_and(|value| value.is_none()); + } + } + } + } + + pub fn port_index(&self, package: &Package) -> Option<usize> { + let graph = package.graphs.get(self.graph)?; + let node = graph.node(self.node).ok()?; + if node.def == "output" { + return (self.port == "output").then_some(0); + } + + materialcraft_eval::ports(package, graph, node).1.iter().position(|port| port.id == self.port) + } +} diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs index 7fa6b3ed..34efaa75 100644 --- a/crates/engine/src/node_cmds.rs +++ b/crates/engine/src/node_cmds.rs @@ -83,6 +83,7 @@ fn add(s: &mut Session, p: &J) -> Result<J> { pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.add", format!("`{k}` takes a {}", pd.default.type_name())))? }; + crate::graph_validation::value(&v).map_err(|error| bad("graph.node.add", error))?; params.push((k.clone(), v)); } } @@ -136,7 +137,7 @@ fn move_nodes(s: &mut Session, p: &J) -> Result<J> { if let Some(t) = to { n.pos = snap_position(t, snap); } else if let Some(d) = by { - n.pos = snap_position([n.pos[0] + d[0], n.pos[1] + d[1]], snap); + n.pos = crate::graph_grid::translate(n.pos, d, snap); } } Ok(J::Null) @@ -198,9 +199,7 @@ fn set_param(s: &mut Session, p: &J) -> Result<J> { v }; - if let Value::PatternGraph(graph) = &value { - graph.validate().map_err(|error| bad("graph.node.param", error))?; - } + crate::graph_validation::value(&value).map_err(|error| bad("graph.node.param", error))?; s.edit_merged(&format!("param:{}:{param}", id.0), "Set parameter", |s| { s.graph_mut()?.node_mut(id)?.params.insert(param.clone(), value); @@ -315,9 +314,7 @@ fn set_function(s: &mut Session, p: &J) -> Result<J> { }, }; - if f.nodes.len() > 4096 { - return Err(bad("graph.node.function", "the function is too large")); - } + crate::graph_validation::function(&f).map_err(|error| bad("graph.node.function", error))?; s.edit_merged(&format!("fn:{}:{param}", id.0), "Set parameter function", |s| { s.graph_mut()?.node_mut(id)?.functions.insert(param.clone(), f); Ok(J::Null) diff --git a/crates/engine/src/node_graph_commands.rs b/crates/engine/src/node_graph_commands.rs index 3686f75c..112d24a0 100644 --- a/crates/engine/src/node_graph_commands.rs +++ b/crates/engine/src/node_graph_commands.rs @@ -1,8 +1,7 @@ -use materialcraft_core::NodeId; use serde_json::{Value, json}; use crate::commands::{CommandSpec, bad}; -use crate::{Result, Session, cmd}; +use crate::{FunctionGraphTarget, Session, cmd}; pub(crate) fn specs() -> Vec<CommandSpec> { vec![cmd!( @@ -10,32 +9,29 @@ pub(crate) fn specs() -> Vec<CommandSpec> { "Edit node graph", ["Edit"], Some("Ctrl+E"), - "{} resolves the selected FX-Map graph to {node, parameter}; UI invocation opens its editor", - enabled, - edit + "{} resolves the selected FX-Map, processor or local graph instance to {kind, node, parameter?, graph?}; UI invocation opens it in the graph panel", + |session| resolve(session).map(|_| ()), + |session, _| resolve(session).map_err(|error| bad("graph.node.edit", error)) )] } -fn selected_node(session: &Session) -> std::result::Result<NodeId, String> { +fn resolve(session: &Session) -> std::result::Result<Value, String> { if session.annotation_selection.is_some() { - return Err("select an FX-Map node".into()); + return Err("select a node with an editable graph".into()); } - - let id = session.selection.last().copied().ok_or("select an FX-Map node")?; + let id = session.selection.last().copied().ok_or("select a node with an editable graph")?; let graph = session.graph().map_err(|error| error.to_string())?; let node = graph.node(id).map_err(|error| error.to_string())?; - if node.def != "fx_map" { - return Err("the selected node has no editable FX-Map graph".into()); + match node.def.as_str() { + "fx_map" => Ok(json!({"kind": "pattern", "node": id, "parameter": "pattern"})), + "pixel_processor" | "value_processor" => { + FunctionGraphTarget::Parameter { node: id, parameter: "function".into() }.current(session).map_err(|error| error.to_string())?; + Ok(json!({"kind": "function", "node": id, "parameter": "function"})) + } + "graph_instance" => { + let (index, _) = materialcraft_eval::instance_graph(&session.pkg, node).ok_or("the referenced graph is missing")?; + Ok(json!({"kind": "graph", "node": id, "graph": index})) + } + _ => Err("the selected node has no editable graph".into()), } - - Ok(id) -} - -fn enabled(session: &Session) -> std::result::Result<(), String> { - selected_node(session).map(|_| ()) -} - -fn edit(session: &mut Session, _: &Value) -> Result<Value> { - let node = selected_node(session).map_err(|error| bad("graph.node.edit", error))?; - Ok(json!({"node": node.0, "parameter": "pattern"})) } diff --git a/crates/engine/src/pattern_edit.rs b/crates/engine/src/pattern_edit.rs new file mode 100644 index 00000000..5a479369 --- /dev/null +++ b/crates/engine/src/pattern_edit.rs @@ -0,0 +1,114 @@ +use materialcraft_core::{PatternGraph, PatternNodeKind, Value}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value as Json, json}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "action", rename_all = "camelCase")] +pub enum PatternEdit { + Add { + kind: PatternNodeKind, + at: [f32; 2], + #[serde(default)] + snap: bool, + }, + Move { + ids: Vec<u32>, + by: [f32; 2], + #[serde(default)] + snap: bool, + }, + Connect { + parent: u32, + slot: usize, + child: u32, + }, + Disconnect { + node: u32, + slot: Option<usize>, + }, + Root { + id: u32, + }, + Value { + id: u32, + parameter: String, + value: Option<Value>, + }, +} + +impl PatternEdit { + pub(crate) fn apply(&self, graph: &mut PatternGraph) -> Result<Json, String> { + match self { + Self::Add { kind, at, snap } => { + let id = graph.add(*kind)?; + if let Some(node) = graph.nodes.last_mut() { + node.position = crate::graph_grid::snap_position(*at, *snap); + } + return Ok(json!({"id": id})); + } + Self::Move { ids, by, snap } => { + for id in ids { + if !graph.nodes.iter().any(|node| node.id == *id) { + return Err(format!("no FX-Map node {id}")); + } + } + for node in &mut graph.nodes { + if ids.contains(&node.id) { + node.position = crate::graph_grid::translate(node.position, *by, *snap); + } + } + } + Self::Connect { parent, slot, child } => { + if !graph.nodes.iter().any(|node| node.id == *child) { + return Err("missing child node".into()); + } + let destination = + graph.nodes.iter_mut().find(|node| node.id == *parent).and_then(|node| node.children.get_mut(*slot)).ok_or("invalid child slot")?; + *destination = Some(*child); + } + Self::Disconnect { node, slot } => { + if let Some(slot) = slot { + let destination = graph + .nodes + .iter_mut() + .find(|candidate| candidate.id == *node) + .and_then(|node| node.children.get_mut(*slot)) + .ok_or("invalid child slot")?; + *destination = None; + } else { + for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { + if *child == Some(*node) { + *child = None; + } + } + } + } + Self::Root { id } => { + if !graph.nodes.iter().any(|node| node.id == *id) { + return Err("missing root node".into()); + } + graph.root = Some(*id); + } + Self::Value { id, parameter, value } => { + let node = graph.nodes.iter_mut().find(|node| node.id == *id).ok_or("missing FX-Map node")?; + let definition = materialcraft_nodes::pattern::definition(node.kind).ok_or("unknown FX-Map node")?; + if !definition.params.iter().any(|candidate| candidate.id == parameter) { + return Err("unknown FX-Map parameter".into()); + } + if let Some(value) = value { + node.parameters.insert(parameter.clone(), value.clone()); + } else { + node.parameters.remove(parameter); + } + } + } + Ok(Json::Null) + } + + pub(crate) fn merge_key(&self) -> Option<String> { + match self { + Self::Value { id, parameter, .. } => Some(format!("value:{id}:{parameter}")), + _ => None, + } + } +} diff --git a/crates/engine/src/pattern_graph_commands.rs b/crates/engine/src/pattern_graph_commands.rs index 6e0118c7..95c38eb2 100644 --- a/crates/engine/src/pattern_graph_commands.rs +++ b/crates/engine/src/pattern_graph_commands.rs @@ -16,10 +16,7 @@ fn set(session: &mut Session, parameters: &Json) -> Result<Json> { let graph: PatternGraph = serde_json::from_value(parameters.get("pattern").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.set", error.to_string()))?; - graph.validate().map_err(|error| bad("graph.pattern.set", error))?; - if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) { - return Err(bad("graph.pattern.set", "node positions must be finite")); - } + crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.set", error))?; session.edit("Edit FX-Map graph", |session| { session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); diff --git a/crates/engine/src/preview_cook.rs b/crates/engine/src/preview_cook.rs new file mode 100644 index 00000000..1a225f29 --- /dev/null +++ b/crates/engine/src/preview_cook.rs @@ -0,0 +1,32 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; + +use materialcraft_core::Package; +use materialcraft_eval::{Cache, Cooked, Options}; + +/// One background result for the editor and the assigned material sources +#[derive(Default)] +pub struct PreviewCook { + pub graph: usize, + pub cooked: Cooked, + pub materials: BTreeMap<usize, Cooked>, +} + +impl PreviewCook { + pub fn run(package: &Package, graph: usize, materials: &BTreeSet<usize>, options: &Options<'_>, cache: &Arc<Mutex<Cache>>) -> Self { + let mut result = Self { graph, cooked: materialcraft_eval::cook(package, graph, options, cache), materials: BTreeMap::new() }; + for &index in materials { + if result.cancelled() { + break; + } + if index != graph && package.graphs.get(index).is_some() { + result.materials.insert(index, materialcraft_eval::cook(package, index, options, cache)); + } + } + result + } + + pub fn cancelled(&self) -> bool { + self.cooked.cancelled || self.materials.values().any(|cooked| cooked.cancelled) + } +} diff --git a/crates/engine/src/selection_commands.rs b/crates/engine/src/selection_commands.rs new file mode 100644 index 00000000..e49913f2 --- /dev/null +++ b/crates/engine/src/selection_commands.rs @@ -0,0 +1,191 @@ +//! Targeted selection and clipboard commands for standalone and embedded graphs + +use crate::{EmbeddedClipboard, Result, Session, commands::bad, graph_edit, selection_target::SelectionTarget}; +use materialcraft_core::{FunctionGraph, NodeId, PatternGraph, Value}; +use serde_json::{Value as Json, json}; + +pub fn supports(command: &str) -> bool { + matches!( + command, + "graph.select" + | "edit.selectAll" + | "edit.selectNone" + | "edit.copy" + | "edit.cut" + | "edit.paste" + | "edit.pasteWithoutLinks" + | "edit.delete" + | "edit.deleteRelink" + | "edit.duplicate" + | "edit.duplicateWithoutLinks" + | "graph.selectUpstream" + | "graph.selectDownstream" + ) +} + +fn selected(session: &Session, target: &SelectionTarget, parameters: &Json) -> Result<Vec<u32>> { + if let Some(ids) = parameters.get("ids") { + return serde_json::from_value(ids.clone()).map_err(|error| bad("graph selection", error.to_string())); + } + if target.standalone() { + return session.selection.iter().map(|id| u32::try_from(id.0).map_err(|_| bad("graph selection", "invalid function node id"))).collect(); + } + Ok(Vec::new()) +} + +pub fn enabled(session: &Session, command: &str, parameters: &Json) -> Option<bool> { + if !handles(session, command, parameters) { + return None; + } + let target = match SelectionTarget::resolve(session, parameters) { + Ok(Some(target)) => target, + Ok(None) => return None, + Err(_) => return Some(false), + }; + let selection = match selected(session, &target, parameters) { + Ok(selection) => selection, + Err(_) => return Some(false), + }; + enabled_for(session, &target, &selection, command) +} + +pub fn enabled_for(session: &Session, target: &SelectionTarget, selection: &[u32], command: &str) -> Option<bool> { + if !supports(command) { + return None; + } + match target { + SelectionTarget::Function(target) => { + if target.current(session).is_err() { + return Some(false); + } + let nodes = match &session.embedded_clipboard { + Some(EmbeddedClipboard::Function { nodes, .. }) => nodes.as_slice(), + _ => &[], + }; + graph_edit::enabled::<FunctionGraph>(selection, nodes, command) + } + SelectionTarget::Pattern(owner) => { + if SelectionTarget::pattern(session, *owner).is_err() { + return Some(false); + } + let nodes = match &session.embedded_clipboard { + Some(EmbeddedClipboard::Pattern { nodes, .. }) => nodes.as_slice(), + _ => &[], + }; + graph_edit::enabled::<PatternGraph>(selection, nodes, command) + } + } +} + +fn handles(session: &Session, command: &str, parameters: &Json) -> bool { + supports(command) + && !(parameters.get("function").is_none() + && parameters.get("pattern").is_none() + && session.annotation_selection.is_some() + && matches!(command, "edit.delete" | "edit.deleteRelink")) +} + +pub(crate) fn execute(session: &mut Session, command: &str, parameters: &Json) -> Option<Result<Json>> { + if !handles(session, command, parameters) { + return None; + } + match SelectionTarget::resolve(session, parameters) { + Ok(Some(target)) => Some(run(session, command, parameters, target)), + Ok(None) => None, + Err(error) => Some(Err(error)), + } +} + +fn run(session: &mut Session, command: &str, parameters: &Json, target: SelectionTarget) -> Result<Json> { + let source = target.source(session)?; + let mut selection = selected(session, &target, parameters)?; + if command == "graph.select" && target.standalone() && parameters.get("add").and_then(Json::as_bool) == Some(true) { + for id in session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()) { + if !selection.contains(&id) { + selection.push(id); + } + } + } + let copied_count = selection.len(); + let at = crate::commands::point(parameters, "at").unwrap_or([0.0; 2]); + let snap = parameters.get("snapToGrid").and_then(Json::as_bool).unwrap_or(false); + let supplied: Option<EmbeddedClipboard> = + parameters.get("clip").cloned().map(serde_json::from_value).transpose().map_err(|error| bad(command, error.to_string()))?; + let clipboard = supplied.as_ref().or(session.embedded_clipboard.as_ref()); + let copying = matches!(command, "edit.copy" | "edit.cut"); + let updated_clipboard = match &target { + SelectionTarget::Function(function) => { + let (nodes, origin) = match clipboard { + Some(EmbeddedClipboard::Function { nodes, source }) => (nodes.as_slice(), source.as_str()), + _ => (&[][..], ""), + }; + let (graph, copied) = apply(function.current(session)?, &mut selection, nodes, paste_command(command, origin == source), at, snap)?; + if let Some(graph) = graph { + crate::graph_validation::function(&graph).map_err(|error| bad(command, error))?; + session.edit("Edit Function Graph", |session| function.replace(session, graph))?; + } + copying.then_some(EmbeddedClipboard::Function { source, nodes: copied }) + } + SelectionTarget::Pattern(owner) => { + let (nodes, origin) = match clipboard { + Some(EmbeddedClipboard::Pattern { nodes, source }) => (nodes.as_slice(), source.as_str()), + _ => (&[][..], ""), + }; + let (graph, copied) = apply(SelectionTarget::pattern(session, *owner)?, &mut selection, nodes, paste_command(command, origin == source), at, snap)?; + if let Some(graph) = graph { + crate::graph_validation::pattern(&graph).map_err(|error| bad(command, error))?; + session.edit("Edit FX-Map graph", |session| { + session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(()) + })?; + } + copying.then_some(EmbeddedClipboard::Pattern { source, nodes: copied }) + } + }; + if target.standalone() { + session.selection = selection.iter().map(|id| NodeId(u64::from(*id))).collect(); + session.annotation_selection = None; + } + let mut result = json!({"ids": selection, "selected": selection.len()}); + if copying { + result["clip"] = json!(updated_clipboard); + result["copied"] = json!(copied_count); + } + if let Some(clipboard) = updated_clipboard { + session.embedded_clipboard = Some(clipboard); + } + Ok(result) +} + +fn paste_command(command: &str, same_source: bool) -> &str { + if command == "edit.paste" && !same_source { "edit.pasteWithoutLinks" } else { command } +} + +fn apply<G: graph_edit::EditableGraph + Clone>( + graph: &G, + selection: &mut Vec<u32>, + clipboard: &[G::Node], + command: &str, + at: [f32; 2], + snap: bool, +) -> Result<(Option<G>, Vec<G::Node>)> { + if !matches!(command, "edit.selectAll" | "edit.selectNone") { + let present: std::collections::BTreeSet<_> = graph.nodes().iter().map(G::id).collect(); + if selection.iter().any(|id| !present.contains(id)) { + return Err(bad(command, "selection contains a missing node")); + } + } + if graph_edit::enabled::<G>(selection, clipboard, command) != Some(true) { + return Err(bad(command, "the selection or clipboard does not support this action")); + } + let mut copied = Vec::new(); + if graph_edit::read(graph, selection, &mut copied, command) { + return Ok((None, copied)); + } + if command.starts_with("edit.paste") { + copied = clipboard.to_vec(); + } + let mut edited = graph.clone(); + let changed = graph_edit::run(&mut edited, selection, &mut copied, command, at, snap).map_err(|error| bad(command, error))?; + Ok((changed.then_some(edited), copied)) +} diff --git a/crates/engine/src/selection_target.rs b/crates/engine/src/selection_target.rs new file mode 100644 index 00000000..663ea203 --- /dev/null +++ b/crates/engine/src/selection_target.rs @@ -0,0 +1,51 @@ +use crate::{FunctionGraphTarget, Result, Session, commands::bad}; +use materialcraft_core::{NodeId, PatternGraph, Value}; +use serde_json::Value as Json; + +#[derive(Clone, Debug)] +pub enum SelectionTarget { + Function(FunctionGraphTarget), + Pattern(NodeId), +} + +impl SelectionTarget { + pub(crate) fn resolve(session: &Session, parameters: &Json) -> Result<Option<Self>> { + if parameters.get("function").is_some() && parameters.get("pattern").is_some() { + return Err(bad("graph selection", "specify function or pattern, not both")); + } + if let Some(graph) = parameters.get("graph") + && graph.as_u64() != Some(session.graph as u64) + { + return Err(bad("graph selection", "the owning graph is no longer active")); + } + if let Some(target) = parameters.get("function") { + let target = serde_json::from_value(target.clone()).map_err(|error| bad("graph selection", error.to_string()))?; + return Ok(Some(Self::Function(target))); + } + if let Some(owner) = parameters.get("pattern") { + let owner = owner.as_u64().ok_or_else(|| bad("graph selection", "pattern must be an owner node id"))?; + return Ok(Some(Self::Pattern(NodeId(owner)))); + } + Ok(session.graph()?.function.as_ref().map(|_| Self::Function(FunctionGraphTarget::Graph))) + } + + pub(crate) fn standalone(&self) -> bool { + matches!(self, Self::Function(FunctionGraphTarget::Graph)) + } + + pub(crate) fn source(&self, session: &Session) -> Result<String> { + Ok(format!("{}:{self:?}", session.graph()?.name)) + } + + pub(crate) fn pattern(session: &Session, owner: NodeId) -> Result<&PatternGraph> { + let node = session.graph()?.node(owner)?; + if node.def != "fx_map" { + return Err(bad("graph selection", "the node is not an FX-Map")); + } + let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| ¶meter.default)); + match value { + Some(Value::PatternGraph(graph)) => Ok(graph), + _ => Err(bad("graph selection", "missing FX-Map graph")), + } + } +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index ca5a9fe0..3e3d274d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -124,6 +124,9 @@ pub struct Session { pub annotation_selection: Option<AnnotationSelection>, pub view2d: View2d, pub view3d: View3d, + pub material_preview: crate::MaterialPreview, + pub(crate) cooked_graph: Option<usize>, + pub(crate) material_cooked: std::collections::BTreeMap<usize, Cooked>, /// Cap on node output size while editing (`None` = full size). pub preview_size: Option<u32>, /// 3D view camera preferences (set with [`Session::set_camera_prefs`]). @@ -133,6 +136,7 @@ pub struct Session { /// What the last opened SBS package held that MaterialCraft couldn't read; empty after a clean open. pub load_warnings: Vec<String>, pub clipboard: Option<Clip>, + pub embedded_clipboard: Option<crate::EmbeddedClipboard>, /// The last cook of the open graph. pub cooked: Cooked, /// Set when the graph changed and needs cooking. @@ -151,6 +155,9 @@ pub struct Session { impl Session { pub fn new(pkg: Package) -> Session { Session { + material_preview: crate::MaterialPreview::for_graph(&pkg, 0), + cooked_graph: None, + material_cooked: std::collections::BTreeMap::new(), pkg, path: None, graph: 0, @@ -164,6 +171,7 @@ impl Session { log: Vec::new(), load_warnings: Vec::new(), clipboard: None, + embedded_clipboard: None, cooked: Cooked::default(), dirty: true, cache: Arc::new(Mutex::new(Cache::default())), @@ -190,6 +198,7 @@ impl Session { graph: self.graph, selection: self.selection.clone(), annotation_selection: self.annotation_selection, + material_preview: self.material_preview.clone(), label: label.into(), } } @@ -217,6 +226,11 @@ impl Session { r } + /// End the current gesture without adding an undo step + pub fn finish_edit(&mut self) { + self.merge_key = None; + } + fn edit_inner<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> { let snap = self.snapshot(label); match f(self) { @@ -241,6 +255,8 @@ impl Session { self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1)); self.selection = s.selection; self.annotation_selection = s.annotation_selection; + self.material_preview = s.material_preview; + self.clear_preview_results(); } /// Mark the document modified and in need of a cook. @@ -319,11 +335,22 @@ impl Session { let dec = self.resource_decoder(); let mut opts = Options::new(&dec); opts.max_size = self.preview_size; - self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache); + let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache); + self.accept_preview(cooked); self.dirty = false; &self.cooked } + /// Publish a completed editor and material cook together + pub fn accept_preview(&mut self, result: crate::PreviewCook) { + if result.graph != self.graph || result.cancelled() { + return; + } + self.cooked_graph = Some(result.graph); + self.cooked = result.cooked; + self.material_cooked = result.materials; + } + /// Cook graph `gi` at full size, without touching the preview results. pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); @@ -358,12 +385,6 @@ impl Session { self.view3d.target = self.camera.clamp_target(self.view3d.target); } - /// The open graph's material channels for the 3D view: usage id → image. - pub fn material_maps(&self) -> Vec<(&'static str, &Image)> { - let Ok(g) = self.graph() else { return Vec::new() }; - materialcraft_eval::outputs(g, &self.cooked).into_iter().filter_map(|(_, usage, _, img)| Some((usage, img?))).collect() - } - /// Show a mesh file in the 3D view (OBJ, glTF, GLB). pub fn load_mesh_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<()> { let mesh = materialcraft_formats::mesh::load_mesh(name, bytes)?; diff --git a/crates/engine/src/snapshot.rs b/crates/engine/src/snapshot.rs index 110c7cab..b09078cf 100644 --- a/crates/engine/src/snapshot.rs +++ b/crates/engine/src/snapshot.rs @@ -7,5 +7,6 @@ pub(crate) struct Snapshot { pub(crate) graph: usize, pub(crate) selection: Vec<NodeId>, pub(crate) annotation_selection: Option<AnnotationSelection>, + pub(crate) material_preview: crate::MaterialPreview, pub(crate) label: String, } diff --git a/crates/engine/tests/atomics.rs b/crates/engine/tests/atomics.rs index 61001b98..8660a3be 100644 --- a/crates/engine/tests/atomics.rs +++ b/crates/engine/tests/atomics.rs @@ -171,17 +171,30 @@ fn levels_preserve_independent_rgba_parameters_in_sbs() { } #[test] -fn selected_pattern_graph_is_resolved_without_changing_the_document() { +fn selected_node_graph_is_resolved_without_changing_the_document() { let mut session = materialcraft_engine::new_session(); assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err()); - let node = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); - let original = session.pkg.clone(); - let history = session.history(); - - assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"node": node, "parameter": "pattern"})); - assert_eq!(session.pkg, original); - assert_eq!(session.history(), history); - + for (definition, kind, parameter) in + [("fx_map", "pattern", "pattern"), ("pixel_processor", "function", "function"), ("value_processor", "function", "function")] + { + let node = execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap(); + let original = session.pkg.clone(); + let history = session.history(); + assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"kind": kind, "node": node, "parameter": parameter})); + assert_eq!(session.pkg, original); + assert_eq!(session.history(), history); + } execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap(); assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err()); + + let node = session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]); + session.graph_mut().unwrap().node_mut(node).unwrap().params.insert("graph".into(), Value::Text("Child".into())); + session.selection = vec![node]; + assert!(execute(&mut session, "graph.node.edit", &json!({})).is_err()); + session.pkg.graphs.push(materialcraft_engine::core::Graph::new("Child")); + let original = session.pkg.clone(); + let history = session.history(); + assert_eq!(execute(&mut session, "graph.node.edit", &json!({})).unwrap(), json!({"kind": "graph", "node": node, "graph": 1})); + assert_eq!(session.pkg, original); + assert_eq!(session.history(), history); } diff --git a/crates/engine/tests/embedded_edit.rs b/crates/engine/tests/embedded_edit.rs new file mode 100644 index 00000000..c995c2e0 --- /dev/null +++ b/crates/engine/tests/embedded_edit.rs @@ -0,0 +1,319 @@ +use materialcraft_engine::{ + FunctionGraphTarget, Session, + core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value}, + execute, new_session, +}; +use serde_json::json; + +fn function_session(kind: &str) -> (Session, FunctionGraphTarget) { + let mut session = new_session(); + let target = match kind { + "graph" => { + execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + FunctionGraphTarget::Graph + } + "pattern" => { + let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let node = graph.nodes[0].id; + graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::default())); + execute(&mut session, "graph.pattern.set", &json!({"id": owner.0, "pattern": graph})).unwrap(); + FunctionGraphTarget::Pattern { owner, node, parameter: "patternrotation".into() } + } + _ => { + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + if kind == "dynamic" { + session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("test".into(), FunctionGraph::default()); + FunctionGraphTarget::Dynamic { node, parameter: "test".into() } + } else { + FunctionGraphTarget::Parameter { node, parameter: "function".into() } + } + } + }; + execute(&mut session, "graph.function.set", &json!({"target": target, "function": FunctionGraph::default()})).unwrap(); + session.reset_history(); + (session, target) +} + +#[test] +fn creation_and_connections_use_the_same_rules_for_every_function_target() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let mut ids = Vec::new(); + for operation in ["const_float1", "mul"] { + let result = execute( + &mut session, + "graph.function.edit", + &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [19, -19], "snap": true}}), + ) + .unwrap(); + ids.push(result["id"].as_u64().unwrap() as u32); + } + let graph = target.current(&session).unwrap(); + assert_eq!(graph.node(ids[1]).unwrap().inputs, vec![None, None]); + assert_eq!(graph.node(ids[1]).unwrap().pos, [32.0, -32.0]); + assert_eq!(graph.output, Some(ids[0])); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": ids[0], "to": ids[1], "input": 0}})) + .unwrap(); + assert_eq!(target.current(&session).unwrap().node(ids[1]).unwrap().inputs[0], Some(ids[0])); + let before = session.pkg.clone(); + for edit in [ + json!({"action": "connect", "from": ids[1], "to": ids[1], "input": 0}), + json!({"action": "connect", "from": ids[0], "to": ids[1], "input": 1000000}), + json!({"action": "add", "operation": "unknown", "at": [0, 0]}), + ] { + assert!(execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": edit})).is_err()); + assert_eq!(session.pkg, before); + } + } +} + +#[test] +fn value_gestures_merge_but_separate_edits_undo_independently() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let added = + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})) + .unwrap(); + let id = added["id"].as_u64().unwrap(); + let initial = target.current(&session).unwrap().node(id as u32).unwrap().value.clone(); + session.reset_history(); + for value in [1.0, 2.0, 3.0] { + execute( + &mut session, + "graph.function.edit", + &json!({"target": target, "merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}}), + ) + .unwrap(); + } + assert_eq!(session.history().len(), 1, "{kind}"); + execute(&mut session, "edit.finish", &json!({})).unwrap(); + for value in [4.0, 5.0] { + execute( + &mut session, + "graph.function.edit", + &json!({"target": target, "merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}}), + ) + .unwrap(); + } + assert_eq!(session.history().len(), 2, "{kind}"); + session.undo(); + assert_eq!(target.current(&session).unwrap().node(id as u32).unwrap().value, Some(Value::Float(3.0))); + session.undo(); + assert_eq!(target.current(&session).unwrap().node(id as u32).unwrap().value, initial); + for _ in 0..2 { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "mul", "at": [0, 0]}})).unwrap(); + } + session.undo(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 2); + } +} + +#[test] +fn pattern_value_gestures_and_invalid_connections_are_atomic() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let result = execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "add", "kind": "paramset", "at": [0, 0]}})).unwrap(); + let id = result["id"].as_u64().unwrap(); + session.reset_history(); + for value in [1.0, 2.0, 3.0] { + execute( + &mut session, + "graph.pattern.edit", + &json!({"id": owner, "merge": true, "edit": {"action": "value", "id": id, "parameter": "patternrotation", "value": Value::Float(value)}}), + ) + .unwrap(); + } + assert_eq!(session.history().len(), 1); + execute(&mut session, "edit.finish", &json!({})).unwrap(); + execute( + &mut session, + "graph.pattern.edit", + &json!({"id": owner, "merge": true, "edit": {"action": "value", "id": id, "parameter": "patternrotation", "value": Value::Float(4.0)}}), + ) + .unwrap(); + assert_eq!(session.history().len(), 2); + let before = session.pkg.clone(); + assert!(execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "connect", "parent": id, "slot": 0, "child": id}})).is_err()); + assert_eq!(session.pkg, before); + assert!(execute(&mut session, "graph.function.edit", &json!({"target": {"kind": "pattern", "owner": owner, "node": id, "parameter": "absent"}, "edit": {"action": "add", "operation": "mul", "at": [0, 0]}})).is_err()); + assert_eq!(session.pkg, before); +} + +#[test] +fn selection_commands_work_without_a_ui_for_every_function_target() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + for operation in ["const_float1", "passthrough"] { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [0, 0]}})).unwrap(); + } + let target_parameters = if kind == "graph" { json!({}) } else { json!({"function": target}) }; + let parent_selection = session.selection.clone(); + session.reset_history(); + let selected = execute(&mut session, "edit.selectAll", &target_parameters).unwrap(); + assert_eq!(selected["selected"], 2, "{kind}"); + let mut parameters = target_parameters.clone(); + parameters["ids"] = selected["ids"].clone(); + let copied = execute(&mut session, "edit.copy", ¶meters).unwrap(); + assert_eq!(copied["copied"], 2); + assert!(session.history().is_empty()); + let duplicated = execute(&mut session, "edit.duplicate", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 4); + parameters["ids"] = duplicated["ids"].clone(); + execute(&mut session, "edit.delete", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 2); + parameters["ids"] = json!([]); + parameters["clip"] = copied["clip"].clone(); + execute(&mut session, "edit.paste", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes.len(), 4); + if kind != "graph" { + assert_eq!(session.selection, parent_selection, "embedded commands changed the parent selection"); + } + } +} + +#[test] +fn rejected_function_duplicate_preserves_document_selection_clipboard_and_history() { + let (mut session, target) = function_session("graph"); + let mut graph = FunctionGraph::default(); + for _ in 0..2049 { + graph.add("passthrough", &[], None); + } + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + execute(&mut session, "edit.selectAll", &json!({})).unwrap(); + execute(&mut session, "edit.copy", &json!({})).unwrap(); + let before = session.pkg.clone(); + let selection = session.selection.clone(); + let clipboard = serde_json::to_value(&session.embedded_clipboard).unwrap(); + let history = session.history(); + assert!(execute(&mut session, "edit.duplicate", &json!({})).is_err()); + assert_eq!(session.pkg, before); + assert_eq!(session.selection, selection); + assert_eq!(serde_json::to_value(&session.embedded_clipboard).unwrap(), clipboard); + assert_eq!(session.history(), history); + assert_eq!(target.current(&session).unwrap().nodes.len(), 2049); +} + +#[test] +fn graph_validation_is_shared_by_creation_legacy_setters_and_targeted_edits() { + let mut cyclic = FunctionGraph::default(); + let id = cyclic.add("passthrough", &[], None); + cyclic.nodes[0].inputs = vec![Some(id)]; + cyclic.output = Some(id); + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap(); + let before = session.pkg.clone(); + for (command, parameters) in [ + ("graph.node.add", json!({"def": "pixel_processor", "params": {"function": Value::Function(Box::new(cyclic.clone()))}})), + ("graph.node.param", json!({"id": owner, "param": "function", "value": Value::Function(Box::new(cyclic.clone()))})), + ("graph.node.function", json!({"id": owner, "param": "color_mode", "function": cyclic})), + ("graph.function.set", json!({"target": {"kind": "parameter", "node": owner, "parameter": "function"}, "function": cyclic})), + ] { + let error = execute(&mut session, command, ¶meters).unwrap_err().to_string(); + assert!(error.contains("cycle"), "{command}: {error}"); + assert_eq!(session.pkg, before); + } + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::new(cyclic.clone()))); + let before = session.pkg.clone(); + for (command, parameters) in [ + ("graph.pattern.set", json!({"id": owner, "pattern": graph})), + ("graph.node.param", json!({"id": owner, "param": "pattern", "value": Value::PatternGraph(Box::new(graph))})), + ( + "graph.pattern.edit", + json!({"id": owner, "edit": {"action": "value", "id": 1, "parameter": "patternrotation", "value": Value::Function(Box::new(cyclic))}}), + ), + ] { + assert!(execute(&mut session, command, ¶meters).unwrap_err().to_string().contains("cycle"), "{command}"); + assert_eq!(session.pkg, before); + } +} + +#[test] +fn pattern_selection_commands_and_cross_graph_clipboards_keep_ownership() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let selected = execute(&mut session, "edit.selectAll", &json!({"pattern": owner})).unwrap(); + let parameters = json!({"pattern": owner, "ids": selected["ids"]}); + execute(&mut session, "edit.copy", ¶meters).unwrap(); + let before = session.pkg.clone(); + assert!(execute(&mut session, "edit.deleteRelink", ¶meters).is_err()); + assert!(execute(&mut session, "edit.delete", &json!({"pattern": owner, "ids": [1], "graph": 99})).is_err()); + assert_eq!(session.pkg, before); + execute(&mut session, "edit.duplicate", ¶meters).unwrap(); + assert_eq!(session.selection, vec![NodeId(owner)]); + + let (mut session, _) = function_session("graph"); + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(Value::Float(1.0)); + let child = graph.add("passthrough", &[source], None); + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + let copied = execute(&mut session, "edit.copy", &json!({"ids": [child]})).unwrap(); + execute(&mut session, "graph.duplicate", &json!({})).unwrap(); + let pasted = execute(&mut session, "edit.paste", &json!({"clip": copied["clip"]})).unwrap(); + let id = pasted["ids"][0].as_u64().unwrap() as u32; + assert_eq!(session.graph().unwrap().function.as_ref().unwrap().node(id).unwrap().inputs, vec![None]); +} + +#[test] +fn alignment_targets_embedded_functions_and_undo_restores_them() { + for kind in ["parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + for at in [[10, 30], [50, 90]] { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": at}})).unwrap(); + } + let before = session.pkg.clone(); + execute(&mut session, "graph.align", &json!({"function": target, "ids": [1, 2], "mode": "left"})).unwrap(); + let positions: Vec<_> = target.current(&session).unwrap().nodes.iter().map(|node| node.pos).collect(); + assert_eq!(positions, vec![[10.0, 30.0], [10.0, 90.0]]); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + } +} + +#[test] +fn replacing_a_package_discards_embedded_clipboard_provenance() { + let (mut session, _) = function_session("graph"); + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})).unwrap(); + execute(&mut session, "edit.selectAll", &json!({})).unwrap(); + execute(&mut session, "edit.copy", &json!({})).unwrap(); + assert!(session.embedded_clipboard.is_some()); + let package = session.pkg.clone(); + materialcraft_engine::file_cmds::replace_package(&mut session, package, None); + assert!(session.embedded_clipboard.is_none()); +} + +#[test] +fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs() { + for definition in ["pixel_processor", "value_processor"] { + let mut session = new_session(); + let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() }; + let operations: Vec<_> = target.available_operations(&session).map(|operation| operation.id).collect(); + let full_catalog = materialcraft_engine::nodes::function::FUNCTIONS; + let sampling = definition == "pixel_processor"; + assert_eq!(operations.len(), full_catalog.len() - if sampling { 0 } else { 2 }); + assert!(operations.contains(&"add")); + for sampler in ["samplelum", "samplecol"] { + assert_eq!(operations.contains(&sampler), sampling); + let original = session.pkg.clone(); + let history = session.history(); + let result = + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}})); + assert_eq!(result.is_ok(), sampling); + if !sampling { + assert_eq!(session.pkg, original); + assert_eq!(session.history(), history); + } + } + let mut existing = FunctionGraph::default(); + existing.add("samplelum", &[], Some(Value::Int2([0, 1]))); + execute(&mut session, "graph.function.set", &json!({"target": target, "function": existing})).unwrap(); + assert_eq!(target.current(&session).unwrap().nodes[0].op, "samplelum"); + } + for kind in ["graph", "pattern", "dynamic"] { + let (session, target) = function_session(kind); + assert_eq!(target.available_operations(&session).count(), materialcraft_engine::nodes::function::FUNCTIONS.len()); + } +} diff --git a/crates/engine/tests/graph_alignment.rs b/crates/engine/tests/graph_alignment.rs new file mode 100644 index 00000000..88be9f47 --- /dev/null +++ b/crates/engine/tests/graph_alignment.rs @@ -0,0 +1,93 @@ +use materialcraft_engine::{ + Session, + core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}, + execute, new_session, +}; +use serde_json::json; + +fn positions(session: &Session, kind: &str, owner: u64) -> Vec<[f32; 2]> { + let graph = session.graph().unwrap(); + match kind { + "function" => graph.function.as_ref().unwrap().nodes.iter().map(|node| node.pos).collect(), + "pattern" => { + let Value::PatternGraph(pattern) = &graph.node(materialcraft_engine::core::NodeId(owner)).unwrap().params["pattern"] else { + panic!("missing pattern") + }; + pattern.nodes.iter().map(|node| node.position).collect() + } + _ => graph.nodes.iter().map(|node| node.pos).collect(), + } +} + +#[test] +fn alignment_and_undo_target_only_the_active_graph_kind() { + for kind in ["material", "function", "pattern"] { + let mut session = new_session(); + let coordinates = [[0.0, 0.0], [32.0, 96.0], [256.0, 192.0]]; + let mut owner = 0; + let ids: Vec<u64> = match kind { + "function" => { + execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for position in coordinates { + graph.add_constant(Value::Float(1.0)); + graph.nodes.last_mut().unwrap().pos = position; + } + let ids = graph.nodes.iter().map(|node| u64::from(node.id)).collect(); + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + ids + } + "pattern" => { + owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map", "at": [700, 800]})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::default(); + for position in coordinates { + graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes.last_mut().unwrap().position = position; + } + let ids = graph.nodes.iter().map(|node| u64::from(node.id)).collect(); + execute(&mut session, "graph.pattern.set", &json!({"id": owner, "pattern": graph})).unwrap(); + ids + } + _ => coordinates + .into_iter() + .map(|position| execute(&mut session, "graph.node.add", &json!({"def": "uniform", "at": position})).unwrap()["id"].as_u64().unwrap()) + .collect(), + }; + let original = session.pkg.clone(); + for (mode, expected) in [("left", vec![[0.0, 0.0], [0.0, 96.0], [0.0, 192.0]]), ("hdistribute", vec![[0.0, 0.0], [128.0, 96.0], [256.0, 192.0]])] { + let mut parameters = json!({"ids": ids, "mode": mode}); + if kind == "pattern" { + parameters["pattern"] = json!(owner); + } + execute(&mut session, "graph.align", ¶meters).unwrap(); + assert_eq!(positions(&session, kind, owner), expected, "{kind}: {mode}"); + if kind == "pattern" { + assert_eq!(session.graph().unwrap().nodes[0].pos, [700.0, 800.0]); + assert_eq!(session.graph().unwrap().nodes.len(), 1); + } + session.undo().unwrap(); + assert_eq!(session.pkg, original); + parameters["ids"] = json!([u64::MAX]); + assert!(execute(&mut session, "graph.align", ¶meters).is_err()); + assert_eq!(session.pkg, original); + parameters["ids"] = json!(ids); + parameters["mode"] = json!("invalid"); + assert!(execute(&mut session, "graph.align", ¶meters).is_err()); + assert_eq!(session.pkg, original); + } + } +} + +#[test] +fn malformed_embedded_targets_never_fall_back_to_parent_selection() { + let mut session = new_session(); + for position in [[0, 0], [200, 100]] { + execute(&mut session, "graph.node.add", &json!({"def": "fx_map", "at": position})).unwrap(); + } + execute(&mut session, "edit.selectAll", &json!({})).unwrap(); + let original = session.pkg.clone(); + for parameters in [json!({"pattern": "invalid", "mode": "left"}), json!({"pattern": 1, "mode": "left"})] { + assert!(execute(&mut session, "graph.align", ¶meters).is_err()); + assert_eq!(session.pkg, original); + } +} diff --git a/crates/engine/tests/graph_edit.rs b/crates/engine/tests/graph_edit.rs new file mode 100644 index 00000000..a892a9a0 --- /dev/null +++ b/crates/engine/tests/graph_edit.rs @@ -0,0 +1,130 @@ +use materialcraft_engine::{ + core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}, + graph_edit::{self, EditableGraph}, +}; + +fn exercise_clipboard<G: EditableGraph>(mut graph: G, chain: [u32; 3]) { + let mut selection = vec![chain[1], chain[2]]; + let mut clipboard = Vec::new(); + let before = graph.nodes().len(); + graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.copy", [0.0; 2], true).unwrap(); + for command in ["edit.paste", "edit.pasteWithoutLinks"] { + graph_edit::run(&mut graph, &mut selection, &mut clipboard, command, [19.0, 19.0], true).unwrap(); + assert_eq!(selection.len(), 2); + let first = graph.nodes().iter().find(|node| G::id(node) == selection[0]).unwrap(); + let second = graph.nodes().iter().find(|node| G::id(node) == selection[1]).unwrap(); + assert_eq!(G::links(second)[0], Some(selection[0])); + assert_eq!(G::links(first)[0], if command == "edit.paste" { Some(chain[0]) } else { None }); + assert!(graph_edit::remove(&mut graph, &mut selection, false)); + assert_eq!(graph.nodes().len(), before); + } + + for command in ["graph.selectUpstream", "graph.selectDownstream"] { + selection = vec![chain[1]]; + graph_edit::run(&mut graph, &mut selection, &mut clipboard, command, [0.0; 2], false).unwrap(); + let follow_links = (command == "graph.selectUpstream") == G::LINKS_ARE_INPUTS; + let mut expected = if follow_links { vec![chain[0], chain[1]] } else { vec![chain[1], chain[2]] }; + expected.sort(); + assert_eq!(selection, expected); + } +} + +#[test] +fn function_and_pattern_clipboards_keep_internal_links_and_respect_direction() { + let mut function = FunctionGraph::default(); + let a = function.add_constant(Value::Float(1.0)); + let b = function.add("passthrough", &[a], None); + let c = function.add("passthrough", &[b], None); + exercise_clipboard(function, [a, b, c]); + + let mut pattern = PatternGraph::default(); + let a = pattern.add(PatternNodeKind::Dot).unwrap(); + let b = pattern.add(PatternNodeKind::Dot).unwrap(); + let c = pattern.add(PatternNodeKind::Dot).unwrap(); + pattern.nodes[1].children[0] = Some(a); + pattern.nodes[2].children[0] = Some(b); + exercise_clipboard(pattern, [a, b, c]); +} + +#[test] +fn pattern_paste_capacity_failure_is_atomic_and_root_is_preserved() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Dot); + let node = graph.nodes[0].clone(); + graph.nodes = (1..4096).map(|id| materialcraft_engine::core::PatternNode { id, ..node.clone() }).collect(); + let before = graph.clone(); + let mut clipboard = vec![node.clone(), node]; + let mut selection = vec![1]; + assert!(graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.paste", [0.0; 2], true).is_err()); + assert_eq!(graph, before); + assert_eq!(selection, vec![1]); +} + +#[test] +fn function_delete_relinks_chains_and_clears_a_deleted_output() { + let mut graph = FunctionGraph::default(); + let a = graph.add_constant(Value::Float(1.0)); + let b = graph.add("passthrough", &[a], None); + let c = graph.add("passthrough", &[b], None); + let d = graph.add("passthrough", &[c], None); + graph.output = Some(d); + assert!(graph_edit::remove(&mut graph, &mut vec![b, c], true)); + assert_eq!(graph.node(d).unwrap().inputs, vec![Some(a)]); + assert_eq!(graph.output, Some(d)); + assert!(graph_edit::remove(&mut graph, &mut vec![d], false)); + assert_eq!(graph.output, None); +} + +#[test] +fn pattern_clipboard_preserves_selection_order_when_ids_have_holes() { + let mut graph = PatternGraph::default(); + for _ in 0..3 { + graph.add(PatternNodeKind::Quadrant).unwrap(); + } + graph.nodes.remove(1); + let id = graph.add(PatternNodeKind::Quadrant).unwrap(); + assert_eq!(id, 2); + let mut selection = vec![2, 3]; + let mut clipboard = Vec::new(); + graph_edit::run(&mut graph, &mut selection, &mut clipboard, "edit.duplicate", [0.0; 2], false).unwrap(); + assert_eq!(selection, vec![5, 4]); +} + +#[test] +#[ignore = "release timing probe; run explicitly with --ignored --nocapture"] +fn connected_selection_performance() { + use std::{collections::BTreeSet, time::Instant}; + + let mut graph = FunctionGraph::default(); + for id in 1..=4096 { + graph.nodes.push(materialcraft_engine::core::FunctionNode { + id, + op: "passthrough".into(), + type_code: 0, + inputs: if id == 1 { vec![] } else { vec![Some(id - 1)] }, + value: None, + pos: [0.0; 2], + }); + } + let mut before = Vec::new(); + let mut after = Vec::new(); + for _ in 0..3 { + let start = Instant::now(); + let mut visited = BTreeSet::new(); + let mut pending = vec![1]; + while let Some(id) = pending.pop() { + if visited.insert(id) { + pending.extend(graph.nodes.iter().filter(|node| node.inputs.contains(&Some(id))).map(|node| node.id)); + } + } + let expected: Vec<_> = visited.into_iter().collect(); + before.push(start.elapsed().as_secs_f64() * 1000.0); + let mut selection = vec![1]; + let start = Instant::now(); + graph_edit::run(std::hint::black_box(&mut graph), &mut selection, &mut Vec::new(), "graph.selectDownstream", [0.0; 2], false).unwrap(); + after.push(start.elapsed().as_secs_f64() * 1000.0); + assert_eq!(selection, expected); + } + before.sort_by(f64::total_cmp); + after.sort_by(f64::total_cmp); + println!("4096-node downstream selection, median of three: scan {:.3} ms; shared index {:.3} ms", before[1], after[1]); +} diff --git a/crates/engine/tests/material_preview.rs b/crates/engine/tests/material_preview.rs new file mode 100644 index 00000000..054af706 --- /dev/null +++ b/crates/engine/tests/material_preview.rs @@ -0,0 +1,263 @@ +use materialcraft_engine::{ + MaterialPreview, MaterialSource, Session, + core::{Graph, MaterialChannel, NodeId, Package, Value}, + execute, new_session, +}; +use serde_json::json; + +fn add(session: &mut Session, definition: &str, params: serde_json::Value) -> NodeId { + NodeId(execute(session, "graph.node.add", &json!({"def": definition, "params": params})).unwrap()["id"].as_u64().unwrap()) +} + +fn source(session: &mut Session, color: [f32; 4]) -> NodeId { + add(session, "uniform", json!({"color_mode": true, "color": color})) +} + +fn output(session: &mut Session, source: NodeId, usage: u32) -> NodeId { + let output = add(session, "output", json!({"usage": usage})); + execute(session, "graph.connect", &json!({"from": source, "to": output})).unwrap(); + output +} + +fn instance(session: &mut Session, graph: &str) -> NodeId { + let node = session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]); + session.graph_mut().unwrap().node_mut(node).unwrap().params.insert("graph".into(), Value::Text(graph.into())); + node +} + +fn color(session: &mut Session, channel: &str) -> [f32; 4] { + session.cook(); + session.material_maps().into_iter().find(|(usage, _)| *usage == channel).unwrap().1.get(0, 0, false) +} + +#[test] +fn explicit_assignment_shows_unclassified_output_and_tracks_edits() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + let output = output(&mut session, red, 9); + session.cook(); + assert!(session.material_maps().is_empty()); + let history = session.history(); + let package = session.pkg.clone(); + execute(&mut session, "view.3d.assign", &json!({"node": output, "channel": "baseColor"})).unwrap(); + assert_eq!(session.history(), history); + assert_eq!(session.pkg, package); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + let key = session.material_key(); + execute(&mut session, "graph.node.param", &json!({"id": red, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.1, 0.8, 0.2, 1.0]); + assert_ne!(session.material_key(), key); + let inspection = execute(&mut session, "session.inspect", &json!({})).unwrap(); + assert_eq!(inspection["material3d"]["channels"][0]["size"], json!([16, 16])); +} + +#[test] +fn automatic_outputs_follow_usage_and_do_not_follow_selection() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + let output = output(&mut session, red, 0); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.select", &json!({"ids": [blue]})).unwrap(); + execute(&mut session, "view.2d", &json!({"node": blue})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.node.param", &json!({"id": output, "param": "usage", "value": 4})).unwrap(); + assert_eq!(color(&mut session, "height"), [0.8, 0.1, 0.1, 1.0]); + assert!(session.material_maps().iter().all(|(channel, _)| *channel != "baseColor")); +} + +#[test] +fn graph_application_and_material_reset_preserve_camera_and_scene() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + output(&mut session, red, 0); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": blue, "channel": "baseColor"})).unwrap(); + execute(&mut session, "view.3d.assign", &json!({"node": blue, "channel": "roughness"})).unwrap(); + execute(&mut session, "view.3d", &json!({"scene": "sphere", "yaw": 70, "distance": 4, "environment": "sunset"})).unwrap(); + let view = session.view3d.clone(); + execute(&mut session, "view.3d.outputs", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + assert!(session.material_maps().iter().any(|(channel, _)| *channel == "roughness")); + execute(&mut session, "view.3d.outputs", &json!({"reset": true})).unwrap(); + session.cook(); + assert_eq!(session.material_maps().len(), 1); + assert_eq!(session.view3d, view); + execute(&mut session, "view.3d.clear", &json!({})).unwrap(); + assert!(session.material_maps().is_empty()); + assert_eq!(session.view3d, view); +} + +#[test] +fn assignments_survive_function_editing_and_undo_without_retargeting_node_ids() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": red, "channel": "baseColor"})).unwrap(); + session.cook(); + execute(&mut session, "file.new", &json!({"kind": "function", "name": "Function"})).unwrap(); + assert_eq!(session.material_maps()[0].1.get(0, 0, false), [0.8, 0.1, 0.1, 1.0], "keep the previous material while the worker cooks"); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "file.new", &json!({"template": "empty", "name": "Blue"})).unwrap(); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + assert_eq!(red, blue); + execute(&mut session, "view.3d.assign", &json!({"graph": 0, "node": red, "channel": "baseColor"})).unwrap(); + execute(&mut session, "graph.node.param", &json!({"id": blue, "param": "color", "value": [0.2, 0.2, 0.9, 1.0]})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.rename", &json!({"graph": 0, "name": "Renamed"})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "graph.delete", &json!({"graph": 0})).unwrap(); + session.cook(); + assert!(session.material_maps().is_empty()); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "file.newPackage", &json!({})).unwrap(); + assert!(session.material_preview.channels.is_empty()); +} + +#[test] +fn opening_material_graph_automatically_applies_its_outputs() { + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + output(&mut session, red, 0); + execute(&mut session, "file.new", &json!({"template": "empty", "name": "Blue"})).unwrap(); + let blue = source(&mut session, [0.1, 0.1, 0.8, 1.0]); + output(&mut session, blue, 0); + assert_eq!(color(&mut session, "baseColor"), [0.1, 0.1, 0.8, 1.0]); + execute(&mut session, "graph.open", &json!({"graph": 0})).unwrap(); + assert!(session.material_maps().is_empty(), "stale results must not cross graph IDs"); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); +} + +#[test] +fn invalid_assignments_are_atomic_including_scalar_instance_outputs() { + let mut session = new_session(); + session.preview_size = Some(16); + let image = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": image, "channel": "baseColor"})).unwrap(); + let value = add(&mut session, "input_value", json!({})); + let value_output = output(&mut session, value, 0); + let mut graph = Graph::new("Values"); + let input = graph.add_node("input_value", [0.0; 2]); + let out = graph.add_node("output", [100.0, 0.0]); + graph.node_mut(out).unwrap().params.insert("identifier".into(), Value::Text("value".into())); + graph.connect(input, "output", out, "input").unwrap(); + session.pkg.graphs.push(graph); + let instance = instance(&mut session, "Values"); + let before = session.material_preview.clone(); + let history = session.history(); + let package = session.pkg.clone(); + for parameters in [ + json!({"node": image, "channel": "unknown", "reset": true}), + json!({"node": image, "channel": "baseColor", "port": 999, "reset": true}), + json!({"node": image, "channel": "baseColor", "graph": 999, "reset": true}), + json!({"node": value, "channel": "baseColor", "reset": true}), + json!({"node": value_output, "channel": "baseColor", "reset": true}), + json!({"node": instance, "port": "value", "channel": "baseColor", "reset": true}), + ] { + assert!(execute(&mut session, "view.3d.assign", ¶meters).is_err(), "{parameters}"); + assert_eq!(session.material_preview, before); + assert_eq!(session.history(), history); + assert_eq!(session.pkg, package); + } + assert!(execute(&mut session, "view.3d.outputs", &json!({"graph": "Values", "reset": true})).is_err()); + assert_eq!(session.material_preview, before); +} + +#[test] +fn multiple_graph_channels_and_multi_output_instances_use_the_correct_ports() { + let mut package = Package::new("Test"); + let mut graph = Graph::new("Colors"); + graph.size = [4, 4]; + for (name, color) in [("red", [0.8, 0.1, 0.1, 1.0]), ("blue", [0.1, 0.1, 0.8, 1.0])] { + let image = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(image).unwrap().params.insert("color".into(), Value::Color(color)); + let output = graph.add_node("output", [100.0, 0.0]); + graph.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into())); + graph.connect(image, "output", output, "input").unwrap(); + } + package.graphs.push(graph); + package.graphs.push(Graph::new("Instances")); + let mut session = Session::new(package); + execute(&mut session, "graph.open", &json!({"graph": 1})).unwrap(); + let instance = instance(&mut session, "Colors"); + execute(&mut session, "view.3d.assign", &json!({"node": instance, "port": "blue", "channel": "baseColor"})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.1, 0.1, 0.8, 1.0]); + let key = session.material_key(); + execute(&mut session, "view.3d.assign", &json!({"node": instance, "port": 0, "channel": "baseColor"})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + assert_ne!(session.material_key(), key); + execute(&mut session, "view.3d.assign", &json!({"graph": "Colors", "node": 1, "channel": "emissive"})).unwrap(); + assert_eq!(color(&mut session, "emissive"), [0.8, 0.1, 0.1, 1.0]); + assert_eq!(session.graph, 1); +} + +#[test] +fn removing_an_earlier_graph_adjusts_sources_and_undo_restores_them() { + let mut session = new_session(); + execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap(); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "view.3d.assign", &json!({"node": red, "channel": "baseColor"})).unwrap(); + execute(&mut session, "graph.delete", &json!({"graph": 0})).unwrap(); + assert_eq!(session.material_preview.channels[&MaterialChannel::BaseColor].graph, 0); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.material_preview.channels[&MaterialChannel::BaseColor].graph, 1); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + let before = session.material_key(); + execute(&mut session, "graph.select", &json!({"ids": [red]})).unwrap(); + execute(&mut session, "edit.delete", &json!({})).unwrap(); + session.cook(); + assert!(session.material_maps().is_empty()); + assert_ne!(session.material_key(), before); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); +} + +#[test] +fn source_cycles_are_rejected_without_recursion() { + let mut package = Package::new("Cycle"); + let mut graph = Graph::new("Cycle"); + let instance = graph.add_node("graph_instance", [0.0; 2]); + graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text("Cycle".into())); + let output = graph.add_node("output", [100.0, 0.0]); + graph.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text("loop".into())); + graph.connect(instance, "loop", output, "input").unwrap(); + package.graphs.push(graph); + let source = MaterialSource { graph: 0, node: instance, port: "loop".into() }; + assert!(!source.is_image(&package)); + assert!(MaterialPreview::for_graph(&package, 0).sources(&package).is_empty()); +} + +#[test] +fn diffuse_usage_previews_as_base_color_and_unknown_usages_stay_unassigned() { + use materialcraft_engine::core::ComponentUsage; + + let mut session = new_session(); + session.preview_size = Some(16); + let red = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + let output = output(&mut session, red, ComponentUsage::index("diffuse")); + assert_eq!(color(&mut session, "baseColor"), [0.8, 0.1, 0.1, 1.0]); + for usage in [ComponentUsage::ANY_INDEX, u32::MAX, ComponentUsage::index("coatRoughness")] { + session.graph_mut().unwrap().node_mut(output).unwrap().params.insert("usage".into(), Value::Enum(usage)); + assert!(session.material_maps().is_empty(), "usage {usage} must not become a different channel"); + } +} + +#[test] +fn extracted_graph_outputs_remain_unclassified() { + let mut session = new_session(); + let uniform = source(&mut session, [0.8, 0.1, 0.1, 1.0]); + output(&mut session, uniform, 0); + execute(&mut session, "graph.select", &json!({"ids": [uniform]})).unwrap(); + execute(&mut session, "graph.createFromSelection", &json!({"name": "Extracted"})).unwrap(); + let (_, graph) = session.pkg.graph_by_name("Extracted").unwrap(); + let output = graph.nodes.iter().find(|node| node.def == "output").unwrap(); + assert_eq!(materialcraft_engine::eval::output_usage(output), "any"); +} diff --git a/crates/engine/tests/optimization_perf.rs b/crates/engine/tests/optimization_perf.rs new file mode 100644 index 00000000..2ebcf7e4 --- /dev/null +++ b/crates/engine/tests/optimization_perf.rs @@ -0,0 +1,84 @@ +//! Focused optimization benchmarks: release, ignored, serial, with --nocapture +use std::{collections::BTreeMap, hint::black_box, sync::Mutex, time::Instant}; + +use materialcraft_core::{Connection, FunctionGraph, Graph, Package, PatternGraph, PatternNodeKind, Value}; +use materialcraft_eval::{Cache, Options, cook}; +use materialcraft_nodes::{CookContext, find, resolve_params}; + +fn median_ms(mut run: impl FnMut()) -> f64 { + let mut samples = [0.0; 3]; + for sample in &mut samples { + let start = Instant::now(); + run(); + *sample = start.elapsed().as_secs_f64() * 1000.0; + } + samples.sort_by(f64::total_cmp); + samples[1] +} + +#[test] +#[ignore = "optimization benchmark"] +fn optimization_baseline() { + for count in [128, 1024, 4096] { + let ms = median_ms(|| { + let mut graph = PatternGraph::default(); + for _ in 0..count { + graph.add(PatternNodeKind::Quadrant).unwrap(); + } + black_box(graph); + }); + println!("pattern_add,{count},{ms:.3}"); + } + + let mut function = FunctionGraph::default(); + let position = function.add("get_float2", &[], Some(Value::Text("$pos".into()))); + let horizontal = function.add("swizzle1", &[position], Some(Value::Int(0))); + let factor = function.add_constant(Value::Float(0.5)); + function.output = Some(function.add("mul", &[horizontal, factor], None)); + let definition = find("pixel_processor").unwrap(); + let mut parameters = resolve_params(definition, &BTreeMap::new()); + parameters.insert("function".into(), Value::Function(Box::new(function))); + parameters.insert("color_mode".into(), Value::Bool(false)); + for size in [512, 2048] { + for count in [0, 16] { + let variables = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect(); + let context = CookContext { w: size, h: size, seed: 7, tile: true, inputs: &[], params: ¶meters, resource: &|_| None, vars: &variables }; + let ms = median_ms(|| { + black_box((definition.cook)(&context).unwrap()); + }); + println!("pixel_processor,{size},{count},{ms:.3}"); + } + } + + for count in [128, 1024, 4096] { + for branching in [false, true] { + let mut graph = Graph::new("Benchmark"); + graph.size = [4, 4]; + let source = graph.add_node("uniform", [0.0; 2]); + let mut previous = source; + for _ in 1..count { + let node = graph.add_node("dot", [0.0; 2]); + graph.connections.push(Connection { + from: if branching { source } else { previous }, + from_port: "output".into(), + to: node, + to_port: "input".into(), + }); + previous = node; + } + let mut package = Package::new("Benchmark"); + package.graphs.push(graph); + let options = Options::new(&|_| None); + let cache = Mutex::new(Cache::default()); + let initial = cook(&package, 0, &options, &cache); + assert_eq!(initial.nodes.len(), count); + assert!(initial.nodes.values().all(|result| result.error.is_none())); + let ms = median_ms(|| { + let cooked = cook(&package, 0, &options, &cache); + assert!(cooked.nodes.values().all(|result| result.cached)); + black_box(cooked); + }); + println!("warm_cook,{count},{branching},{ms:.3}"); + } + } +} diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index 0929b05a..0f522279 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -1,4 +1,7 @@ +use crate::{identifier, instance_graph}; +use materialcraft_core::{Node, Package, Value}; use materialcraft_image::Image; +use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; pub(crate) fn image_key(i: &Image) -> u64 { @@ -11,3 +14,63 @@ pub(crate) fn hash_of(v: &impl Hash) -> u64 { v.hash(&mut h); h.finish() } + +pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { + let mut h = DefaultHasher::new(); + let mut pending = vec![gi]; + let mut seen = HashSet::new(); + while let Some(index) = pending.pop() { + if !seen.insert(index) { + continue; + } + let Some(graph) = pkg.graphs.get(index) else { continue }; + + index.hash(&mut h); + serde_json::to_string(graph).unwrap_or_default().hash(&mut h); + for n in &graph.nodes { + if let Some(Value::Text(name)) = n.params.get("resource") { + pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); + } + if n.def == "graph_instance" + && let Some((si, _)) = instance_graph(pkg, n) + { + pending.push(si); + } + } + } + h.finish() +} + +pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, variables: &BTreeMap<String, Value>) -> u64 { + let mut names = std::collections::BTreeSet::new(); + let mut pending: Vec<&Value> = parameters.values().collect(); + while let Some(value) = pending.pop() { + match value { + Value::Function(graph) => { + for function in &graph.nodes { + if (function.op.starts_with("get_") || function.op == "isdefined") + && let Some(Value::Text(name)) = &function.value + { + names.insert(name.as_str()); + } + } + } + Value::PatternGraph(graph) => { + pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values())); + } + _ => {} + } + } + + let input_identifier = identifier(node); + if node.def == "input_value" { + names.insert(&input_identifier); + } + + let mut hasher = DefaultHasher::new(); + for name in names { + name.hash(&mut hasher); + variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher); + } + hasher.finish() +} diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index c33c3f2c..64eac009 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -1,400 +1,47 @@ -use std::collections::{BTreeMap, HashSet}; -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Mutex}; +use crate::{Cache, Cooked, Options, now_ms}; +use crate::{node_execution::cook_node, prepared_graph::PreparedGraph}; +use materialcraft_core::{Package, Value}; +use materialcraft_image::Image; +use std::{ + collections::BTreeMap, + sync::{Mutex, atomic::Ordering}, +}; -use materialcraft_core::{Graph, Node, NodeId, Package, Value}; -use materialcraft_image::{Image, Kind}; -use materialcraft_nodes::{CookContext, clamp_params, find, resolve_params}; +pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mutex<Cache>) -> Cooked { + let started_ms = now_ms(); + let mut cooked = Cooked::default(); + let Some(graph) = package.graphs.get(graph_index) else { return cooked }; -use crate::cache_key::{hash_of, image_key}; -use crate::{Cache, Cooked, MAX_DEPTH, NodeOutput, NodeResult, Options, Port, identifier, instance_graph, node_size, ports}; - -/// The magenta image a failed node shows -pub fn error_image(w: u32, h: u32) -> Image { - Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0]) -} - -/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written) -fn lock(cache: &Mutex<Cache>) -> std::sync::MutexGuard<'_, Cache> { - cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner) -} - -pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex<Cache>) -> Cooked { - let t0 = now_ms(); - let mut out = Cooked::default(); - let Some(graph) = pkg.graphs.get(gi) else { return out }; // The top-level graph's input nodes show their preview images; the caller's images win let bound; - let opts = if opts.depth == 0 && !graph.input_images.is_empty() { - let mut inputs: BTreeMap<String, Image> = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect(); - inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone()))); - bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), graph_stack: opts.graph_stack.clone(), ..*opts }; + let options = if options.depth == 0 && !graph.input_images.is_empty() { + let mut inputs: BTreeMap<String, Image> = + graph.input_images.iter().filter_map(|(id, resource)| Some((id.clone(), (options.resource)(resource)?))).collect(); + inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone()))); + bound = Options { only: options.only.clone(), inputs, overrides: options.overrides.clone(), graph_stack: options.graph_stack.clone(), ..*options }; &bound } else { - opts + options }; - let order = graph.topo_order(); - let needed: Option<std::collections::BTreeSet<NodeId>> = opts.only.as_ref().map(|ids| { - let mut s: std::collections::BTreeSet<NodeId> = ids.iter().copied().collect(); - for id in ids { - s.extend(graph.upstream(*id)); - } - s - }); + let prepared = PreparedGraph::new(package, graph, options.only.as_deref()); + // Exposed parameter values: the graph's own, then the caller's overrides - let mut vars: BTreeMap<String, Value> = graph.exposed.iter().filter_map(|e| graph.input_value(&e.id).map(|v| (e.id.clone(), v.clone()))).collect(); - for (k, v) in &opts.overrides { - vars.insert(k.clone(), v.clone()); + let mut variables: BTreeMap<String, Value> = + graph.exposed.iter().filter_map(|exposed| graph.input_value(&exposed.id).map(|value| (exposed.id.clone(), value.clone()))).collect(); + for (name, value) in &options.overrides { + variables.insert(name.clone(), value.clone()); } - for id in order { - if needed.as_ref().is_some_and(|s| !s.contains(&id)) { - continue; - } - if opts.cancel.is_some_and(|c| c.load(Ordering::Relaxed)) { - out.cancelled = true; + for &id in &prepared.order { + if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) { + cooked.cancelled = true; break; } - let Ok(node) = graph.node(id) else { continue }; - let r = cook_node(pkg, gi, graph, node, &out, &vars, opts, cache); - out.nodes.insert(id, r); + let Some(node) = prepared.index.node(id) else { continue }; + + let result = cook_node(package, graph_index, graph, &prepared, node, &cooked, &variables, options, cache); + cooked.nodes.insert(id, result); } - out.ms = (now_ms() - t0) as f32; - out -} - -pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { - let mut h = DefaultHasher::new(); - let mut pending = vec![gi]; - let mut seen = HashSet::new(); - while let Some(index) = pending.pop() { - if !seen.insert(index) { - continue; - } - let Some(graph) = pkg.graphs.get(index) else { continue }; - index.hash(&mut h); - serde_json::to_string(graph).unwrap_or_default().hash(&mut h); - for n in &graph.nodes { - if let Some(Value::Text(name)) = n.params.get("resource") { - pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); - } - if n.def == "graph_instance" - && let Some((si, _)) = instance_graph(pkg, n) - { - pending.push(si); - } - } - } - h.finish() -} - -fn cook_node( - pkg: &Package, - gi: usize, - graph: &Graph, - node: &Node, - done: &Cooked, - vars: &BTreeMap<String, Value>, - opts: &Options, - cache: &Mutex<Cache>, -) -> NodeResult { - let (in_ports, out_ports) = ports(pkg, graph, node); - let def = find(&node.def); - // Gather inputs by port order, with their keys - let mut inputs = Vec::new(); - let mut incoming = Vec::new(); - let mut input_keys = Vec::new(); - let mut variables = vars.clone(); - let mut input_error = None; - for port in &in_ports { - let source = graph.input_of(node.id, &port.id).and_then(|connection| { - let result = done.nodes.get(&connection.from)?; - let source_node = graph.node(connection.from).ok()?; - let index = ports(pkg, graph, source_node).1.iter().position(|output| output.id == connection.from_port)?; - Some((result.outputs.get(index)?.clone(), result.key ^ hash_of(&index))) - }); - input_keys.push(source.as_ref().map_or(0, |source| source.1)); - let output = source.map(|source| source.0); - - if let Some(expected) = node.input_values.get(&port.id) { - let value = match output.as_ref() { - Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(*expected) => value.clone(), - Some(_) => { - input_error = Some(format!("input `{}` requires {}", port.id, expected.label())); - expected.default_value() - } - None => expected.default_value(), - }; - - variables.insert(port.id.clone(), value); - } else { - if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") { - input_error = Some(format!("input `{}` requires an image", port.id)); - } - inputs.push(output.as_ref().and_then(NodeOutput::as_image).cloned()); - } - - incoming.push(output); - } - let vars = &variables; - let first = inputs.iter().flatten().next().map(|i| (i.w, i.h)); - let (w, h) = node_size(graph, def, node, first, opts.max_size); - let fail = |msg: String, key: u64| NodeResult { - outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]), - error: Some(msg), - ms: 0.0, - key, - cached: false, - }; - - if let Some(error) = input_error { - return fail(error, 0); - } - - // Parameters: defaults, overrides, then bindings to exposed inputs - let mut params = match def { - Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params), - _ => node.params.clone(), - }; - - for (param, exposed) in &node.bindings { - if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param)) - && let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default()) - { - params.insert(param.clone(), c); - } - } - let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32); - // Dynamic parameters: functions of the graph's inputs, evaluated once per cook - for (param, f) in &node.functions { - let Some(cur) = params.get(param) else { continue }; - match materialcraft_nodes::function::compile(f, seed) { - Ok(prog) => { - let context = materialcraft_nodes::function::EvaluationContext { - position: [0.5; 2], - size: [w as f32, h as f32], - images: &[], - tile: true, - variables: vars, - }; - - let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) { - Ok(value) => value, - Err(error) => return fail(format!("function of `{param}`: {error}"), 0), - }; - - if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) { - params.insert(param.clone(), c); - } - } - Err(e) => return fail(format!("function of `{param}`: {e}"), 0), - } - } - // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook) - if let Some(d) = def - && node.def != "graph_instance" - { - clamp_params(d, &mut params); - } - let tile = node.base.tiling[0] && node.base.tiling[1]; - // Input nodes read the caller's image for their identifier - let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); - let res_hash = match params.get("resource") { - Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), - _ => 0, - }; - - let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 }; - let key = hash_of(&( - &node.def, - serde_json::to_string(¶ms).unwrap_or_default(), - (w, h, seed, tile, node.disabled), - &input_keys, - res_hash, - sub_hash, - input_img.map(image_key), - variable_key(node, ¶ms, vars), - )); - if let Some(v) = lock(cache).get(key) { - return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; - } - let t0 = now_ms(); - let result: Result<Vec<NodeOutput>, String> = if node.disabled { - let output = incoming.iter().flatten().next().cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4]))); - Ok(vec![output; out_ports.len().max(1)]) - } else if node.def == "input_value" { - let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0)); - Ok(vec![NodeOutput::Value(value)]) - } else if node.def == "value_processor" { - evaluate_value(¶ms, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)]) - } 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().and_then(Clone::clone).map(|output| vec![output]).ok_or("missing value input".into()) - } else if let Some(image) = input_img { - let image = image.resize(w, h, tile); - let image = if node.def == "input_grayscale" { image.to_gray() } else { image }; - Ok(vec![NodeOutput::Image(image)]) - } else if node.def == materialcraft_core::MISSING_NODE { - let name = if node.label.is_empty() { "this node" } else { node.label.as_str() }; - Err(format!("unsupported node `{name}`")) - } else if node.def == "graph_instance" { - cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) - .map(|images| images.into_iter().map(NodeOutput::Image).collect()) - } else if let Some(definition) = def { - let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; - (definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect()) - } else { - Err(format!("unknown node `{}`", node.def)) - }; - - match result { - Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { - let v = Arc::new(imgs); - lock(cache).put(key, v.clone()); - NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } - } - Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), - Err(e) => fail(e, key), - } -} - -/// Whether graph `from` reaches `target`, without recursive stack growth -pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool { - let mut pending = vec![from]; - let mut seen = HashSet::new(); - while let Some(index) = pending.pop() { - if !seen.insert(index) { - continue; - } - let Some(graph) = pkg.graphs.get(index) else { continue }; - for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) { - if si == target { - return true; - } - pending.push(si); - } - } - false -} - -fn cook_instance( - pkg: &Package, - gi: usize, - node: &Node, - in_ports: &[Port], - out_ports: &[Port], - inputs: &[Option<Image>], - params: &BTreeMap<String, Value>, - size: (u32, u32), - opts: &Options, - cache: &Mutex<Cache>, -) -> Result<Vec<Image>, String> { - if opts.depth >= MAX_DEPTH { - return Err("graph instances nest too deep (does a graph use itself?)".into()); - } - let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; - if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) { - return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); - } - let mut o = Options::new(opts.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(gi); - o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); - o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); - let cooked = cook(pkg, sub_gi, &o, cache); - if cooked.cancelled { - return Err("cancelled".into()); - } - Ok(out_ports - .iter() - .map(|p| { - sub.nodes - .iter() - .find(|n| n.def == "output" && identifier(n) == p.id) - .and_then(|n| cooked.image(n.id, 0)) - .map(|i| i.resize(size.0, size.1, true)) - .unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4])) - }) - .collect()) -} - -/// 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>)> { - graph - .nodes - .iter() - .filter(|n| n.def == "output") - .map(|n| { - let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0).clamp(0, materialcraft_nodes::atomic::USAGE_IDS.len() as i32 - 1) as usize; - (n.id, materialcraft_nodes::atomic::USAGE_IDS.get(usage).copied().unwrap_or("any"), identifier(n), cooked.image(n.id, 0)) - }) - .collect() -} - -/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable) -pub fn now_ms() -> f64 { - #[cfg(not(target_arch = "wasm32"))] - { - static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); - START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0 - } - #[cfg(target_arch = "wasm32")] - 0.0 -} - -fn evaluate_value( - parameters: &BTreeMap<String, Value>, - variables: &BTreeMap<String, Value>, - seed: u32, - size: [u32; 2], - images: &[Option<Image>], - tile: bool, -) -> Result<Value, String> { - use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile}; - - let Some(Value::Function(graph)) = parameters.get("function") else { - return Err("missing value function".into()); - }; - - let program = compile(graph, seed)?; - let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables }; - - program.evaluate(&context, &mut EvaluationState::default()) -} - -fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, variables: &BTreeMap<String, Value>) -> u64 { - let mut names = std::collections::BTreeSet::new(); - let mut pending: Vec<&Value> = parameters.values().collect(); - while let Some(value) = pending.pop() { - match value { - Value::Function(graph) => { - for function in &graph.nodes { - if (function.op.starts_with("get_") || function.op == "isdefined") - && let Some(Value::Text(name)) = &function.value - { - names.insert(name.as_str()); - } - } - } - Value::PatternGraph(graph) => { - pending.extend(graph.nodes.iter().flat_map(|node| node.parameters.values())); - } - _ => {} - } - } - - let input_identifier = identifier(node); - if node.def == "input_value" { - names.insert(&input_identifier); - } - - let mut hasher = DefaultHasher::new(); - for name in names { - name.hash(&mut hasher); - variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher); - } - hasher.finish() + cooked.ms = (now_ms() - started_ms) as f32; + cooked } diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs new file mode 100644 index 00000000..6a700fd6 --- /dev/null +++ b/crates/eval/src/graph_instance.rs @@ -0,0 +1,71 @@ +use crate::{Cache, MAX_DEPTH, Options, Port, cook, identifier, instance_graph}; +use materialcraft_core::{Node, Package, Value}; +use materialcraft_image::{Image, Kind}; +use std::{ + collections::{BTreeMap, HashSet}, + sync::Mutex, +}; + +/// Whether graph `from` reaches `target`, without recursive stack growth +pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool { + let mut pending = vec![from]; + let mut seen = HashSet::new(); + while let Some(index) = pending.pop() { + if !seen.insert(index) { + continue; + } + let Some(graph) = pkg.graphs.get(index) else { continue }; + + for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) { + if si == target { + return true; + } + pending.push(si); + } + } + false +} + +pub(crate) fn cook_instance( + pkg: &Package, + gi: usize, + node: &Node, + in_ports: &[Port], + out_ports: &[Port], + inputs: &[Option<Image>], + params: &BTreeMap<String, Value>, + size: (u32, u32), + opts: &Options, + cache: &Mutex<Cache>, +) -> Result<Vec<Image>, String> { + if opts.depth >= MAX_DEPTH { + return Err("graph instances nest too deep (does a graph use itself?)".into()); + } + let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) { + return Err(format!("graph `{}` uses itself through a graph instance", sub.name)); + } + let mut o = Options::new(opts.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(gi); + o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); + o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + let cooked = cook(pkg, sub_gi, &o, cache); + if cooked.cancelled { + return Err("cancelled".into()); + } + Ok(out_ports + .iter() + .map(|p| { + sub.nodes + .iter() + .find(|n| n.def == "output" && identifier(n) == p.id) + .and_then(|n| cooked.image(n.id, 0)) + .map(|i| i.resize(size.0, size.1, true)) + .unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4])) + }) + .collect()) +} diff --git a/crates/eval/src/graph_output.rs b/crates/eval/src/graph_output.rs new file mode 100644 index 00000000..e96e0ff4 --- /dev/null +++ b/crates/eval/src/graph_output.rs @@ -0,0 +1,17 @@ +use crate::{Cooked, identifier}; +use materialcraft_core::{ComponentUsage, Graph, Node, NodeId, Value}; + +pub fn output_usage(node: &Node) -> &'static str { + let index = match node.params.get("usage") { + None => 0, + Some(Value::Enum(index)) => *index, + Some(value) => value.as_i32().map_or(ComponentUsage::ANY_INDEX, |index| index.max(0) as u32), + }; + ComponentUsage::from_index(index).id +} +use materialcraft_image::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>)> { + graph.nodes.iter().filter(|n| n.def == "output").map(|n| (n.id, output_usage(n), identifier(n), cooked.image(n.id, 0))).collect() +} diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index 2ee3b730..bee00925 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -5,21 +5,33 @@ mod cache; mod cache_key; mod cooked; mod graph_execution; +mod graph_instance; +mod graph_output; +mod node_execution; mod node_output; mod node_result; mod node_size; mod options; +mod parameter; mod port; +mod ports; +mod prepared_graph; +mod time; +mod value_execution; mod value_input_label; pub use cache::Cache; pub use cooked::Cooked; -pub use graph_execution::{cook, error_image, now_ms, outputs}; +pub use graph_execution::cook; +pub use graph_output::{output_usage, outputs}; +pub use node_execution::error_image; pub use node_output::NodeOutput; pub use node_result::NodeResult; pub use node_size::node_size; pub use options::Options; -pub use port::{Port, identifier, instance_graph, ports}; +pub use port::Port; +pub use ports::{identifier, instance_graph, ports, ports_with_connections}; +pub use time::now_ms; pub use value_input_label::value_input_label; pub const MAX_DEPTH: u32 = 8; diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs new file mode 100644 index 00000000..ac4b9456 --- /dev/null +++ b/crates/eval/src/node_execution.rs @@ -0,0 +1,158 @@ +use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, instance_graph, node_size, now_ms}; +use crate::{ + cache_key::{graph_tree_hash, hash_of, image_key, variable_key}, + graph_instance::cook_instance, + parameter::resolve_parameters, + prepared_graph::PreparedGraph, + value_execution::evaluate_value, +}; +use materialcraft_core::{Graph, Node, Package, Value}; +use materialcraft_image::{Image, Kind}; +use materialcraft_nodes::{CookContext, find}; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; + +/// The magenta image a failed node shows +pub fn error_image(w: u32, h: u32) -> Image { + Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0]) +} + +/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written) +fn lock(cache: &Mutex<Cache>) -> std::sync::MutexGuard<'_, Cache> { + cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +pub(crate) fn cook_node( + pkg: &Package, + gi: usize, + graph: &Graph, + prepared: &PreparedGraph<'_>, + node: &Node, + done: &Cooked, + vars: &BTreeMap<String, Value>, + opts: &Options, + cache: &Mutex<Cache>, +) -> NodeResult { + let (in_ports, out_ports) = prepared.ports(node.id); + let def = find(&node.def); + // Gather inputs by port order, with their keys + let mut inputs = Vec::new(); + let mut incoming = Vec::new(); + let mut input_keys = Vec::new(); + let mut variables = std::borrow::Cow::Borrowed(vars); + let mut input_error = None; + for port in in_ports { + let source = prepared.index.input_of(node.id, &port.id).and_then(|connection| { + let result = done.nodes.get(&connection.from)?; + let index = prepared.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?; + Some((result.outputs.get(index)?, result.key ^ hash_of(&index))) + }); + input_keys.push(source.as_ref().map_or(0, |source| source.1)); + let output = source.map(|source| source.0); + + if let Some(expected) = node.input_values.get(&port.id) { + let value = match output.as_ref() { + Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(*expected) => value.clone(), + Some(_) => { + input_error = Some(format!("input `{}` requires {}", port.id, expected.label())); + expected.default_value() + } + None => expected.default_value(), + }; + + variables.to_mut().insert(port.id.clone(), value); + } else { + if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") { + input_error = Some(format!("input `{}` requires an image", port.id)); + } + inputs.push(output.and_then(NodeOutput::as_image).cloned()); + } + + incoming.push(output); + } + let vars = &variables; + let first = inputs.iter().flatten().next().map(|i| (i.w, i.h)); + let (w, h) = node_size(graph, def, node, first, opts.max_size); + let fail = |msg: String, key: u64| NodeResult { + outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]), + error: Some(msg), + ms: 0.0, + key, + cached: false, + }; + + if let Some(error) = input_error { + return fail(error, 0); + } + + let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32); + let params = match resolve_parameters(node, def, vars, seed, [w, h]) { + Ok(parameters) => parameters, + Err(error) => return fail(error, 0), + }; + + let tile = node.base.tiling[0] && node.base.tiling[1]; + // Input nodes read the caller's image for their identifier + let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); + let res_hash = match params.get("resource") { + Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), + _ => 0, + }; + + let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 }; + + let key = hash_of(&( + &node.def, + serde_json::to_string(¶ms).unwrap_or_default(), + (w, h, seed, tile, node.disabled), + &input_keys, + res_hash, + sub_hash, + input_img.map(image_key), + variable_key(node, ¶ms, vars), + )); + if let Some(v) = lock(cache).get(key) { + return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; + } + let t0 = now_ms(); + let result: Result<Vec<NodeOutput>, String> = if node.disabled { + let output = incoming.iter().find_map(|output| *output).cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4]))); + Ok(vec![output; out_ports.len().max(1)]) + } else if node.def == "input_value" { + let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0)); + Ok(vec![NodeOutput::Value(value)]) + } else if node.def == "value_processor" { + evaluate_value(¶ms, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)]) + } 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_img { + let image = image.resize(w, h, tile); + let image = if node.def == "input_grayscale" { image.to_gray() } else { image }; + + Ok(vec![NodeOutput::Image(image)]) + } else if node.def == materialcraft_core::MISSING_NODE { + let name = if node.label.is_empty() { "this node" } else { node.label.as_str() }; + + Err(format!("unsupported node `{name}`")) + } else if node.def == "graph_instance" { + cook_instance(pkg, gi, node, in_ports, out_ports, &inputs, ¶ms, (w, h), opts, cache) + .map(|images| images.into_iter().map(NodeOutput::Image).collect()) + } else if let Some(definition) = def { + let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; + (definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect()) + } else { + Err(format!("unknown node `{}`", node.def)) + }; + + match result { + Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { + let v = Arc::new(imgs); + lock(cache).put(key, v.clone()); + NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } + } + Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), + Err(e) => fail(e, key), + } +} diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs new file mode 100644 index 00000000..5d2a7b57 --- /dev/null +++ b/crates/eval/src/parameter.rs @@ -0,0 +1,58 @@ +use materialcraft_core::{Node, Value}; +use materialcraft_nodes::{NodeDefinition, clamp_params, resolve_params}; +use std::collections::BTreeMap; + +pub(crate) fn resolve_parameters( + node: &Node, + def: Option<&NodeDefinition>, + vars: &BTreeMap<String, Value>, + seed: u32, + size: [u32; 2], +) -> Result<BTreeMap<String, Value>, String> { + // Parameters: defaults, overrides, then bindings to exposed inputs + let mut params = match def { + Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params), + _ => node.params.clone(), + }; + + for (param, exposed) in &node.bindings { + if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param)) + && let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default()) + { + params.insert(param.clone(), c); + } + } + // Dynamic parameters: functions of the graph's inputs, evaluated once per cook + for (param, f) in &node.functions { + let Some(cur) = params.get(param) else { continue }; + + match materialcraft_nodes::function::compile(f, seed) { + Ok(prog) => { + let context = materialcraft_nodes::function::EvaluationContext { + position: [0.5; 2], + size: size.map(|side| side as f32), + images: &[], + tile: true, + variables: vars, + }; + + let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) { + Ok(value) => value, + Err(error) => return Err(format!("function of `{param}`: {error}")), + }; + + if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) { + params.insert(param.clone(), c); + } + } + Err(e) => return Err(format!("function of `{param}`: {e}")), + } + } + // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook) + if let Some(d) = def + && node.def != "graph_instance" + { + clamp_params(d, &mut params); + } + Ok(params) +} diff --git a/crates/eval/src/port.rs b/crates/eval/src/port.rs index cde2aa28..2c35bbda 100644 --- a/crates/eval/src/port.rs +++ b/crates/eval/src/port.rs @@ -1,5 +1,4 @@ -use materialcraft_core::{Graph, Node, Package, Value}; -use materialcraft_nodes::{PortKind, find}; +use materialcraft_nodes::PortKind; #[derive(Clone, Debug, PartialEq)] pub struct Port { @@ -7,88 +6,3 @@ pub struct Port { pub label: String, pub kind: PortKind, } - -/// The input and output ports of a node in its package -pub fn ports(package: &Package, graph: &Graph, node: &Node) -> (Vec<Port>, Vec<Port>) { - if node.def == "graph_instance" { - let Some((_, graph)) = instance_graph(package, node) else { - return (Vec::new(), Vec::new()); - }; - - let graph_ports = |definition: &str| -> Vec<Port> { - graph - .nodes - .iter() - .filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_"))) - .map(|node| { - let id = identifier(node); - let kind = match node.def.as_str() { - "input_grayscale" => PortKind::Gray, - "input_color" => PortKind::Color, - _ => PortKind::Any, - }; - - Port { label: id.clone(), id, kind } - }) - .collect() - }; - - return (graph_ports("input"), graph_ports("output")); - } - - if node.def == materialcraft_core::MISSING_NODE { - let (inputs, outputs) = materialcraft_core::missing_ports(node); - let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect(); - let outputs = - outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect(); - - return (inputs, outputs); - } - - let Some(definition) = find(&node.def) else { - return (Vec::new(), Vec::new()); - }; - - let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind }; - let mut inputs: Vec<Port> = node - .input_values - .iter() - .map(|(identifier, value_type)| Port { - id: identifier.clone(), - label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()), - kind: PortKind::Value, - }) - .collect(); - inputs.extend(definition.inputs.iter().map(catalog_port)); - if let Some(prefix) = materialcraft_nodes::image_input_prefix(&node.def) { - let count = graph - .connections - .iter() - .filter(|connection| connection.to == node.id) - .filter_map(|connection| connection.to_port.strip_prefix(prefix)?.parse::<usize>().ok()) - .filter(|index| *index < materialcraft_nodes::MAX_IMAGE_INPUTS) - .map(|index| index + 2) - .max() - .unwrap_or(1) - .min(materialcraft_nodes::MAX_IMAGE_INPUTS); - inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any })); - } - - (inputs, definition.outputs.iter().map(catalog_port).collect()) -} - -/// The graph a graph-instance node refers to -pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> { - match node.params.get("graph") { - Some(Value::Text(name)) => pkg.graph_by_name(name), - _ => None, - } -} - -/// An input or output node's identifier (its `identifier` parameter, default "input"/"output") -pub fn identifier(n: &Node) -> String { - match n.params.get("identifier") { - Some(Value::Text(s)) if !s.is_empty() => s.clone(), - _ => if n.def == "output" { "output" } else { "input" }.into(), - } -} diff --git a/crates/eval/src/ports.rs b/crates/eval/src/ports.rs new file mode 100644 index 00000000..1ceb1f30 --- /dev/null +++ b/crates/eval/src/ports.rs @@ -0,0 +1,95 @@ +use crate::Port; +use materialcraft_core::{Graph, Node, Package, Value}; +use materialcraft_nodes::{PortKind, find}; + +/// The input and output ports of a node in its package +pub fn ports(package: &Package, graph: &Graph, node: &Node) -> (Vec<Port>, Vec<Port>) { + ports_with_connections(package, node, graph.connections.iter().filter(|connection| connection.to == node.id)) +} + +/// Resolve ports using the node's incoming connections in document order +pub fn ports_with_connections<'a>( + package: &Package, + node: &Node, + incoming: impl IntoIterator<Item = &'a materialcraft_core::Connection>, +) -> (Vec<Port>, Vec<Port>) { + if node.def == "graph_instance" { + let Some((_, graph)) = instance_graph(package, node) else { + return (Vec::new(), Vec::new()); + }; + + let graph_ports = |definition: &str| -> Vec<Port> { + graph + .nodes + .iter() + .filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_"))) + .map(|node| { + let id = identifier(node); + let kind = match node.def.as_str() { + "input_grayscale" => PortKind::Gray, + "input_color" => PortKind::Color, + _ => PortKind::Any, + }; + + Port { label: id.clone(), id, kind } + }) + .collect() + }; + + return (graph_ports("input"), graph_ports("output")); + } + + if node.def == materialcraft_core::MISSING_NODE { + let (inputs, outputs) = materialcraft_core::missing_ports(node); + let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect(); + let outputs = + outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect(); + + return (inputs, outputs); + } + + let Some(definition) = find(&node.def) else { + return (Vec::new(), Vec::new()); + }; + + let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind }; + let mut inputs: Vec<Port> = node + .input_values + .iter() + .map(|(identifier, value_type)| Port { + id: identifier.clone(), + label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()), + kind: PortKind::Value, + }) + .collect(); + inputs.extend(definition.inputs.iter().map(catalog_port)); + if let Some(prefix) = materialcraft_nodes::image_input_prefix(&node.def) { + let count = incoming + .into_iter() + .filter_map(|connection| connection.to_port.strip_prefix(prefix)?.parse::<usize>().ok()) + .filter(|index| *index < materialcraft_nodes::MAX_IMAGE_INPUTS) + .map(|index| index + 2) + .max() + .unwrap_or(1) + .min(materialcraft_nodes::MAX_IMAGE_INPUTS); + inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any })); + } + + (inputs, definition.outputs.iter().map(catalog_port).collect()) +} + +/// The graph a graph-instance node refers to +pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> { + match node.params.get("graph") { + Some(Value::Text(name)) => pkg.graph_by_name(name), + _ => None, + } +} + +/// An input or output node's identifier (its `identifier` parameter, default "input"/"output") +pub fn identifier(n: &Node) -> String { + match n.params.get("identifier") { + Some(Value::Text(s)) if !s.is_empty() => s.clone(), + _ => if n.def == "output" { "output" } else { "input" }.into(), + } +} diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs new file mode 100644 index 00000000..7a25bf4b --- /dev/null +++ b/crates/eval/src/prepared_graph.rs @@ -0,0 +1,31 @@ +use crate::{Port, ports_with_connections}; +use materialcraft_core::{Graph, GraphIndex, NodeId, Package}; +use std::collections::BTreeMap; + +/// Port definitions resolved once for a cook, alongside borrowed graph lookups +pub(crate) struct PreparedGraph<'a> { + pub index: GraphIndex<'a>, + pub order: Vec<NodeId>, + ports: BTreeMap<NodeId, (Vec<Port>, Vec<Port>)>, +} + +impl<'a> PreparedGraph<'a> { + pub fn new(package: &Package, graph: &'a Graph, roots: Option<&[NodeId]>) -> Self { + let index = GraphIndex::new(graph); + let needed = roots.map(|roots| index.required_nodes(roots)); + let order: Vec<_> = index.topo_order().into_iter().filter(|id| needed.as_ref().is_none_or(|needed| needed.contains(id))).collect(); + let ports = order + .iter() + .filter_map(|id| { + let node = index.node(*id)?; + Some((*id, ports_with_connections(package, node, index.incoming(*id).iter().copied()))) + }) + .collect(); + + Self { index, order, ports } + } + + pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) { + self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice())) + } +} diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 30dad6ba..9c714b42 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -1,4 +1,4 @@ -use crate::graph_execution::{graph_tree_hash, instances_reach}; +use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach}; use materialcraft_core::{NodeId, Package, Value}; use materialcraft_image::{Image, Kind}; use std::sync::Mutex; @@ -242,3 +242,32 @@ fn input_change_recooks_only_readers() { } assert!(!second.nodes[&reader].cached, "the reader must re-cook"); } + +#[test] +fn partial_cooks_keep_shared_dependencies_and_first_duplicate_node() { + let mut graph = Graph::new("Partial cook"); + graph.size = [4, 4]; + let source = graph.add_node("uniform", [0.0; 2]); + let first = graph.add_node("dot", [0.0; 2]); + let second = graph.add_node("dot", [0.0; 2]); + let unrelated = graph.add_node("uniform", [0.0; 2]); + graph.connect(source, "output", first, "input").unwrap(); + graph.connect(source, "output", second, "input").unwrap(); + + let mut duplicate = graph.node(source).unwrap().clone(); + duplicate.def = "input_value".into(); + graph.nodes.push(duplicate); + let mut package = Package::new("Partial cook"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + let mut options = Options::new(&no_res); + options.only = Some(vec![first, second]); + + let cooked = cook(&package, 0, &options, &cache); + assert_eq!(cooked.nodes.len(), 3); + assert!(!cooked.nodes.contains_key(&unrelated)); + for id in [source, first, second] { + assert!(cooked.nodes[&id].error.is_none()); + assert!(cooked.image(id, 0).is_some()); + } +} diff --git a/crates/eval/src/time.rs b/crates/eval/src/time.rs new file mode 100644 index 00000000..033626ae --- /dev/null +++ b/crates/eval/src/time.rs @@ -0,0 +1,10 @@ +/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable) +pub fn now_ms() -> f64 { + #[cfg(not(target_arch = "wasm32"))] + { + static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0 + } + #[cfg(target_arch = "wasm32")] + 0.0 +} diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs new file mode 100644 index 00000000..ee72c631 --- /dev/null +++ b/crates/eval/src/value_execution.rs @@ -0,0 +1,23 @@ +use materialcraft_core::Value; +use materialcraft_image::Image; +use std::collections::BTreeMap; + +pub(crate) fn evaluate_value( + parameters: &BTreeMap<String, Value>, + variables: &BTreeMap<String, Value>, + seed: u32, + size: [u32; 2], + images: &[Option<Image>], + tile: bool, +) -> Result<Value, String> { + use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile}; + + let Some(Value::Function(graph)) = parameters.get("function") else { + return Err("missing value function".into()); + }; + + let program = compile(graph, seed)?; + let context = EvaluationContext { position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables }; + + program.evaluate(&context, &mut EvaluationState::default()) +} diff --git a/crates/formats/src/material/archive.rs b/crates/formats/src/material/archive.rs index 2781c832..1c8a1deb 100644 --- a/crates/formats/src/material/archive.rs +++ b/crates/formats/src/material/archive.rs @@ -16,7 +16,20 @@ const SOURCE: &str = "source.sbs"; /// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear) pub fn srgb_usage(usage: &str) -> bool { - matches!(usage, "baseColor" | "emissive" | "specular") + matches!( + usage, + "baseColor" + | "diffuse" + | "emissive" + | "specular" + | "specularEdgeColor" + | "scatteringColor" + | "absorptionColor" + | "coatColor" + | "sheenColor" + | "reflection" + | "ambient" + ) } /// Whether other apps can set a value of this type from the manifest diff --git a/crates/formats/src/sbs/canvas.rs b/crates/formats/src/sbs/canvas.rs index efb3450a..c4d536f7 100644 --- a/crates/formats/src/sbs/canvas.rs +++ b/crates/formats/src/sbs/canvas.rs @@ -1,6 +1,10 @@ use super::sbs_writer::SbsWriter; +use super::warnings::Warnings; +use super::xml::{child_element, child_value, children_named, parse_floats}; use super::xml::{format_float, xml_escape}; +use materialcraft_core::{Comment, Frame, Pin, srgb_to_linear}; use materialcraft_core::{Graph, linear_to_srgb}; +use roxmltree::Node as XmlNode; use std::fmt::Write as _; pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) { @@ -43,3 +47,41 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu output.push_str("</GUIObjects>"); } + +pub(super) fn read_canvas_items(element: XmlNode, graph: &mut Graph, warnings: &mut Warnings) { + for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) { + let layout = child_element(item, "GUILayout"); + let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); + let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default(); + let x = position.first().copied().unwrap_or(0.0); + let y = position.get(1).copied().unwrap_or(0.0); + let width = size.first().copied().unwrap_or(180.0).max(8.0); + let height = size.get(1).copied().unwrap_or(70.0).max(8.0); + let text = child_value(item, "GUIName").unwrap_or("").to_string(); + + match child_value(item, "type") { + Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { + let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); + let color = match channels.as_slice() { + &[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha], + _ => [0.2, 0.4, 0.8, 0.25], + }; + let title = child_value(item, "title").unwrap_or("").to_string(); + let title_visible = child_value(item, "isTitleVisible") != Some("0"); + let id = graph.alloc_id(); + + graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color }); + } + Some("COMMENT") => { + let id = graph.alloc_id(); + graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); + } + Some("PIN") => { + let id = graph.alloc_id(); + graph.pins.push(Pin { id, name: text, pos: [x, y] }); + } + Some(other) => warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), + None => {} + } + } +} diff --git a/crates/formats/src/sbs/component_usage.rs b/crates/formats/src/sbs/component_usage.rs new file mode 100644 index 00000000..37b08b0e --- /dev/null +++ b/crates/formats/src/sbs/component_usage.rs @@ -0,0 +1,22 @@ +use materialcraft_core::{ComponentUsage, Node, Value}; +use roxmltree::Node as XmlNode; +use std::fmt::Write as _; + +use super::xml::{child_element, child_value}; + +pub(super) fn read(element: XmlNode) -> u32 { + child_element(element, "usages") + .and_then(|usages| child_element(usages, "usage")) + .and_then(|usage| child_value(usage, "name")) + .map_or(ComponentUsage::ANY_INDEX, ComponentUsage::index) +} + +pub(super) fn write(out: &mut String, node: &Node, default: u32) { + let index = match node.params.get("usage") { + None => default, + Some(Value::Enum(index)) => *index, + Some(value) => value.as_i32().map_or(ComponentUsage::ANY_INDEX, |index| index.max(0) as u32), + }; + let id = ComponentUsage::from_index(index).id; + let _ = write!(out, "<usages><usage><components v=\"RGBA\"/><name v=\"{id}\"/></usage></usages>"); +} diff --git a/crates/formats/src/sbs/input_bridge.rs b/crates/formats/src/sbs/input_bridge.rs index f800707d..73c86a3e 100644 --- a/crates/formats/src/sbs/input_bridge.rs +++ b/crates/formats/src/sbs/input_bridge.rs @@ -3,5 +3,6 @@ use materialcraft_core::Value; pub(super) struct InputBridge { pub identifier: String, pub type_code: u32, + pub usage: u32, pub default: Value, } diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index 7083cb5b..b3545a6a 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -1,5 +1,6 @@ mod base_parameters; mod canvas; +mod component_usage; mod connection; mod constant; mod embedded; @@ -24,9 +25,12 @@ mod warnings; mod xml; pub use constant::SBS_EXT; +pub use read::{is_sbs, read_sbs}; pub use sbs_read::SbsRead; -pub use sbs_reader::{is_sbs, read_sbs}; -pub use sbs_writer::write_sbs; +pub use write::write_sbs; #[cfg(test)] mod tests; + +mod read; +mod write; diff --git a/crates/formats/src/sbs/output.rs b/crates/formats/src/sbs/output.rs index 865975b3..8c758470 100644 --- a/crates/formats/src/sbs/output.rs +++ b/crates/formats/src/sbs/output.rs @@ -1,15 +1,5 @@ use materialcraft_nodes::PortKind; -pub(super) fn usage_index(name: &str) -> u32 { - let ids = materialcraft_nodes::atomic::USAGE_IDS; - let name = name.trim(); - let index = ids.iter().position(|u| u.eq_ignore_ascii_case(name)).or_else(|| name.eq_ignore_ascii_case("diffuse").then_some(0)); - index.unwrap_or(ids.len().saturating_sub(1)) as u32 -} - -pub(super) fn usage_name(index: u32) -> &'static str { - materialcraft_nodes::atomic::USAGE_IDS.get(index as usize).copied().unwrap_or("any") -} pub(super) fn output_type(graph: &materialcraft_core::Graph, id: materialcraft_core::NodeId, port: &str) -> u32 { if let Ok(Some(kind)) = materialcraft_nodes::output_value_type(graph, id) { return kind as u32; diff --git a/crates/formats/src/sbs/read.rs b/crates/formats/src/sbs/read.rs new file mode 100644 index 00000000..1958dd9d --- /dev/null +++ b/crates/formats/src/sbs/read.rs @@ -0,0 +1,99 @@ +use super::{ + constant::{MAX_GRAPHS, MAX_SBS_BYTES, MAX_XML_NODES, SNIFF_BYTES}, + placeholder::report_placeholders, + sbs_read::SbsRead, + sbs_reader::{SbsReader, unique_name}, + warnings::Warnings, + xml::{child_element, child_value, children_named}, +}; +use crate::{FormatError, Result}; +use materialcraft_core::{Graph, Package}; +use roxmltree::Node as XmlNode; +use std::collections::HashMap; + +pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<SbsRead> { + if bytes.len() > MAX_SBS_BYTES { + return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); + } + + let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; + let text = text.trim_start_matches('\u{feff}'); + let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES }; + let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?; + let root = doc.root_element(); + if root.tag_name().name() != "package" { + return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into())); + } + + let mut warnings = Warnings::default(); + let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); + let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); + let package_name = match child_value(root, "identifier").map(str::trim) { + Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), + _ if !file_stem.is_empty() => file_stem.to_string(), + _ => "Untitled package".to_string(), + }; + + let mut reader = + SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 }; + for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { + if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { + reader.dependencies.insert(uid.to_string(), file.to_string()); + } + } + + // Load resources before resolving graph references + let content = child_element(root, "content"); + let mut pkg = Package::new(&package_name); + let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); + if let Some(content) = content { + reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); + } + + // Name every graph first so instances can refer to graphs defined later in the file + let mut names: Vec<String> = Vec::new(); + for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { + let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); + let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); + reader.graph_names.insert(path.clone(), unique.clone()); + names.push(unique); + } + if graph_elements.len() > MAX_GRAPHS { + reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); + } + + for ((_, graph), name) in graph_elements.iter().zip(names) { + let graph = reader.read_graph(*graph, name); + pkg.graphs.push(graph); + } + if pkg.graphs.is_empty() { + reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); + pkg.graphs.push(Graph::new("Graph")); + } + + report_placeholders(&pkg, reader.warnings); + Ok(SbsRead { pkg, warnings: warnings.finish() }) +} +pub fn is_sbs(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); + let mut rest = head.trim_start_matches('\u{feff}'); + + // Skip the XML declaration and comments before the root element + loop { + rest = rest.trim_start(); + let (skip_open, skip_close) = if rest.starts_with("<?") { + ("<?", "?>") + } else if rest.starts_with("<!--") { + ("<!--", "-->") + } else { + break; + }; + + match rest[skip_open.len()..].find(skip_close) { + Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], + None => return false, + } + } + + rest.strip_prefix("<package").is_some_and(|after| after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace())) +} diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index 12f0bdb9..ffde83e7 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -1,23 +1,20 @@ use super::base_parameters::read_base_params; +use super::component_usage; use super::connection::connect_all; -use super::constant::{MAX_GRAPHS, MAX_NODES, MAX_RESOURCES, MAX_SBS_BYTES, MAX_XML_NODES}; -use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY, SNIFF_BYTES}; +use super::constant::{MAX_NODES, MAX_RESOURCES}; +use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY}; use super::embedded::decode_embedded; use super::filter_map::{BASE_PARAMS, FilterMap, HANDLED_PARAMS, filter_by_sbs_name}; use super::function_graph; use super::input_bridge::InputBridge; -use super::output::usage_index; -use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs, report_placeholders}; +use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs}; use super::read_node::ReadNode; -use super::sbs_read::SbsRead; use super::sbs_value::{SbsValue, exposed_default, sbs_constant, to_natural_value, to_param_value}; use super::type_code; use super::warnings::Warnings; use super::xml::{child_element, child_value, children_named, parse_floats}; -use crate::{FormatError, Result}; use materialcraft_core::{ - Comment, Connection, ExposedParameter, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Pin, Resource, ResourceBytes, - Value, srgb_to_linear, + ComponentUsage, Connection, ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Resource, ResourceBytes, Value, }; use materialcraft_nodes::find; use roxmltree::Node as XmlNode; @@ -100,10 +97,12 @@ impl<'text> SbsReader<'text, '_> { match bytes { Some(data) => { let ext = if kind == "svg" { "svg".to_string() } else { format }; + pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); } None => { let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; + self.warnings.add(format!("resource `{path}` could not be loaded: {why}")); } } @@ -150,7 +149,7 @@ impl<'text> SbsReader<'text, '_> { } }); if let Some(dynamic) = dynamic { - self.read_canvas_items(dynamic, &mut graph); + super::canvas::read_canvas_items(dynamic, &mut graph, self.warnings); } return graph; } @@ -167,6 +166,7 @@ impl<'text> SbsReader<'text, '_> { } let Some(uid) = child_value(*comp_node, "uid").map(str::to_string) else { continue }; + if read_nodes.contains_key(&uid) { self.warnings.add(format!("graph `{name}`: duplicate node uid {uid} skipped")); continue; @@ -189,7 +189,7 @@ impl<'text> SbsReader<'text, '_> { let wires = self.read_wires(&mut graph, &comp_nodes, &read_nodes); connect_all(&mut graph, wires, self.warnings); - self.read_canvas_items(element, &mut graph); + super::canvas::read_canvas_items(element, &mut graph, self.warnings); graph } pub(super) fn read_graph_inputs(&mut self, element: XmlNode, graph: &mut Graph) -> HashMap<String, InputBridge> { @@ -202,7 +202,10 @@ impl<'text> SbsReader<'text, '_> { .and_then(sbs_constant) .and_then(|value| to_param_value(&Value::Color([0.5, 0.5, 0.5, 1.0]), &value, 0)) .unwrap_or(Value::Color([0.5, 0.5, 0.5, 1.0])); - image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default }); + image_inputs.insert( + child_value(input, "uid").unwrap_or("").to_string(), + InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default }, + ); continue; } if graph.exposed.iter().any(|e| e.id == id) { @@ -211,7 +214,10 @@ impl<'text> SbsReader<'text, '_> { let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref()); if child_value(input, "isConnectable") == Some("1") { - image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), InputBridge { identifier: id, type_code: code as u32, default }); + image_inputs.insert( + child_value(input, "uid").unwrap_or("").to_string(), + InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default }, + ); continue; } let label = child_element(input, "attributes").and_then(|a| child_value(a, "label")).filter(|l| !l.is_empty()).unwrap_or(&id).to_string(); @@ -238,6 +244,7 @@ impl<'text> SbsReader<'text, '_> { for comp_node in comp_nodes { let Some(to) = child_value(*comp_node, "uid").and_then(|u| read_nodes.get(u)) else { continue }; + for connection in child_element(*comp_node, "connections").into_iter().flat_map(|c| children_named(c, "connection")) { let sbs_input = child_value(connection, "identifier").unwrap_or(""); let Some(from) = child_value(connection, "connRef").and_then(|u| read_nodes.get(u)) else { @@ -275,44 +282,6 @@ impl<'text> SbsReader<'text, '_> { wires } - pub(super) fn read_canvas_items(&mut self, element: XmlNode, graph: &mut Graph) { - for item in child_element(element, "GUIObjects").into_iter().flat_map(|objects| children_named(objects, "GUIObject")) { - let layout = child_element(item, "GUILayout"); - let position = layout.and_then(|layout| child_value(layout, "gpos")).map(parse_floats).unwrap_or_default(); - let size = layout.and_then(|layout| child_value(layout, "size")).map(parse_floats).unwrap_or_default(); - let x = position.first().copied().unwrap_or(0.0); - let y = position.get(1).copied().unwrap_or(0.0); - let width = size.first().copied().unwrap_or(180.0).max(8.0); - let height = size.get(1).copied().unwrap_or(70.0).max(8.0); - let text = child_value(item, "GUIName").unwrap_or("").to_string(); - - match child_value(item, "type") { - Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { - let channels = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); - let color = match channels.as_slice() { - &[red, green, blue, alpha, ..] => [srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha], - _ => [0.2, 0.4, 0.8, 0.25], - }; - let title = child_value(item, "title").unwrap_or("").to_string(); - let title_visible = child_value(item, "isTitleVisible") != Some("0"); - let id = graph.alloc_id(); - - graph.frames.push(Frame { id, title, title_visible, description: text, rect: [x, y, width, height], color }); - } - Some("COMMENT") => { - let id = graph.alloc_id(); - graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); - } - Some("PIN") => { - let id = graph.alloc_id(); - graph.pins.push(Pin { id, name: text, pos: [x, y] }); - } - Some(other) => self.warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), - None => {} - } - } - } - pub(super) fn read_node( &mut self, graph: &mut Graph, @@ -354,6 +323,7 @@ impl<'text> SbsReader<'text, '_> { if let Some(node) = node { let identifier = input.map_or("input", |input| input.identifier.as_str()); node.params.insert("identifier".into(), Value::Text(identifier.to_string())); + node.params.insert("usage".into(), Value::Enum(input.map_or(ComponentUsage::ANY_INDEX, |input| input.usage))); if let Some(input) = input { node.params.insert("default".into(), input.default.clone()); } @@ -363,7 +333,7 @@ impl<'text> SbsReader<'text, '_> { } "compOutputBridge" => { let output = child_value(implementation, "output").unwrap_or(""); - let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), usage_index("any"))); + let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), ComponentUsage::ANY_INDEX)); let (id, index, node) = push_node(graph, "output", pos); if let Some(node) = node { node.params.insert("identifier".into(), Value::Text(identifier)); @@ -465,6 +435,7 @@ impl<'text> SbsReader<'text, '_> { } let Some(dynamic) = child_element(param_value, "dynamicValue") else { return }; + match function_graph::read(dynamic) { Ok(graph) if matches!(like, Value::Function(_)) => { node.params.insert(id.to_string(), Value::Function(Box::new(graph))); @@ -513,93 +484,6 @@ impl<'text> SbsReader<'text, '_> { } } } -pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<SbsRead> { - if bytes.len() > MAX_SBS_BYTES { - return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); - } - - let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; - let text = text.trim_start_matches('\u{feff}'); - let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES }; - let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?; - let root = doc.root_element(); - if root.tag_name().name() != "package" { - return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into())); - } - - let mut warnings = Warnings::default(); - let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); - let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); - let package_name = match child_value(root, "identifier").map(str::trim) { - Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), - _ if !file_stem.is_empty() => file_stem.to_string(), - _ => "Untitled package".to_string(), - }; - - let mut reader = - SbsReader { text, warnings: &mut warnings, dependencies: HashMap::new(), graph_names: HashMap::new(), resource_names: HashMap::new(), node_count: 0 }; - for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { - if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { - reader.dependencies.insert(uid.to_string(), file.to_string()); - } - } - - // Load resources before resolving graph references - let content = child_element(root, "content"); - let mut pkg = Package::new(&package_name); - let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); - if let Some(content) = content { - reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); - } - - // Name every graph first so instances can refer to graphs defined later in the file - let mut names: Vec<String> = Vec::new(); - for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { - let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); - let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); - reader.graph_names.insert(path.clone(), unique.clone()); - names.push(unique); - } - if graph_elements.len() > MAX_GRAPHS { - reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); - } - - for ((_, graph), name) in graph_elements.iter().zip(names) { - let graph = reader.read_graph(*graph, name); - pkg.graphs.push(graph); - } - if pkg.graphs.is_empty() { - reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); - pkg.graphs.push(Graph::new("Graph")); - } - - report_placeholders(&pkg, reader.warnings); - Ok(SbsRead { pkg, warnings: warnings.finish() }) -} -pub fn is_sbs(bytes: &[u8]) -> bool { - let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); - let mut rest = head.trim_start_matches('\u{feff}'); - - // Skip the XML declaration and comments before the root element - loop { - rest = rest.trim_start(); - let (skip_open, skip_close) = if rest.starts_with("<?") { - ("<?", "?>") - } else if rest.starts_with("<!--") { - ("<!--", "-->") - } else { - break; - }; - - match rest[skip_open.len()..].find(skip_close) { - Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], - None => return false, - } - } - - rest.strip_prefix("<package").is_some_and(|after| after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace())) -} - pub(super) fn unique_name(taken: &[String], base: &str) -> String { let free = |name: &str| !taken.iter().any(|t| t == name); if free(base) { @@ -616,10 +500,7 @@ pub(super) fn read_graph_outputs(element: XmlNode) -> HashMap<String, (String, u let mut outputs = HashMap::new(); for output in child_element(element, "graphOutputs").into_iter().flat_map(|o| children_named(o, "graphoutput")) { let identifier = child_value(output, "identifier").unwrap_or("output").to_string(); - let usage = child_element(output, "usages") - .and_then(|u| child_element(u, "usage")) - .and_then(|u| child_value(u, "name")) - .map_or(usage_index("any"), usage_index); + let usage = component_usage::read(output); outputs.insert(child_value(output, "uid").unwrap_or("").to_string(), (identifier, usage)); } outputs diff --git a/crates/formats/src/sbs/sbs_value.rs b/crates/formats/src/sbs/sbs_value.rs index 98cfb262..a1072e92 100644 --- a/crates/formats/src/sbs/sbs_value.rs +++ b/crates/formats/src/sbs/sbs_value.rs @@ -73,6 +73,7 @@ pub(super) fn to_param_value(like: &Value, value: &SbsValue, options: usize) -> // SBS colors are stored as displayed (sRGB); MaterialCraft's are linear Value::Color(_) if value.component_count() >= 3 => { let alpha = if value.component_count() >= 4 { f(3) } else { 1.0 }; + Value::Color([srgb_to_linear(f(0)), srgb_to_linear(f(1)), srgb_to_linear(f(2)), alpha]) } Value::Color(_) => { @@ -137,21 +138,9 @@ pub(super) fn exposed_default(code: i64, value: Option<&SbsValue>) -> Value { } pub(super) fn exposed_type_code(value: &Value) -> i64 { - use type_code::*; - - match value { - Value::Bool(_) => BOOL, - Value::Int(_) | Value::Enum(_) => INT1, - Value::Int2(_) => INT2, - Value::Int3(_) => INT3, - Value::Int4(_) => INT4, - Value::Float(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => FLOAT1, - Value::Float2(_) => FLOAT2, - Value::Float3(_) => FLOAT3, - Value::Float4(_) | Value::Color(_) => FLOAT4, - Value::Text(_) => STRING, - } + materialcraft_core::ValueType::of(value).map_or(type_code::FLOAT1, |kind| i64::from(kind as u32)) } + pub(super) fn constant_xml(value: &Value) -> Option<String> { let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::<Vec<_>>().join(" "); let (tag, text) = match value { diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs index c87aeb10..6915524d 100644 --- a/crates/formats/src/sbs/sbs_writer.rs +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -1,18 +1,17 @@ use super::base_parameters::base_params_xml; use super::canvas::write_canvas_items; -use super::constant::FORMAT_VERSION; -use super::constant::{FIRST_UID, NODE_HALF_SIZE, SELF_DEPENDENCY}; -use super::embedded::encode_embedded; +use super::component_usage; +use super::constant::NODE_HALF_SIZE; use super::filter_map::filter_by_def; use super::function_graph; use super::node_identifiers::NodeIdentifiers; use super::node_parameter::{param_xml, special_filter_params_xml, text_param}; -use super::output::{output_type, usage_name}; +use super::output::output_type; use super::sbs_value::{constant_xml, exposed_type_code}; use super::type_code; use super::xml::{format_float, is_parameters_element, xml_escape}; use crate::{FormatError, Result}; -use materialcraft_core::{Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports}; +use materialcraft_core::{ComponentUsage, Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports}; use materialcraft_nodes::find; use std::collections::{BTreeMap, HashMap}; use std::fmt::Write as _; @@ -120,6 +119,7 @@ impl SbsWriter { out.push_str("<connections>"); for wire in wires { let Some(from_uid) = node_uids.get(&wire.from) else { continue }; + let Some((_, _, output_uid)) = node_outputs.get(&wire.from).and_then(|o| o.iter().find(|(port, _, _)| *port == wire.from_port)) else { continue; }; @@ -169,6 +169,7 @@ impl SbsWriter { let uid = self.next_uid(); entries.insert(node.id, uid); let fallback = if node.def == "input_value" { Value::Float(0.0) } else { Value::Color([0.5, 0.5, 0.5, 1.0]) }; + let value = node.params.get("default").unwrap_or(&fallback); let default = constant_xml(value).unwrap_or_default(); let code = match node.def.as_str() { @@ -179,14 +180,17 @@ impl SbsWriter { let _ = write!( out, - "<paraminput><identifier v=\"{}\"/><uid v=\"{uid}\"/><isConnectable v=\"1\"/><type v=\"{code}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"\"/><options/></defaultWidget></paraminput>", + "<paraminput><identifier v=\"{}\"/><uid v=\"{uid}\"/><isConnectable v=\"1\"/><type v=\"{code}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"\"/><options/></defaultWidget>", xml_escape(&text_param(node, "identifier", "input")) ); + component_usage::write(out, node, ComponentUsage::ANY_INDEX); + out.push_str("</paraminput>"); } for exposed in &graph.exposed { let default = constant_xml(graph.inputs.get(&exposed.id).unwrap_or(&exposed.default)).unwrap_or_else(|| "<constantValueFloat1 v=\"0\"/>".into()); let group = if exposed.group.is_empty() { String::new() } else { format!("<group v=\"{}\"/>", xml_escape(&exposed.group)) }; + let _ = write!( out, "<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/><attributes><label v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"slider\"/><options><option><name v=\"min\"/><value v=\"{}\"/></option><option><name v=\"max\"/><value v=\"{}\"/></option></options></defaultWidget>{group}</paraminput>", @@ -209,18 +213,19 @@ impl SbsWriter { for node in graph.nodes.iter().filter(|n| n.def == "output") { let uid = self.next_uid(); output_uids.insert(node.id, uid); - let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0).max(0) as u32; let code = output_type(graph, node.id, "output"); let channels = format!("<channels v=\"{code}\"/>"); let identifier = text_param(node, "identifier", "output"); let label = if node.label.is_empty() { identifier.clone() } else { node.label.clone() }; + let _ = write!( out, - "<graphoutput><identifier v=\"{}\"/><uid v=\"{uid}\"/><attributes><label v=\"{}\"/></attributes><usages><usage><components v=\"RGBA\"/><name v=\"{}\"/></usage></usages><group v=\"Material\"/>{channels}</graphoutput>", + "<graphoutput><identifier v=\"{}\"/><uid v=\"{uid}\"/><attributes><label v=\"{}\"/></attributes>", xml_escape(&identifier), - xml_escape(&label), - usage_name(usage) + xml_escape(&label) ); + component_usage::write(out, node, 0); + let _ = write!(out, "<group v=\"Material\"/>{channels}</graphoutput>"); } out.push_str("</graphOutputs>"); @@ -276,6 +281,7 @@ impl SbsWriter { let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default)); for (sbs_name, mc_name) in filter.params { let Some(value) = value_of(mc_name) else { continue }; + let binding = node.bindings.get(*mc_name).map(|identifier| function_graph::binding(identifier, value)).transpose().map_err(FormatError::Io)?; let function = node.functions.get(*mc_name).or(binding.as_ref()).or_else(|| match value { @@ -311,62 +317,6 @@ impl SbsWriter { Ok(()) } } -pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> { - let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; - let self_uid = writer.next_uid(); - - let mut content = String::from("<content>"); - for graph in &pkg.graphs { - if graph.function.is_some() { - super::standalone_function::write(&mut content, graph, &mut writer)?; - } else { - writer.write_graph(&mut content, pkg, graph, self_uid)?; - } - } - if !pkg.resources.is_empty() { - let _ = write!(content, "<group><uid v=\"{}\"/><identifier v=\"Resources\"/><content>", writer.next_uid()); - for resource in &pkg.resources { - let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); - let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); - let _ = write!( - content, - "<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - resource.bytes.len(), - encode_embedded(resource.bytes.as_slice())? - ); - } - content.push_str("</content></group>"); - } - content.push_str("</content>"); - - let mut out = String::with_capacity(content.len() + 4096); - let _ = write!( - out, - "<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><identifier v=\"{}\"/><formatVersion v=\"{FORMAT_VERSION}\"/><updaterVersion v=\"{FORMAT_VERSION}\"/><fileUID v=\"0\"/><versionUID v=\"0\"/><dependencies>", - xml_escape(&pkg.name) - ); - let write_dependency = |out: &mut String, file: &str, uid: u64| { - let _ = write!( - out, - "<dependency><filename v=\"{}\"/><uid v=\"{uid}\"/><type v=\"package\"/><fileUID v=\"0\"/><versionUID v=\"0\"/></dependency>", - xml_escape(file) - ); - }; - - write_dependency(&mut out, SELF_DEPENDENCY, self_uid); - for (file, uid) in &writer.external_packages { - write_dependency(&mut out, file, *uid); - } - out.push_str("</dependencies>"); - out.push_str(&content); - - out.push_str("</package>\n"); - Ok(out.into_bytes()) -} pub(super) type WrittenOutputs = Vec<(String, u32, u64)>; pub(super) fn write_bridgings(out: &mut String, outputs: &[(String, u32, u64)]) { diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index ce058f1b..5b1c1dca 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -1,6 +1,6 @@ use super::embedded::{base64_engine, decode_embedded, encode_embedded}; -use super::sbs_reader::{is_sbs, read_sbs}; -use super::sbs_writer::write_sbs; +use super::read::{is_sbs, read_sbs}; +use super::write::write_sbs; use base64::Engine as _; use materialcraft_core::{Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Package, Resource, ResourceBytes, SizeMode, Value, missing_ports}; @@ -81,6 +81,7 @@ fn structural_round_trip() { assert_eq!(back.nodes[1].params.get("intensity"), Some(&Value::Float(4.5))); let Some(Value::Color(color)) = back.nodes[2].params.get("color") else { panic!("uniform color") }; + assert!((color[0] - 0.25).abs() < 1e-3 && (color[2] - 0.75).abs() < 1e-3); assert_eq!(back.nodes[3].params.get("mode"), Some(&Value::Enum(3))); assert_eq!(back.nodes[4].params.get("usage"), Some(&Value::Enum(4))); @@ -242,6 +243,7 @@ fn native_function_fixture_retains_operation_types_and_ports() { assert!(read.warnings.is_empty(), "{:?}", read.warnings); let back = read_sbs(&write_sbs(&read.pkg).unwrap(), "values.sbs", &no_linked_files).unwrap(); let Value::Function(function) = &back.pkg.graphs[0].nodes[0].params["function"] else { panic!("missing function") }; + assert_eq!(function.nodes[0].value, Some(Value::Int(16_777_217))); assert_eq!(function.nodes[2].op, "add"); assert_eq!(function.nodes[2].type_code, 16); @@ -301,3 +303,61 @@ fn navigation_pins_round_trip_in_graphs_and_functions() { assert_eq!(reopened.pkg.graphs[0].pins, *pins); } } + +#[test] +fn component_usages_round_trip_without_reassigning_existing_indices() { + use materialcraft_core::ComponentUsage; + + let original = ["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; + for (index, id) in original.iter().enumerate() { + assert_eq!(ComponentUsage::from_index(index as u32).id, *id); + } + assert_eq!(ComponentUsage::from_index(u32::MAX), ComponentUsage::ANY); + assert_eq!(ComponentUsage::index("futureUsage"), ComponentUsage::ANY_INDEX); + assert_eq!(ComponentUsage::index(" DIFFUSE "), ComponentUsage::index("diffuse")); + + let mut package = Package::new("Usage round trip"); + let mut graph = Graph::new("Usages"); + for definition in ["output", "input_color", "input_grayscale", "input_value"] { + for (index, usage) in ComponentUsage::ALL.iter().enumerate() { + let id = graph.add_node(definition, [index as f32 * 160.0, 0.0]); + graph + .node_mut(id) + .unwrap() + .params + .extend([("identifier".into(), Value::Text(format!("{definition}_{}", usage.id))), ("usage".into(), Value::Enum(index as u32))]); + } + } + package.graphs.push(graph); + let xml = write_sbs(&package).unwrap(); + let restored = read_sbs(&xml, "usages.sbs", &no_linked_files).unwrap(); + assert!(restored.warnings.is_empty(), "{:?}", restored.warnings); + assert_eq!(restored.pkg.graphs[0].nodes.len(), package.graphs[0].nodes.len()); + for (original, node) in package.graphs[0].nodes.iter().zip(&restored.pkg.graphs[0].nodes) { + assert_eq!(node.def, original.def); + assert_eq!(node.params.get("usage"), original.params.get("usage")); + assert_eq!(node.params.get("identifier"), original.params.get("identifier")); + } +} + +#[test] +fn input_usage_defaults_and_unknown_metadata_stay_unclassified() { + use materialcraft_core::ComponentUsage; + + let mut package = Package::new("Input usages"); + let mut graph = Graph::new("Inputs"); + for definition in ["input_color", "input_grayscale", "input_value"] { + graph.add_node(definition, [0.0; 2]); + } + package.graphs.push(graph); + let saved = String::from_utf8(write_sbs(&package).unwrap()).unwrap(); + let usage = "<usages><usage><components v=\"RGBA\"/><name v=\"any\"/></usage></usages>"; + assert_eq!(saved.matches(usage).count(), 3); + for xml in [saved.clone(), saved.replace(usage, ""), saved.replace("<name v=\"any\"/>", "<name v=\"futureUsage\"/>")] { + let restored = read_sbs(xml.as_bytes(), "inputs.sbs", &no_linked_files).unwrap(); + assert_eq!(restored.pkg.graphs[0].nodes.len(), 3); + for node in &restored.pkg.graphs[0].nodes { + assert_eq!(node.params.get("usage"), Some(&Value::Enum(ComponentUsage::ANY_INDEX))); + } + } +} diff --git a/crates/formats/src/sbs/type_code.rs b/crates/formats/src/sbs/type_code.rs index 8b541431..4db589fe 100644 --- a/crates/formats/src/sbs/type_code.rs +++ b/crates/formats/src/sbs/type_code.rs @@ -1,12 +1,14 @@ +use materialcraft_core::ValueType; + pub const COLOR_IMAGE: i64 = 1; pub const GRAY_IMAGE: i64 = 2; -pub const BOOL: i64 = 4; -pub const INT1: i64 = 16; -pub const INT2: i64 = 32; -pub const INT3: i64 = 64; -pub const INT4: i64 = 128; -pub const FLOAT1: i64 = 256; -pub const FLOAT2: i64 = 512; -pub const FLOAT3: i64 = 1024; -pub const FLOAT4: i64 = 2048; -pub const STRING: i64 = 16384; +pub const BOOL: i64 = ValueType::Boolean as i64; +pub const INT1: i64 = ValueType::Integer as i64; +pub const INT2: i64 = ValueType::Integer2 as i64; +pub const INT3: i64 = ValueType::Integer3 as i64; +pub const INT4: i64 = ValueType::Integer4 as i64; +pub const FLOAT1: i64 = ValueType::Float as i64; +pub const FLOAT2: i64 = ValueType::Float2 as i64; +pub const FLOAT3: i64 = ValueType::Float3 as i64; +pub const FLOAT4: i64 = ValueType::Float4 as i64; +pub const STRING: i64 = ValueType::String as i64; diff --git a/crates/formats/src/sbs/write.rs b/crates/formats/src/sbs/write.rs new file mode 100644 index 00000000..dbed6974 --- /dev/null +++ b/crates/formats/src/sbs/write.rs @@ -0,0 +1,66 @@ +use super::{ + constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY}, + embedded::encode_embedded, + sbs_writer::SbsWriter, + xml::xml_escape, +}; +use crate::Result; +use materialcraft_core::Package; +use std::{collections::BTreeMap, fmt::Write as _}; + +pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> { + let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; + let self_uid = writer.next_uid(); + + let mut content = String::from("<content>"); + for graph in &pkg.graphs { + if graph.function.is_some() { + super::standalone_function::write(&mut content, graph, &mut writer)?; + } else { + writer.write_graph(&mut content, pkg, graph, self_uid)?; + } + } + if !pkg.resources.is_empty() { + let _ = write!(content, "<group><uid v=\"{}\"/><identifier v=\"Resources\"/><content>", writer.next_uid()); + for resource in &pkg.resources { + let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); + let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); + let _ = write!( + content, + "<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>", + xml_escape(&resource.name), + writer.next_uid(), + if svg { "svg" } else { "bitmap" }, + xml_escape(ext), + resource.bytes.len(), + encode_embedded(resource.bytes.as_slice())? + ); + } + content.push_str("</content></group>"); + } + content.push_str("</content>"); + + let mut out = String::with_capacity(content.len() + 4096); + let _ = write!( + out, + "<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><identifier v=\"{}\"/><formatVersion v=\"{FORMAT_VERSION}\"/><updaterVersion v=\"{FORMAT_VERSION}\"/><fileUID v=\"0\"/><versionUID v=\"0\"/><dependencies>", + xml_escape(&pkg.name) + ); + let write_dependency = |out: &mut String, file: &str, uid: u64| { + let _ = write!( + out, + "<dependency><filename v=\"{}\"/><uid v=\"{uid}\"/><type v=\"package\"/><fileUID v=\"0\"/><versionUID v=\"0\"/></dependency>", + xml_escape(file) + ); + }; + + write_dependency(&mut out, SELF_DEPENDENCY, self_uid); + for (file, uid) in &writer.external_packages { + write_dependency(&mut out, file, *uid); + } + out.push_str("</dependencies>"); + out.push_str(&content); + + out.push_str("</package>\n"); + Ok(out.into_bytes()) +} diff --git a/crates/nodes/src/atomic/input_color.rs b/crates/nodes/src/atomic/input_color.rs index 6cea4eff..fa94be9b 100644 --- a/crates/nodes/src/atomic/input_color.rs +++ b/crates/nodes/src/atomic/input_color.rs @@ -1,5 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_core::ComponentUsage; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { @@ -8,6 +9,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .generator() .text("identifier", "Identifier", "input") + .component_usage(ComponentUsage::ANY_INDEX) .color("default", "Default color", [0.5, 0.5, 0.5, 1.0]) .color_out() .cook(input_color_default) diff --git a/crates/nodes/src/atomic/input_grayscale.rs b/crates/nodes/src/atomic/input_grayscale.rs index ac1f1f15..80900df7 100644 --- a/crates/nodes/src/atomic/input_grayscale.rs +++ b/crates/nodes/src/atomic/input_grayscale.rs @@ -1,5 +1,6 @@ use super::GRAPH_ITEMS; use crate::{CookContext, CookResult, NodeDefinition, node}; +use materialcraft_core::ComponentUsage; use materialcraft_image::{Image, Kind}; pub(super) fn definition() -> NodeDefinition { @@ -8,6 +9,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .generator() .text("identifier", "Identifier", "input") + .component_usage(ComponentUsage::ANY_INDEX) .color("default", "Default value", [0.5, 0.5, 0.5, 1.0]) .gray_out() .cook(input_gray_default) diff --git a/crates/nodes/src/atomic/input_value.rs b/crates/nodes/src/atomic/input_value.rs index b28aa98a..4178e2ce 100644 --- a/crates/nodes/src/atomic/input_value.rs +++ b/crates/nodes/src/atomic/input_value.rs @@ -1,11 +1,13 @@ use super::GRAPH_ITEMS; use crate::{NodeDefinition, PortKind, node}; +use materialcraft_core::ComponentUsage; pub(super) fn definition() -> NodeDefinition { node("input_value", "Input Value", GRAPH_ITEMS) .desc("A typed value input of the graph.") .atomic() .text("identifier", "Identifier", "value") + .component_usage(ComponentUsage::ANY_INDEX) .float("default", "Default", 0.0, 0.0, 0.0) .output("output", "Value", PortKind::Value) .cook(crate::node_definition_builder::no_cook) diff --git a/crates/nodes/src/atomic/mod.rs b/crates/nodes/src/atomic/mod.rs index 7cea5328..33a2a17b 100644 --- a/crates/nodes/src/atomic/mod.rs +++ b/crates/nodes/src/atomic/mod.rs @@ -37,8 +37,6 @@ use direction::direction; pub const ATOMIC: &str = "Atomic nodes"; pub const GRAPH_ITEMS: &str = "Graph items"; -pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"]; -pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; pub use levels::levels_fn; pub use normal::height_to_normal; diff --git a/crates/nodes/src/atomic/output.rs b/crates/nodes/src/atomic/output.rs index 775d8201..62202a23 100644 --- a/crates/nodes/src/atomic/output.rs +++ b/crates/nodes/src/atomic/output.rs @@ -1,5 +1,5 @@ +use super::GRAPH_ITEMS; use super::dot::passthrough; -use super::{GRAPH_ITEMS, USAGES}; use crate::{NodeDefinition, PortKind, node}; use materialcraft_image::{Image, Kind}; @@ -9,7 +9,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .any_in("input", "Input") .text("identifier", "Identifier", "output") - .choice("usage", "Usage", USAGES, 0) + .component_usage(0) .cook(passthrough) } diff --git a/crates/nodes/src/function/operation.rs b/crates/nodes/src/function/operation.rs index 0b27e04a..b206d621 100644 --- a/crates/nodes/src/function/operation.rs +++ b/crates/nodes/src/function/operation.rs @@ -14,8 +14,8 @@ pub(crate) fn evaluate( context: &EvaluationContext<'_>, ) -> Result<Value, String> { let op = instruction.definition.id; - let first = || arguments.first().ok_or("missing first operand".to_string()); - let second = || arguments.get(1).ok_or("missing second operand".to_string()); + let first = || arguments.first().ok_or("missing first operand"); + let second = || arguments.get(1).ok_or("missing second operand"); let name = || match &instruction.value { Some(Value::Text(name)) => Ok(name.as_str()), _ => Err("variable name must be a string".to_string()), @@ -26,22 +26,26 @@ pub(crate) fn evaluate( if value_type::type_code(&value) != instruction.type_code { return Err("constant has the wrong type".into()); } + return Ok(value); } + if op.starts_with("get_") { let name = name()?; let value = match name { "$pos" => Value::Float2(context.position), "$size" => Value::Float2(context.size), "$sizelog2" => Value::Float2(context.size.map(f32::log2)), - _ => variables.get(name).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?, + _ => variables.get(name).or_else(|| context.variables.get(name)).cloned().ok_or_else(|| format!("undefined variable `{name}`"))?, }; if value_type::type_code(&value) != instruction.type_code { return Err(format!("variable `{name}` has the wrong type for {op}")); } + return Ok(value); } + if op.starts_with("to") || op.contains("vector") || op.contains("swizzle") { return super::vector::evaluate(op, arguments, instruction.value.as_ref()); } @@ -53,11 +57,15 @@ pub(crate) fn evaluate( if name.is_empty() || name.starts_with('$') { return Err("use a nonempty user variable name".into()); } + let value = first()?.clone(); variables.insert(name.to_string(), value.clone()); value } - "isdefined" => Value::Bool(variables.contains_key(name()?) || matches!(name()?, "$pos" | "$size" | "$sizelog2")), + "isdefined" => { + let name = name()?; + Value::Bool(variables.contains_key(name) || context.variables.contains_key(name) || matches!(name, "$pos" | "$size" | "$sizelog2")) + } "and" => Value::Bool(boolean(first()?)? && boolean(second()?)?), "or" => Value::Bool(boolean(first()?)? || boolean(second()?)?), "not" => Value::Bool(!boolean(first()?)?), diff --git a/crates/nodes/src/function/processor.rs b/crates/nodes/src/function/processor.rs index 3b25818a..ee07720c 100644 --- a/crates/nodes/src/function/processor.rs +++ b/crates/nodes/src/function/processor.rs @@ -31,6 +31,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { let program = compile(graph, context.seed)?; 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 channels = kind.channels(); let mut data = vec![0.0; width as usize * height as usize * channels]; @@ -44,7 +45,7 @@ pub(crate) fn pixel_processor(context: &CookContext) -> CookResult { variables: context.vars, }; - let result = pixel(program.evaluate(&evaluation, state)?, gray)?; + let result = pixel(program.evaluate_pixel(&evaluation, state)?, gray)?; target.copy_from_slice(result.get(..channels).ok_or("invalid output channels")?); } Ok(()) diff --git a/crates/nodes/src/function/program.rs b/crates/nodes/src/function/program.rs index 0ee75a58..f9fffe9f 100644 --- a/crates/nodes/src/function/program.rs +++ b/crates/nodes/src/function/program.rs @@ -20,23 +20,35 @@ impl Program { } fn instruction(&self, index: usize) -> Result<&Instruction, String> { - self.instructions.get(index).ok_or("invalid function instruction".into()) + self.instructions.get(index).ok_or_else(|| "invalid function instruction".into()) } fn input(&self, index: usize, slot: usize) -> Result<usize, String> { - self.instruction(index)?.inputs.get(slot).copied().ok_or("missing function input".into()) + self.instruction(index)?.inputs.get(slot).copied().ok_or_else(|| "missing function input".into()) } pub fn evaluate(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> { + state.variables.clone_from(context.variables); + self.run(context, state) + } + + // Pixel assignments are local; only the general evaluator exports the complete environment + pub(super) fn evaluate_pixel(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> { + state.variables.clear(); + self.run(context, state) + } + + fn run(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> { use EvaluationStep::*; + state.steps.clear(); state.values.clear(); state.registers.clear(); state.registers.resize(self.instructions.len(), None); - state.variables.clone_from(context.variables); state.random = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32); state.steps.push(Enter(self.output)); let mut remaining_steps = MAX_EVALUATION_STEPS; + while let Some(step) = state.steps.pop() { remaining_steps = remaining_steps.checked_sub(1).ok_or("function exceeded its execution budget; check loop termination")?; match step { @@ -71,17 +83,20 @@ impl Program { let arguments = state.values.get(base..).ok_or("invalid function operands")?; let result = operation::evaluate(instruction, arguments, &mut state.variables, &mut state.random, context) .map_err(|error| format!("{} ({}): {error}", instruction.definition.label, instruction.id))?; + state.values.truncate(base); if instruction.pure && let Some(register) = state.registers.get_mut(index) { *register = Some(result.clone()); } + state.values.push(result); } Branch(index) => { let condition = state.values.pop().ok_or("missing branch condition")?; let slot = if value_type::boolean(&condition)? { 1 } else { 2 }; + state.steps.push(Enter(self.input(index, slot)?)); } Sequence(index) => { @@ -116,6 +131,7 @@ impl Program { if value_type::type_code(&result) != expected { return Err(format!("function returned {}, expected native type {expected}", result.type_name())); } + Ok(result) } } diff --git a/crates/nodes/src/function/tests.rs b/crates/nodes/src/function/tests.rs index 6793d58c..7e4756be 100644 --- a/crates/nodes/src/function/tests.rs +++ b/crates/nodes/src/function/tests.rs @@ -162,3 +162,51 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() { graph.output = Some(previous); assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0)); } + +#[test] +fn pixel_assignments_are_local_and_match_exported_evaluation() { + let mut graph = FunctionGraph::default(); + let current = graph.add("get_float1", &[], Some(Value::Text("counter".into()))); + let one = graph.add_constant(Value::Float(1.0)); + let next = graph.add("add", &[current, one], None); + let assign = graph.add("set", &[next], Some(Value::Text("counter".into()))); + let get = graph.add("get_float1", &[], Some(Value::Text("counter".into()))); + graph.output = Some(graph.add("sequence", &[assign, get], None)); + let program = compile(&graph, 7).unwrap(); + let mut pixel_state = EvaluationState::default(); + for initial in [3.0, 10.0, -2.0] { + let variables = BTreeMap::from([("counter".into(), Value::Float(initial)), ("untouched".into(), Value::Text("keep".into()))]); + let context = EvaluationContext { position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables }; + let mut exported = EvaluationState::default(); + let expected = program.evaluate(&context, &mut exported).unwrap(); + for _ in 0..2 { + assert_eq!(program.evaluate_pixel(&context, &mut pixel_state).unwrap(), expected); + } + assert_eq!(expected, Value::Float(initial + 1.0)); + assert_eq!(variables["counter"], Value::Float(initial)); + assert_eq!(exported.variables()["counter"], expected); + assert_eq!(exported.variables()["untouched"], variables["untouched"]); + } + + let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap(); + let context = EvaluationContext { 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()); +} + +#[test] +fn pixel_random_seed_and_defined_variables_match_general_evaluation() { + let mut graph = FunctionGraph::default(); + let maximum = graph.add_constant(Value::Float(1.0)); + let random = graph.add("rand", &[maximum], None); + let defined = graph.add("isdefined", &[], Some(Value::Text("known".into()))); + let zero = graph.add_constant(Value::Float(0.0)); + graph.output = Some(graph.add("ifelse", &[defined, random, zero], None)); + let program = compile(&graph, 7).unwrap(); + let mut state = EvaluationState::default(); + for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] { + let context = EvaluationContext { 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); + } +} diff --git a/crates/nodes/src/node_definition_builder.rs b/crates/nodes/src/node_definition_builder.rs index 52697c4b..f53a264e 100644 --- a/crates/nodes/src/node_definition_builder.rs +++ b/crates/nodes/src/node_definition_builder.rs @@ -1,5 +1,5 @@ use crate::{Cook, CookContext, CookResult, NodeDefinition, ParameterDefinition, PortDefinition, PortKind}; -use materialcraft_core::{Curve, FunctionGraph, Gradient, PatternGraph, Value}; +use materialcraft_core::{ComponentUsage, Curve, FunctionGraph, Gradient, PatternGraph, Value}; pub(crate) fn no_cook(_: &CookContext) -> CookResult { Err("this node is cooked by the graph evaluator".into()) @@ -120,6 +120,10 @@ impl NodeDefinitionBuilder { self } + pub fn component_usage(self, default: u32) -> NodeDefinitionBuilder { + self.choice("usage", "Component Usage", ComponentUsage::LABELS, default) + } + pub fn text(self, id: &'static str, label: &'static str, d: &str) -> NodeDefinitionBuilder { self.push(id, label, Value::Text(d.into()), 0.0, 0.0) } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 0229b1e2..a2fe2a08 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +materialcraft-core = { workspace = true } materialcraft-geom = { workspace = true } materialcraft-image = { workspace = true } rayon = { workspace = true } diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 634ed0d6..5ae587d4 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -32,16 +32,18 @@ impl Maps { pub fn from_usages<'a>(items: impl IntoIterator<Item = (&'a str, &'a Image)>) -> Maps { let mut m = Maps::default(); for (usage, img) in items { - let slot = match usage { - "baseColor" => &mut m.base_color, - "normal" => &mut m.normal, - "roughness" => &mut m.roughness, - "metallic" => &mut m.metallic, - "height" => &mut m.height, - "ambientOcclusion" => &mut m.ao, - "emissive" => &mut m.emissive, - "opacity" => &mut m.opacity, - _ => continue, + use materialcraft_core::MaterialChannel; + let Some(channel) = MaterialChannel::from_id(usage) else { continue }; + + let slot = match channel { + MaterialChannel::BaseColor => &mut m.base_color, + MaterialChannel::Normal => &mut m.normal, + MaterialChannel::Roughness => &mut m.roughness, + MaterialChannel::Metallic => &mut m.metallic, + MaterialChannel::Height => &mut m.height, + MaterialChannel::AmbientOcclusion => &mut m.ao, + MaterialChannel::Emissive => &mut m.emissive, + MaterialChannel::Opacity => &mut m.opacity, }; if slot.is_none() { *slot = Some(img.clone()); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2a0b8f66..2d92d217 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -240,20 +240,25 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: } "ui.inspect" => { let rect = |r: egui::Rect| json!([r.min.x, r.min.y, r.width(), r.height()]); + let target = crate::graph::editor_target::EditorTarget::resolve(app); + let (view, nodes, ports) = (app.graph.view, &app.graph.rects, &app.graph.ports); ok(json!({ "state": app.ui, - "graphView": rect(app.graph.view), + "graphView": rect(view), "selection": app.session.selection, "inspectedNode": app.graph.inspected_node, - "subgraph": app.pattern_editor.as_ref().filter(|_| crate::pattern::active(app)) - .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})) - .or_else(|| app.function_editor.as_ref().filter(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_))) - .map(|editor| json!({"kind": "function", "graph": app.session.graph, "selection": editor.selection, "inspectedNode": editor.inspected_node}))), + "subgraph": match target { + crate::graph::editor_target::EditorTarget::Function => app.function_editor.as_ref() + .map(|editor| json!({"kind": "function", "graph": app.session.graph, "node": editor.node, "target": editor.command_target(), "selection": editor.selection, "inspectedNode": editor.inspected_node})), + crate::graph::editor_target::EditorTarget::Pattern => app.pattern_editor.as_ref() + .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})), + crate::graph::editor_target::EditorTarget::Material => None, + }, "annotationSelection": app.session.annotation_selection, "frames": app.graph.frames.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), "comments": app.graph.comments.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(), - "nodes": app.graph.rects.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(), - "ports": app.graph.ports.iter().map(|port| json!({ + "nodes": nodes.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(), + "ports": ports.iter().map(|port| json!({ "node": port.node.0, "port": port.port, "label": port.label, diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index bab9167f..f2828a94 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -3,13 +3,13 @@ use std::sync::mpsc::{Receiver, TryRecvError}; -use materialcraft_engine::eval::Cooked; +use materialcraft_engine::PreviewCook; use crate::MaterialCraftApp; #[derive(Default)] pub struct Cooker { - rx: Option<Receiver<Cooked>>, + rx: Option<Receiver<PreviewCook>>, /// Stops the running cook between nodes once its result is stale. #[cfg(not(target_arch = "wasm32"))] cancel: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>, @@ -28,11 +28,11 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(rx) = &app.cooker.rx { match rx.try_recv() { Ok(c) => { - if c.cancelled { + if c.cancelled() { // A stopped cook is partial: keep the previous results and cook again. app.session.dirty = true; } else if !app.session.dirty { - app.session.cooked = c; + app.session.accept_preview(c); } app.cooker.rx = None; app.cooker.started = None; @@ -78,6 +78,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { s.dirty = false; let pkg = s.pkg.clone(); let (gi, max) = (s.graph, s.preview_size); + let materials = s.material_preview.graphs(); let cache = s.cache.clone(); let dec = s.resource_decoder(); let (tx, rx) = std::sync::mpsc::channel(); @@ -88,7 +89,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let mut opts = Options::new(&dec); opts.max_size = max; opts.cancel = Some(&thread_flag); - let cooked = materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache); + let cooked = PreviewCook::run(&pkg, gi, &materials, &opts, &cache); let _ = tx.send(cooked); }); match spawned { diff --git a/crates/ui-egui/src/cook_cancellation.test.rs b/crates/ui-egui/src/cook_cancellation.test.rs index d4f7c692..cb4ab3db 100644 --- a/crates/ui-egui/src/cook_cancellation.test.rs +++ b/crates/ui-egui/src/cook_cancellation.test.rs @@ -1,11 +1,12 @@ use super::*; +use materialcraft_engine::eval::Cooked; use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, mpsc, }; -fn waiting() -> (MaterialCraftApp, mpsc::Sender<Cooked>, Arc<AtomicBool>) { +fn waiting() -> (MaterialCraftApp, mpsc::Sender<PreviewCook>, Arc<AtomicBool>) { let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); app.session.cook(); app.session.cooked.ms = 123.0; @@ -26,7 +27,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() { assert!(flag.load(Ordering::Relaxed)); assert!(Arc::ptr_eq(app.cooker.cancel.as_ref().unwrap(), &flag)); } - tx.send(Cooked { cancelled: true, ..Default::default() }).unwrap(); + tx.send(PreviewCook { cooked: Cooked { cancelled: true, ..Default::default() }, ..Default::default() }).unwrap(); drive(&mut app, &egui::Context::default()); assert!(!app.session.dirty, "latest snapshot should start once the worker ends"); assert_eq!(app.session.cooked.ms, 123.0, "partial results replaced the display"); @@ -35,7 +36,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() { #[test] fn ready_results_are_discarded_when_an_edit_is_pending() { let (mut app, tx, _) = waiting(); - tx.send(Cooked { ms: 7.0, ..Default::default() }).unwrap(); + tx.send(PreviewCook { cooked: Cooked { ms: 7.0, ..Default::default() }, ..Default::default() }).unwrap(); app.session.dirty = true; drive(&mut app, &egui::Context::default()); assert_eq!(app.session.cooked.ms, 123.0); diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 8c565f60..1d22730f 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -1,4 +1,4 @@ -//! The package tree, its graphs, named outputs and resources +//! The package tree, its graphs, inputs, outputs and resources use egui::{RichText, Ui}; @@ -36,17 +36,29 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong)); let mut open: Option<usize> = None; let mut action: Option<(&str, usize)> = None; - let mut output = None; + let mut selected_node = None; + let mut assignment = None; for (index, graph) in app.session.pkg.graphs.iter().enumerate() { let active = index == app.session.graph; let function = graph.function.is_some(); let mut header = |ui: &mut Ui| { let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE }; let response = tree_row::show(ui, &graph.name, symbol, active); + if !function { + response.interact(egui::Sense::drag()).dnd_set_drag_payload(crate::graph_drag_payload::GraphDragPayload { name: graph.name.clone() }); + } if response.clicked() { open = Some(index); } response.context_menu(|ui| { + if !function { + for (label, command) in [("View outputs in 3D view", "view3d"), ("Reset and view outputs in 3D view", "reset3d")] { + if ui.button(tr(label)).clicked() { + action = Some((command, index)); + ui.close(); + } + } + } for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { if ui.button(tr(label)).clicked() { action = Some((command, index)); @@ -66,15 +78,21 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let id = ui.make_persistent_id(("graph", index, &graph.name)); egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true).show_header(ui, header).body(|ui| { - ui.indent("outputs", |ui| { - for node in graph.nodes.iter().filter(|node| node.def == "output") { + ui.indent("graph-ports", |ui| { + for node in graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")) { ui.push_id(node.id, |ui| { - let name = materialcraft_engine::eval::identifier(node); + let name = crate::graph::node_label(node); let selected = active && app.session.selection.contains(&node.id); - let response = tree_row::show(ui, &name, icon::IMAGE, selected); + let symbol = if node.def == "input_value" { icon::FUNCTION } else { icon::IMAGE }; + let response = tree_row::show(ui, &name, symbol, selected); + response.context_menu(|ui| { + if let Some(parameters) = crate::material_preview_menu::show(ui, &app.session, index, node.id) { + assignment = Some(parameters); + } + }); if response.clicked() || response.double_clicked() { - output = Some((index, node.id, response.double_clicked())); + selected_node = Some((index, node.id, response.double_clicked())); } }); } @@ -84,7 +102,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { if let Some(i) = open { app.run("graph.open", json!({"graph": i})); } - if let Some((index, node, preview)) = output { + if let Some((index, node, preview)) = selected_node { if index != app.session.graph && app.run("graph.open", json!({"graph": index})).is_none() { return; } @@ -101,7 +119,13 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } } + if let Some(parameters) = assignment { + app.run("view.3d.assign", parameters); + } match action { + Some((command @ ("view3d" | "reset3d"), graph)) => { + app.run("view.3d.outputs", json!({"graph": graph, "reset": command == "reset3d"})); + } Some(("open", i)) => { app.run("graph.open", json!({"graph": i})); } diff --git a/crates/ui-egui/src/function/actions.rs b/crates/ui-egui/src/function/actions.rs new file mode 100644 index 00000000..0f55c9bd --- /dev/null +++ b/crates/ui-egui/src/function/actions.rs @@ -0,0 +1,49 @@ +use super::{FunctionEditor, FunctionTarget}; +use crate::MaterialCraftApp; + +pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, command: &str) -> Option<bool> { + let standalone = matches!(editor.target, FunctionTarget::Graph); + if standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { + return None; + } + if let Some(target) = editor.command_target() + && let Some(enabled) = materialcraft_engine::selection_commands::enabled_for( + &app.session, + &materialcraft_engine::SelectionTarget::Function(target), + &editor.selection, + command, + ) + { + return Some(enabled && editor.current(app).is_some()); + } + match command { + "edit.undo" | "edit.redo" | "edit.finish" | "graph.cook" | "ui.graph.snapToGrid" => None, + "ui.graph.previousPin" | "ui.graph.nextPin" | "graph.comment.add" | "graph.frame.add" | "graph.pin.add" if standalone => None, + command if command.starts_with("graph.") || command.starts_with("ui.graph.") || command.starts_with("edit.") => Some(false), + _ => None, + } +} + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { + app.function_editor.as_ref().and_then(|editor| editor_enabled(app, editor, command)) +} + +pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, command: &str) -> bool { + let Some(allowed) = editor_enabled(app, editor, command) else { return false }; + + if !allowed { + return true; + } + + let parameters = editor.selection_parameters(command); + crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters); + true +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + let Some(mut editor) = app.function_editor.take() else { return false }; + + let handled = invoke_editor(app, &mut editor, command); + app.function_editor = Some(editor); + handled +} diff --git a/crates/ui-egui/src/function/canvas.rs b/crates/ui-egui/src/function/canvas.rs index 8b39ce18..1ee7ba7e 100644 --- a/crates/ui-egui/src/function/canvas.rs +++ b/crates/ui-egui/src/function/canvas.rs @@ -1,572 +1,58 @@ -//! Function canvas edits are committed through engine commands - -use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::Value; -use materialcraft_engine::core::{FunctionGraph, FunctionNode}; -use materialcraft_engine::nodes::function::FUNCTIONS; +use super::{FunctionEditor, FunctionTarget}; +use crate::{MaterialCraftApp, graph::GraphCamera, i18n::tr}; +use egui::Ui; +use materialcraft_engine::FunctionEdit; use serde_json::json; -use crate::MaterialCraftApp; -use crate::graph::node_card; -use crate::i18n::tr; -use crate::theme::Tokens; +pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { + let Some(frame) = super::render::paint(app, editor, ui) else { return }; -use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; - -fn arity(op: &str) -> usize { - FUNCTIONS.iter().find(|o| o.id == op).map_or(0, |o| o.inputs.len()) -} - -fn label(op: &str) -> &'static str { - FUNCTIONS.iter().find(|o| o.id == op).map_or("?", |o| o.label) -} - -fn category_color(op: &str) -> Color32 { - match FUNCTIONS.iter().find(|o| o.id == op).map_or("", |o| o.category) { - "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), - "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), - "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), - "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), - "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), - } -} - -fn visible_inputs(node: &FunctionNode) -> usize { - let count = arity(&node.op); - crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1) -} - -fn node_rect(node: &FunctionNode, previews: bool) -> Rect { - node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough") -} - -fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { - node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough") -} - -fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { - node_card::port(bounds, 0, 1, true, node.op == "passthrough") -} - -pub(super) fn current(app: &MaterialCraftApp, editor: &FunctionEditor) -> Option<FunctionGraph> { - if let FunctionTarget::Graph(index) = editor.target { - return app.session.pkg.graphs.get(index)?.function.clone(); - } - - let node = app.session.graph().ok()?.node(editor.node?).ok()?; - let value = match &editor.target { - FunctionTarget::Graph(_) => return None, - FunctionTarget::Dynamic(parameter) => return node.functions.get(parameter).cloned(), - FunctionTarget::Parameter(parameter) => { - node.params.get(parameter).or_else(|| materialcraft_engine::nodes::find(&node.def)?.param(parameter).map(|parameter| ¶meter.default))? - } - FunctionTarget::Pattern { node: id, parameter } => { - let Value::PatternGraph(graph) = node.params.get("pattern")? else { return None }; - graph.nodes.iter().find(|node| node.id == *id)?.parameters.get(parameter)? - } - }; - - match value { - Value::Function(function) => Some((**function).clone()), - _ => None, - } -} - -pub(super) fn commit(app: &mut MaterialCraftApp, editor: &FunctionEditor, graph: &FunctionGraph) { - match &editor.target { - FunctionTarget::Graph(_) => { - app.run("graph.function.set", json!({"function": graph})); - } - FunctionTarget::Dynamic(parameter) => { - app.run("graph.node.function", json!({"id": editor.node.map(|node| node.0), "param": parameter, "function": graph})); - } - FunctionTarget::Parameter(parameter) => { - let value = Value::Function(Box::new(graph.clone())); - app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": parameter, "value": value})); - } - FunctionTarget::Pattern { node: id, parameter } => { - let Some(mut pattern) = - app.session.graph().ok().and_then(|graph| graph.node(editor.node?).ok()).and_then(|node| node.params.get("pattern")).cloned() - else { - return; - }; - - if let Value::PatternGraph(pattern) = &mut pattern - && let Some(node) = pattern.nodes.iter_mut().find(|node| node.id == *id) - { - node.parameters.insert(parameter.clone(), Value::Function(Box::new(graph.clone()))); - } - app.run("graph.node.param", json!({"id": editor.node.map(|node| node.0), "param": "pattern", "value": pattern})); - } - } -} - -/// Draw the editor window when one is open -pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { - if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph(_))) { - return; - } - - let Some(mut e) = app.function_editor.take() else { return }; - let Some(mut g) = current(app, &e) else { return }; - let title = app.session.graph().ok().and_then(|gr| gr.node(e.node?).ok()).map(crate::graph::node_label).unwrap_or_default(); - let mut open = true; - let mut changed = false; - let what = if e.target.parameter() == "function" { tr("Function").to_string() } else { format!("{} {}", tr("Function"), e.target.parameter()) }; - egui::Window::new(format!("{title} - {what}")) - .id(egui::Id::unique(("fn-editor", e.node, &e.target))) - .open(&mut open) - .default_size(vec2(760.0, 460.0)) - .resizable(true) - .show(ctx, |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label( - egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.")) - .size(11.0) - .color(tk.text_dim), - ); - }); - changed = canvas(app, &mut e, &mut g, ui); - }); - if changed { - commit(app, &e, &g); - } - if open { - app.function_editor = Some(e); - } -} - -pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) { - let index = app.session.graph; - let mut editor = - app.function_editor.take().filter(|editor| editor.target == FunctionTarget::Graph(index)).unwrap_or_else(|| FunctionEditor::standalone(index)); - let Some(mut graph) = current(app, &editor) else { return }; - - ui.horizontal(|ui| { - if ui.button(tr("Frame all")).clicked() { - editor.framed = false; - } - ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid")); - if graph.output.is_none() { - ui.label(tr("Set a node as the output")); - } - }); - if canvas(app, &mut editor, &mut graph, ui) { - commit(app, &editor, &graph); - } - app.function_editor = Some(editor); -} - -fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool) -> Rect { - let mut bounds = node_rect(node, app.ui.prefs.thumbnails); - if let Some(FunctionDrag::Node(d, delta)) = &editor.drag - && (*d == node.id || editor.selection.contains(&node.id)) - { - let position = materialcraft_engine::graph_grid::snap_position([node.pos[0] + delta.x, node.pos[1] + delta.y], snap); - bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); - } - if matches!(editor.target, FunctionTarget::Graph(_)) { - bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id))); - } - bounds -} - -fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool { - editor.selection.retain(|id| graph.node(*id).is_some()); - editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - let snap = app.ui.prefs.snap_to_grid; - let standalone = matches!(editor.target, FunctionTarget::Graph(_)); - let tokens = Tokens::get(ui.ctx()); - let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); - crate::widgets::name(&response, egui::Role::Canvas, "Function Graph"); - let painter = ui.painter_at(canvas_bounds); - painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); + let standalone = matches!(editor.target, FunctionTarget::Graph); + app.ui.frame_all = false; if standalone { - app.graph.view = canvas_bounds; - app.graph.rects.clear(); - app.graph.ports.clear(); - app.graph.wires.clear(); + app.ui.graph_camera = frame.camera.state(); + app.graph.frames = frame.frames.iter().map(|frame| (frame.id, frame.rect)).collect(); + app.graph.comments = frame.comments.clone(); } - - if !editor.framed || (standalone && app.ui.frame_all) { - if standalone { - app.ui.frame_all = false; - } - - editor.framed = true; - let mut destination = - graph.nodes.iter().map(|node| node_rect(node, app.ui.prefs.thumbnails)).fold(Rect::NOTHING, |combined, bounds| combined.union(bounds)); - if standalone && let Ok(document) = app.session.graph() { - for frame in &document.frames { - destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0))); - } - } - if destination.is_finite() && destination.width() > 0.0 { - let destination = destination.expand(30.0); - editor.zoom = (canvas_bounds.width() / destination.width()).min(canvas_bounds.height() / destination.height()).clamp(0.3, 1.2); - editor.pan = destination.center().to_vec2() - canvas_bounds.size() * 0.5 / editor.zoom; - } + if frame.clear_annotation { + app.run("graph.annotation.select", json!({})); } - - let to_screen = |position: Pos2, editor: &FunctionEditor| canvas_bounds.min + (position.to_vec2() - editor.pan) * editor.zoom; - let to_graph = |source: Pos2, editor: &FunctionEditor| ((source - canvas_bounds.min) / editor.zoom + editor.pan).to_pos2(); - let mut changed = false; - let pointer = ui.input(|input| input.pointer.hover_pos()); - - // Zoom and pan - if response.hovered() { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); - if scroll.abs() > 0.0 - && let Some(pointer_position) = pointer + for (id, value) in frame.values { + editor.edit(app, FunctionEdit::Value { id, value }, true); + } + for (id, response) in &frame.nodes { + if response.secondary_clicked() + && let Some(pointer) = response.interact_pointer_pos() { - let before = to_graph(pointer_position, editor); - editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5); - editor.pan = before.to_vec2() - (pointer_position - canvas_bounds.min) / editor.zoom; + editor.menu_at = frame.camera.to_graph(pointer); } - } - - let camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; - let document = standalone.then(|| app.session.graph().ok().cloned()).flatten(); - let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, graph, &camera)).unwrap_or_default(); - if standalone { - app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect(); - } - crate::graph::canvas::grid(&painter, &camera, canvas_bounds); - - // Wires - for node in &graph.nodes { - let bounds = preview_rect(app, editor, node, snap); - for (input_index, source_id) in node.inputs.iter().enumerate() { - if let Some(source) = source_id.and_then(|source| graph.node(source)) { - let source_position = to_screen(out_port(source, preview_rect(app, editor, source, snap)), editor); - let destination = to_screen(in_port(node, bounds, input_index), editor); - let control_offset = ((destination.x - source_position.x).abs() * 0.5).max(24.0); - painter.add(egui::epaint::CubicBezierShape::from_points_stroke( - [source_position, source_position + vec2(control_offset, 0.0), destination - vec2(control_offset, 0.0), destination], - false, - Color32::TRANSPARENT, - Stroke::new(2.0, Color32::from_gray(0xb4)), - )); - } - } - } - - // Nodes - let font = FontId::proportional((11.0 * editor.zoom).min(16.0)); - let mut remove: Option<u32> = None; - let mut set_output: Option<u32> = None; - let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new(); - let ids: Vec<u32> = graph.nodes.iter().map(|node| node.id).collect(); - for id in ids { - let Some(node_index) = graph.nodes.iter().position(|node| node.id == id) else { continue }; - - let node = &graph.nodes[node_index]; - let bounds = preview_rect(app, editor, node, snap); - let screen_rect = Rect::from_min_max(to_screen(bounds.min, editor), to_screen(bounds.max, editor)); - if standalone { - app.graph.rects.push((materialcraft_engine::core::NodeId(u64::from(id)), screen_rect)); - } - - let dot = node.op == "passthrough"; - let show_labels = crate::graph::port_label::visible(ui, screen_rect); - let is_output = graph.output == Some(id); - let selected = editor.selection.contains(&id); - let outline = if selected { - tokens.accent - } else if dot { - Color32::from_gray(0xb4) - } else { - Color32::from_gray(0x10) - }; - - if dot { - node_card::paint_dot(&painter, screen_rect, outline); - } else { - node_card::paint(&painter, screen_rect, editor.zoom, label(&node.op), category_color(&node.op)); - node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); - let body = node_card::body(screen_rect, editor.zoom); - if node.value.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); - } - if is_output { - let header = node_card::header(screen_rect, editor.zoom); - painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD); - } - } - - let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0); - let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value); - if let Some(definition) = materialcraft_engine::nodes::function::definition(&node.op) { - for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() { - let position = to_screen(in_port(node, bounds, input_index), editor); - painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); - if show_labels { - crate::graph::port_label::paint( - &painter, - position - vec2(10.0, 0.0), - Align2::RIGHT_CENTER, - port_label(identifier), - editor.zoom, - tokens.text_strong, - ); - } - ports.push((id, Some(input_index), position)); - } - } - - let output_position = to_screen(out_port(node, bounds), editor); - painter.circle(output_position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); - if show_labels { - crate::graph::port_label::paint( - &painter, - output_position + vec2(10.0, 0.0), - Align2::LEFT_CENTER, - port_label("output"), - editor.zoom, - tokens.text_strong, - ); - } - ports.push((id, None, output_position)); - - let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); - crate::widgets::name(&body, egui::Role::Button, label(&graph.nodes[node_index].op)); - - if !dot && node.value.is_some() { - let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); - child.set_clip_rect(content.intersect(canvas_bounds)); - if let Some(value) = graph.nodes[node_index].value.as_mut() { - changed |= crate::value_editor::show(&mut child, value); - } - } - - if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed())) || body.secondary_clicked() { - let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) }; - crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); - if standalone && app.session.annotation_selection.is_some() { - app.run("graph.annotation.select", json!({})); - } - } - - if body.drag_started() && editor.selection.contains(&id) && editor.drag.is_none() && !app.graph.is_dragging() { - editor.drag = Some(FunctionDrag::Node(id, Vec2::ZERO)); - } - - body.context_menu(|ui| { - changed |= super::context_menu::show(app, editor, graph, ui); + response.context_menu(|ui| { + super::context_menu::show(app, editor, ui); ui.separator(); - if ui.button(format!("{} {}", icon::STAR, tr("Set as output node"))).clicked() { - set_output = Some(id); - ui.close(); - } - if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() { - remove = Some(id); + if ui.button(format!("{} {}", egui_phosphor::regular::STAR, tr("Set as output node"))).clicked() { + editor.edit(app, FunctionEdit::Output { id: *id }, false); ui.close(); } }); } - - if let Some(id) = set_output { - graph.output = Some(id); - changed = true; - } - - if let Some(id) = remove { - graph.nodes.retain(|node| node.id != id); - for node in &mut graph.nodes { - for source in &mut node.inputs { - if *source == Some(id) { - *source = None; - } - } - } - if graph.output == Some(id) { - graph.output = None; - } - changed = true; - } - + let on_annotation = ui + .input(|input| input.pointer.hover_pos()) + .is_some_and(|pointer| frame.frames.iter().any(|frame| frame.contains(pointer)) || frame.comments.iter().any(|(_, rect)| rect.contains(pointer))); + super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry.rects, on_annotation); + frame.geometry.publish(&mut app.graph, frame.response.rect); if standalone { - app.graph.ports = ports - .iter() - .map(|(id, input, position)| { - let identifier = input - .and_then(|slot| { - let node = graph.node(*id)?; - materialcraft_engine::nodes::function::definition(&node.op)?.inputs.get(slot).copied() - }) - .unwrap_or(if input.is_some() { "input" } else { "output" }); - - crate::graph::PortHit { - node: materialcraft_engine::core::NodeId(u64::from(*id)), - port: input.map_or_else(|| "output".into(), |slot| slot.to_string()), - label: port_label(identifier).into(), - output: input.is_none(), - kind: materialcraft_engine::nodes::PortKind::Value, - pos: *position, - } - }) - .collect(); - app.ui.graph_camera.pan = [editor.pan.x, editor.pan.y]; - app.ui.graph_camera.zoom = editor.zoom; - } - - // Gestures: wires from output dots, panning - let near = |pointer_position: Pos2| { - ports - .iter() - .filter(|(id, _, position)| { - let dot = graph.node(*id).is_some_and(|node| node.op == "passthrough"); - let radius = if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }; - position.distance(pointer_position) < radius - }) - .min_by(|first, second| first.2.distance(pointer_position).total_cmp(&second.2.distance(pointer_position))) - .cloned() - }; - if response.drag_started_by(egui::PointerButton::Middle) || (response.drag_started() && ui.input(|input| input.modifiers.alt)) { - editor.drag = Some(FunctionDrag::Pan); - } else if ui.input(|input| input.pointer.primary_pressed()) - && editor.drag.is_none() - && !app.graph.is_dragging() - && let Some(pointer_position) = pointer - && canvas_bounds.contains(pointer_position) - && let Some((id, None, _)) = near(pointer_position) - { - editor.drag = Some(FunctionDrag::Wire(id)); - } - - let delta = ui.input(|input| input.pointer.delta()); - match &mut editor.drag { - Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom, - Some(FunctionDrag::Pan) => editor.pan -= delta / editor.zoom, - Some(FunctionDrag::Wire(id)) => { - if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|(node, source, _)| node == id && source.is_none())) { - painter.line_segment([source_id.2, pointer_position], Stroke::new(2.0, tokens.accent)); - } - } - None => {} - } - - if ui.input(|input| input.pointer.any_released()) { - match editor.drag.take() { - Some(FunctionDrag::Node(id, offset)) => { - if offset.length() > 0.5 { - for node in graph.nodes.iter_mut().filter(|node| node.id == id || editor.selection.contains(&node.id)) { - node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset.x, node.pos[1] + offset.y], snap); - } - changed = true; - } - } - Some(FunctionDrag::Wire(source_id)) => { - if let Some(pointer_position) = pointer - && let Some((destination_id, Some(slot), _)) = near(pointer_position) - && destination_id != source_id - && !reaches(graph, destination_id, source_id) - && let Some(node) = graph.nodes.iter_mut().find(|node| node.id == destination_id) - { - if node.inputs.len() <= slot { - node.inputs.resize(slot + 1, None); - } - node.inputs[slot] = Some(source_id); - changed = true; - } - } - _ => {} - } - } - - if response.clicked() { - crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers)); - } - - // Adding operations - if response.secondary_clicked() - && let Some(pointer_position) = pointer - { - editor.menu_at = to_graph(pointer_position, editor); - } - if response.hovered() - && ui.input(|input| input.key_pressed(egui::Key::Space)) - && let Some(pointer_position) = pointer - { - editor.menu_at = to_graph(pointer_position, editor); - egui::Popup::open_id(ui.ctx(), response.id.with("menu")); - } - response.context_menu(|ui| { - changed |= super::context_menu::show(app, editor, graph, ui); - }); - - if let Some(document) = &document { - let comments = crate::graph::annotation_canvas::comments(app, ui, document, &camera); - app.graph.comments = comments.clone(); - crate::graph::annotation_canvas::pins(app, ui, document, &camera); if editor.drag.is_none() { - crate::graph::annotation_input::handle(app, ui, &camera, &frame_hits, &comments); + let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom }; + crate::graph::annotation_input::handle(app, ui, &camera, &frame.frames, &frame.comments); if app.session.annotation_selection.is_some() { editor.selection.clear(); } } + app.ui.graph_camera = crate::state::GraphCamera { pan: editor.pan.into(), zoom: editor.zoom }; + app.session.selection = editor.selection.iter().map(|id| materialcraft_engine::core::NodeId(u64::from(*id))).collect(); + } else { + app.graph.frames.clear(); + app.graph.comments.clear(); } - editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.node(*id).is_some()); - changed -} - -// Wiring b into a is invalid when a already feeds b -fn reaches(g: &FunctionGraph, a: u32, b: u32) -> bool { - let mut stack = vec![b]; - let mut seen = std::collections::BTreeSet::new(); - while let Some(n) = stack.pop() { - if n == a { - return true; - } - if !seen.insert(n) { - continue; - } - if let Some(node) = g.node(n) { - stack.extend(node.inputs.iter().flatten()); - } - } - false -} - -pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { - if app.session.annotation_selection.is_some() || !app.session.graph().is_ok_and(|graph| graph.function.is_some()) { - return None; - } - super::selection::enabled(app.function_editor.as_ref()?, command) -} - -pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { - if enabled(app, command).is_none() { - return false; - } - let Some(mut editor) = app.function_editor.take() else { return false }; - if let Some(mut graph) = current(app, &editor) - && super::selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid) - { - commit(app, &editor, &graph); - } - app.function_editor = Some(editor); - true -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cycles_are_detected() { - let mut g = FunctionGraph::default(); - let a = g.add("get_float2", &[], Some(Value::Text("$pos".into()))); - let b = g.add("swizzle1", &[a], Some(Value::Int(0))); - // a feeds b: wiring b into a would loop - assert!(reaches(&g, a, b)); - assert!(!reaches(&g, b, a)); - assert_eq!(arity("add"), 2); - assert!(materialcraft_engine::nodes::function::default_value("const_float1").is_some()); - } + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); } diff --git a/crates/ui-egui/src/function/context_menu.rs b/crates/ui-egui/src/function/context_menu.rs index 1f8430d3..8a49ded0 100644 --- a/crates/ui-egui/src/function/context_menu.rs +++ b/crates/ui-egui/src/function/context_menu.rs @@ -1,32 +1,31 @@ -use super::{FunctionEditor, FunctionTarget, selection}; -use crate::{MaterialCraftApp, i18n::tr, menus}; +use super::{FunctionEditor, FunctionTarget}; +use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus}; use egui::Ui; -use materialcraft_engine::{ - core::{FunctionGraph, FunctionNode}, - nodes::function::{FUNCTIONS, default_value}, -}; +use materialcraft_engine::FunctionEdit; use serde_json::json; -pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, graph: &mut FunctionGraph, ui: &mut Ui) -> bool { - let mut changed = false; +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { + let Some(target) = editor.command_target() else { return }; + let mut add = None; - let standalone = matches!(editor.target, FunctionTarget::Graph(_)); + let standalone = matches!(editor.target, FunctionTarget::Graph); ui.set_min_width(290.0); ui.menu_button(tr("Add node"), |ui| { - let entries = FUNCTIONS.iter().filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, operation.category)); + let entries = target + .available_operations(&app.session) + .filter(|operation| operation.id != "passthrough") + .map(|operation| (operation.id, operation.label, operation.category)); add = crate::graph::add_node_menu::show(ui, entries); }); - if standalone { for (label, command, parameters) in [ ("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), ("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})), ("Add Navigation pin", "graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), ] { - if ui.button(tr(label)).clicked() { + if edit_menu::button(ui, label, command, true) { app.run(command, parameters); editor.selection.clear(); - ui.close(); } } } @@ -35,64 +34,24 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, grap ui.close(); } ui.separator(); - - if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() { + if edit_menu::button(ui, "Save package", "file.save", menus::enabled(app, "file.save")) { menus::invoke(app, ui.ctx(), "file.save"); - ui.close(); } - for (label, command) in [ - ("Paste", "edit.paste"), - ("Paste without link", "edit.pasteWithoutLinks"), - ("Select all", "edit.selectAll"), - ("Previous pin", "ui.graph.previousPin"), - ("Next pin", "ui.graph.nextPin"), - ("Copy selection", "edit.copy"), - ("Delete selection", "edit.delete"), - ("Delete and relink", "edit.deleteRelink"), - ("Duplicate selection", "edit.duplicate"), - ("Duplicate selection without link", "edit.duplicateWithoutLinks"), - ("Select upstream nodes", "graph.selectUpstream"), - ("Select downstream nodes", "graph.selectDownstream"), - ("Disable selection", "graph.node.disable"), - ] { - if command == "edit.copy" { - ui.separator(); - } - let annotation = standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink"); - let enabled = if annotation { true } else { selection::enabled(editor, command).unwrap_or_else(|| standalone && menus::enabled(app, command)) }; - let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { - button = button.shortcut_text(shortcut); - } - if ui.add_enabled(enabled, button).clicked() { - if annotation { - app.run(command, json!({})); - } else if command.starts_with("ui.") { - menus::invoke(app, ui.ctx(), command); - editor.pan = app.ui.graph_camera.pan.into(); - } else { - changed |= selection::run(editor, graph, command, app.ui.prefs.snap_to_grid); + if let Some(command) = + edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or_else(|| menus::enabled(app, command))) + && !super::actions::invoke_editor(app, editor, command) + { + app.run(command, json!({})); + } + if standalone { + for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] { + if edit_menu::button(ui, label, command, menus::enabled(app, command)) { + crate::graph::actions::invoke(app, command); + editor.set_camera(app.ui.graph_camera); } - ui.close(); } } - if let Some(operation) = add { - let id = graph.next_id(); - let inputs = FUNCTIONS.iter().find(|definition| definition.id == operation).map_or(0, |definition| definition.inputs.len()); - graph.nodes.push(FunctionNode { - id, - type_code: 0, - op: operation.into(), - inputs: vec![None; inputs], - value: default_value(operation), - pos: materialcraft_engine::graph_grid::snap_position([editor.menu_at.x, editor.menu_at.y], app.ui.prefs.snap_to_grid), - }); - editor.selection = vec![id]; - if graph.output.is_none() { - graph.output = Some(id); - } - changed = true; + editor.edit(app, FunctionEdit::Add { operation: operation.into(), at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); } - changed } diff --git a/crates/ui-egui/src/function/function_canvas.rs b/crates/ui-egui/src/function/function_canvas.rs new file mode 100644 index 00000000..16b60998 --- /dev/null +++ b/crates/ui-egui/src/function/function_canvas.rs @@ -0,0 +1,16 @@ +use super::function_port::FunctionPort; +use crate::graph::{GraphCamera, canvas_geometry::CanvasGeometry, frame_hit::FrameHit}; +use egui::{Rect, Response}; +use materialcraft_engine::core::Value; + +pub(super) struct FunctionCanvas { + pub response: Response, + pub camera: GraphCamera, + pub geometry: CanvasGeometry, + pub ports: Vec<FunctionPort>, + pub nodes: Vec<(u32, Response)>, + pub values: Vec<(u32, Value)>, + pub frames: Vec<FrameHit>, + pub comments: Vec<(u64, Rect)>, + pub clear_annotation: bool, +} diff --git a/crates/ui-egui/src/function/function_drag.rs b/crates/ui-egui/src/function/function_drag.rs index 4d38ae50..d8ee7cb6 100644 --- a/crates/ui-egui/src/function/function_drag.rs +++ b/crates/ui-egui/src/function/function_drag.rs @@ -3,5 +3,6 @@ use egui::Vec2; pub(super) enum FunctionDrag { Node(u32, Vec2), Wire(u32), - Pan, + Box { start: egui::Pos2 }, + Pan(egui::PointerButton), } diff --git a/crates/ui-egui/src/function/function_editor.rs b/crates/ui-egui/src/function/function_editor.rs index fe8f39a8..b6d8eeee 100644 --- a/crates/ui-egui/src/function/function_editor.rs +++ b/crates/ui-egui/src/function/function_editor.rs @@ -1,29 +1,45 @@ +use crate::MaterialCraftApp; use egui::{Pos2, Vec2, vec2}; +use materialcraft_engine::core::FunctionGraph; use materialcraft_engine::core::NodeId; +use serde_json::json; use super::{FunctionDrag, FunctionTarget}; pub struct FunctionEditor { pub node: Option<NodeId>, + pub graph: usize, pub(crate) selection: Vec<u32>, pub(crate) inspected_node: Option<u32>, - pub(super) clipboard: Vec<materialcraft_engine::core::FunctionNode>, pub target: FunctionTarget, pub(super) pan: Vec2, pub(super) zoom: f32, pub(super) drag: Option<FunctionDrag>, pub(super) menu_at: Pos2, - pub(super) framed: bool, + pub(crate) framed: bool, } impl FunctionEditor { pub fn standalone(graph: usize) -> Self { + Self::with_target(graph, None, FunctionTarget::Graph) + } + + pub(crate) fn set_camera(&mut self, camera: crate::state::GraphCamera) { + self.pan = camera.pan.into(); + self.zoom = camera.zoom; + } + + pub fn new(graph: usize, node: NodeId, target: FunctionTarget) -> Self { + Self::with_target(graph, Some(node), target) + } + + fn with_target(graph: usize, node: Option<NodeId>, target: FunctionTarget) -> Self { Self { - node: None, - target: FunctionTarget::Graph(graph), + graph, + node, + target, selection: Vec::new(), inspected_node: None, - clipboard: Vec::new(), pan: vec2(-40.0, -40.0), zoom: 1.0, drag: None, @@ -32,18 +48,43 @@ impl FunctionEditor { } } - pub fn new(node: NodeId, target: FunctionTarget) -> FunctionEditor { - FunctionEditor { - node: Some(node), - selection: Vec::new(), - inspected_node: None, - clipboard: Vec::new(), - target, - pan: vec2(-40.0, -40.0), - zoom: 1.0, - drag: None, - menu_at: Pos2::ZERO, - framed: false, + pub(crate) fn current<'a>(&self, app: &'a MaterialCraftApp) -> Option<&'a FunctionGraph> { + if self.graph != app.session.graph { + return None; + } + + self.command_target()?.current(&app.session).ok() + } + + pub(crate) fn command_target(&self) -> Option<materialcraft_engine::FunctionGraphTarget> { + use materialcraft_engine::FunctionGraphTarget; + Some(match &self.target { + FunctionTarget::Graph => FunctionGraphTarget::Graph, + FunctionTarget::Parameter(parameter) => FunctionGraphTarget::Parameter { node: self.node?, parameter: parameter.clone() }, + FunctionTarget::Dynamic(parameter) => FunctionGraphTarget::Dynamic { node: self.node?, parameter: parameter.clone() }, + FunctionTarget::Pattern { node, parameter } => FunctionGraphTarget::Pattern { owner: self.node?, node: *node, parameter: parameter.clone() }, + }) + } + + pub(crate) fn edit(&mut self, app: &mut MaterialCraftApp, edit: materialcraft_engine::FunctionEdit, merge: bool) { + if self.current(app).is_none() { + return; + } + let Some(target) = self.command_target() else { return }; + + if let Some(result) = app.run("graph.function.edit", json!({"target": target, "edit": edit, "merge": merge})) + && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) + { + self.selection = vec![id]; + if self.target == FunctionTarget::Graph { + app.session.selection = vec![NodeId(u64::from(id))]; + app.session.annotation_selection = None; + } } } + + pub(crate) fn selection_parameters(&self, command: &str) -> serde_json::Value { + let selection = if matches!(command, "edit.selectAll" | "edit.selectNone") { &[][..] } else { self.selection.as_slice() }; + json!({"graph": self.graph, "function": self.command_target(), "ids": selection, "at": [self.menu_at.x, self.menu_at.y]}) + } } diff --git a/crates/ui-egui/src/function/function_port.rs b/crates/ui-egui/src/function/function_port.rs new file mode 100644 index 00000000..84da44c4 --- /dev/null +++ b/crates/ui-egui/src/function/function_port.rs @@ -0,0 +1,9 @@ +use egui::Pos2; + +pub(super) struct FunctionPort { + pub node: u32, + pub slot: Option<usize>, + pub position: Pos2, + pub radius: f32, + pub label: &'static str, +} diff --git a/crates/ui-egui/src/function/function_target.rs b/crates/ui-egui/src/function/function_target.rs index 4f83a487..e20523b5 100644 --- a/crates/ui-egui/src/function/function_target.rs +++ b/crates/ui-egui/src/function/function_target.rs @@ -1,6 +1,6 @@ #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum FunctionTarget { - Graph(usize), + Graph, Parameter(String), Dynamic(String), Pattern { node: u32, parameter: String }, @@ -9,7 +9,7 @@ pub enum FunctionTarget { impl FunctionTarget { pub fn parameter(&self) -> &str { match self { - Self::Graph(_) => "", + Self::Graph => "", Self::Parameter(parameter) | Self::Dynamic(parameter) | Self::Pattern { parameter, .. } => parameter, } } diff --git a/crates/ui-egui/src/function/geometry.rs b/crates/ui-egui/src/function/geometry.rs new file mode 100644 index 00000000..605c186f --- /dev/null +++ b/crates/ui-egui/src/function/geometry.rs @@ -0,0 +1,51 @@ +use super::{FunctionDrag, FunctionEditor, FunctionTarget}; +use crate::{MaterialCraftApp, graph::node_card}; +use egui::{Color32, Pos2, Rect, vec2}; +use materialcraft_engine::core::FunctionNode; + +pub(super) fn arity(op: &str) -> usize { + materialcraft_engine::nodes::function::definition(op).map_or(0, |o| o.inputs.len()) +} + +pub(super) fn category_color(category: &str) -> Color32 { + match category { + "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), + "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), + "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), + "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), + "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), + "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), + _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), + } +} + +pub(super) fn visible_inputs(node: &FunctionNode) -> usize { + let count = arity(&node.op); + crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1) +} + +pub(super) fn node_rect(node: &FunctionNode, previews: bool) -> Rect { + node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough") +} + +pub(super) fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { + node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough") +} + +pub(super) fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { + node_card::port(bounds, 0, 1, true, node.op == "passthrough") +} + +pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool, selected: bool) -> Rect { + let mut bounds = node_rect(node, app.ui.prefs.thumbnails); + if let Some(FunctionDrag::Node(d, delta)) = &editor.drag + && (*d == node.id || selected) + { + let position = materialcraft_engine::graph_grid::translate(node.pos, (*delta).into(), snap); + bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); + } + if matches!(editor.target, FunctionTarget::Graph) { + bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id))); + } + bounds +} diff --git a/crates/ui-egui/src/function/input.rs b/crates/ui-egui/src/function/input.rs new file mode 100644 index 00000000..0eb41449 --- /dev/null +++ b/crates/ui-egui/src/function/input.rs @@ -0,0 +1,125 @@ +use super::function_port::FunctionPort; +use super::{FunctionDrag, FunctionEditor}; +use crate::{MaterialCraftApp, graph::GraphCamera, theme::Tokens}; +use egui::{Pos2, Rect, Stroke, Ui}; +use materialcraft_engine::{FunctionEdit, core::NodeId}; + +pub(super) fn handle( + app: &mut MaterialCraftApp, + editor: &mut FunctionEditor, + ui: &mut Ui, + response: &egui::Response, + ports: &[FunctionPort], + rectangles: &[(NodeId, Rect)], + on_annotation: bool, +) { + let canvas_bounds = response.rect; + let pointer = ui.input(|input| input.pointer.hover_pos()); + let painter = ui.painter_at(canvas_bounds); + let tokens = Tokens::get(ui.ctx()); + let snap = app.ui.prefs.snap_to_grid; + if crate::graph::gesture::cancelled(ui) { + editor.drag = None; + return; + } + // Gestures: wires from output dots, panning + let near = |pointer: Pos2| crate::graph::port_hit::nearest_by(ports, pointer, |port| (port.position, port.radius)).map(|port| (port.node, port.slot)); + if editor.drag.is_none() && GraphCamera::pan_started(ui, canvas_bounds) { + editor.drag = Some(FunctionDrag::Pan(crate::graph::gesture::pan_button(ui))); + } else if ui.input(|input| input.pointer.primary_pressed()) + && editor.drag.is_none() + && !app.graph.is_dragging() + && let Some(pointer_position) = pointer + && ui.rect_contains_pointer(canvas_bounds) + && let Some((id, None)) = near(pointer_position) + { + editor.drag = Some(FunctionDrag::Wire(id)); + } + + if editor.drag.is_none() + && !app.graph.is_dragging() + && response.hovered() + && ui.input(|input| input.pointer.primary_pressed()) + && let Some(start) = pointer + && !on_annotation + { + if matches!(editor.target, super::FunctionTarget::Graph) && app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", serde_json::json!({})); + } + editor.drag = Some(FunctionDrag::Box { start }); + } + + let delta = ui.input(|input| input.pointer.delta()); + match &mut editor.drag { + Some(FunctionDrag::Node(_, offset)) => *offset += delta / editor.zoom, + Some(FunctionDrag::Pan(_)) => editor.pan -= delta / editor.zoom, + Some(FunctionDrag::Wire(id)) => { + if let (Some(pointer_position), Some(source_id)) = (pointer, ports.iter().find(|port| port.node == *id && port.slot.is_none())) { + crate::graph::wire_geometry::bezier(&painter, source_id.position, pointer_position, Stroke::new(2.0, tokens.accent)); + } + } + Some(FunctionDrag::Box { start }) => { + if let Some(pointer) = pointer { + crate::graph::node_selection::paint_box(&painter, *start, pointer, tokens.accent); + } + } + None => {} + } + + let owner = match editor.drag { + Some(FunctionDrag::Pan(button)) => button, + _ => egui::PointerButton::Primary, + }; + if crate::graph::gesture::finished(ui, owner) { + match editor.drag.take() { + Some(FunctionDrag::Node(id, offset)) => { + if offset.length() > 0.5 { + let mut ids = editor.selection.clone(); + if !ids.contains(&id) { + ids.push(id); + } + editor.edit(app, FunctionEdit::Move { ids, by: offset.into(), snap }, false); + } + } + Some(FunctionDrag::Box { start }) => { + if let Some(pointer) = pointer { + let nodes = rectangles.iter().map(|(id, bounds)| (id.0 as u32, *bounds)); + crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, ui.input(|input| input.modifiers)); + } + } + Some(FunctionDrag::Wire(from)) => { + if let Some(pointer) = pointer + && let Some((to, Some(input))) = near(pointer) + && from != to + { + editor.edit(app, FunctionEdit::Connect { from, to, input }, false); + } + } + _ => {} + } + } + + if response.clicked() && !ui.input(|input| input.modifiers.alt) { + crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers)); + } + + let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; + + // Adding operations + if response.secondary_clicked() + && let Some(pointer_position) = pointer + { + editor.menu_at = camera.to_graph(pointer_position); + } + if response.hovered() + && !ui.ctx().egui_wants_keyboard_input() + && ui.input(|input| input.key_pressed(egui::Key::Space)) + && let Some(pointer_position) = pointer + { + editor.menu_at = camera.to_graph(pointer_position); + egui::Popup::open_id(ui.ctx(), response.id.with("menu")); + } + response.context_menu(|ui| { + super::context_menu::show(app, editor, ui); + }); +} diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs index b41437bc..56ea6a75 100644 --- a/crates/ui-egui/src/function/library.rs +++ b/crates/ui-egui/src/function/library.rs @@ -1,24 +1,21 @@ use crate::{MaterialCraftApp, i18n::tr}; use egui::Ui; -use materialcraft_engine::nodes::function::{FUNCTIONS, default_value}; -use serde_json::json; +use materialcraft_engine::FunctionEdit; pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) else { return }; + + let operations = target.available_operations(&app.session); ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions"))); let search = app.ui.library_search.to_ascii_lowercase(); egui::ScrollArea::vertical().show(ui, |ui| { - for definition in FUNCTIONS.iter().filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { + for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { if ui.selectable_label(false, tr(definition.label)).double_clicked() - && let Some(mut graph) = app.session.graph().ok().and_then(|graph| graph.function.clone()) + && let Some(mut editor) = app.function_editor.take() { - let id = graph.add(definition.id, &[], default_value(definition.id)); - if graph.output.is_none() { - graph.output = Some(id); - } - if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) { - node.pos = materialcraft_engine::graph_grid::snap_position(node.pos, app.ui.prefs.snap_to_grid); - } - app.run("graph.function.set", json!({"function": graph})); + let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]); + editor.edit(app, FunctionEdit::Add { operation: definition.id.into(), at, snap: app.ui.prefs.snap_to_grid }, false); + app.function_editor = Some(editor); } } }); diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs index b8a0181e..136b0db8 100644 --- a/crates/ui-egui/src/function/mod.rs +++ b/crates/ui-egui/src/function/mod.rs @@ -6,9 +6,18 @@ mod function_target; pub(crate) mod library; mod port_label; pub(crate) mod properties; -mod selection; -pub(crate) use canvas::{enabled, invoke, show, show_graph}; +pub(crate) use actions::{enabled, invoke}; use function_drag::FunctionDrag; pub use function_editor::FunctionEditor; pub use function_target::FunctionTarget; +pub(crate) use panel::show_graph; + +mod actions; +mod geometry; +mod input; +mod panel; + +mod function_canvas; +mod function_port; +mod render; diff --git a/crates/ui-egui/src/function/panel.rs b/crates/ui-egui/src/function/panel.rs new file mode 100644 index 00000000..a4334b1c --- /dev/null +++ b/crates/ui-egui/src/function/panel.rs @@ -0,0 +1,13 @@ +use super::{FunctionEditor, FunctionTarget, canvas::canvas}; +use crate::MaterialCraftApp; +use egui::Ui; + +pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) { + let index = app.session.graph; + let mut editor = app.function_editor.take().filter(|editor| editor.graph == index).unwrap_or_else(|| FunctionEditor::standalone(index)); + if editor.target == FunctionTarget::Graph { + editor.selection = app.session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(); + } + canvas(app, &mut editor, ui); + app.function_editor = Some(editor); +} diff --git a/crates/ui-egui/src/function/properties.rs b/crates/ui-egui/src/function/properties.rs index 7a6eea13..52ab4ae0 100644 --- a/crates/ui-egui/src/function/properties.rs +++ b/crates/ui-egui/src/function/properties.rs @@ -1,16 +1,11 @@ use egui::Ui; use materialcraft_engine::{core::FunctionGraph, nodes::function::definition}; -use super::{FunctionTarget, canvas}; use crate::{MaterialCraftApp, graph::node_selection, i18n::tr}; fn current(app: &MaterialCraftApp) -> Option<(&FunctionGraph, u32)> { let editor = app.function_editor.as_ref()?; - if editor.target != FunctionTarget::Graph(app.session.graph) { - return None; - } - - let graph = app.session.graph().ok()?.function.as_ref()?; + let graph = editor.current(app)?; let id = node_selection::inspected(&editor.selection, editor.inspected_node)?; graph.node(id)?; Some((graph, id)) @@ -25,8 +20,8 @@ pub(crate) fn title(app: &MaterialCraftApp) -> Option<String> { pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { let Some((graph, id)) = current(app) else { return false }; - let mut graph = graph.clone(); - let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) else { return false }; + + let Some(node) = graph.node(id) else { return false }; let label = definition(&node.op).map_or(node.op.as_str(), |definition| definition.label); ui.heading(tr(label)); @@ -34,10 +29,15 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool { ui.label(tr("Output node")); } - let changed = node.value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)); - if changed && let Some(editor) = app.function_editor.take() { - canvas::commit(app, &editor, &graph); + let mut value = node.value.clone(); + let changed = value.as_mut().is_some_and(|value| crate::value_editor::show(ui, value)); + if changed + && let Some(value) = value + && let Some(mut editor) = app.function_editor.take() + { + editor.edit(app, materialcraft_engine::FunctionEdit::Value { id, value }, true); app.function_editor = Some(editor); } + true } diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs new file mode 100644 index 00000000..60a320bc --- /dev/null +++ b/crates/ui-egui/src/function/render.rs @@ -0,0 +1,214 @@ +use super::geometry::{category_color, in_port, node_rect, out_port, preview_rect, visible_inputs}; +use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; +use super::{function_canvas::FunctionCanvas, function_port::FunctionPort}; +use crate::graph::canvas_geometry::CanvasGeometry; +use crate::{MaterialCraftApp, graph::node_card, theme::Tokens}; +use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; +use egui_phosphor::regular as icon; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option<FunctionCanvas> { + let graph = editor.current(app)?; + let snap = app.ui.prefs.snap_to_grid; + let selected: BTreeSet<_> = editor.selection.iter().copied().collect(); + let layouts: BTreeMap<_, _> = + graph.nodes.iter().map(|node| (node.id, (node, preview_rect(app, editor, node, snap, selected.contains(&node.id))))).collect(); + editor.selection.retain(|id| layouts.contains_key(id)); + editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); + let standalone = matches!(editor.target, FunctionTarget::Graph); + let tokens = Tokens::get(ui.ctx()); + let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Function Graph"); + let painter = ui.painter_at(canvas_bounds); + painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); + let mut geometry = CanvasGeometry::default(); + let mut values = Vec::new(); + let mut nodes = Vec::new(); + let mut clear_annotation = false; + + let frame_key = crate::graph::GraphCamera::frame_key(ui, canvas_bounds); + if !editor.framed || app.ui.frame_all || frame_key { + editor.framed = true; + let selected_only = frame_key && !editor.selection.is_empty(); + let mut destination = graph + .nodes + .iter() + .filter(|node| !selected_only || selected.contains(&node.id)) + .map(|node| node_rect(node, app.ui.prefs.thumbnails)) + .fold(Rect::NOTHING, |combined, bounds| combined.union(bounds)); + if standalone + && !selected_only + && let Ok(document) = app.session.graph() + { + for frame in &document.frames { + destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0))); + } + } + let camera = crate::graph::GraphCamera::fit(canvas_bounds, destination); + editor.pan = camera.pan; + editor.zoom = camera.zoom; + } + + let mut camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; + camera.zoom_from_input(ui, canvas_bounds); + editor.pan = camera.pan; + editor.zoom = camera.zoom; + let document = standalone.then(|| app.session.graph().ok()).flatten(); + let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, &graph.frames, &camera)).unwrap_or_default(); + crate::graph::grid::paint(&painter, &camera, canvas_bounds); + + // Wires use the same prepared bounds as the cards + for node in &graph.nodes { + let Some((_, bounds)) = layouts.get(&node.id) else { continue }; + + for (input_index, source_id) in node.inputs.iter().enumerate() { + if let Some((source, source_bounds)) = source_id.and_then(|source| layouts.get(&source)) { + let source_position = camera.to_screen(out_port(source, *source_bounds)); + let destination = camera.to_screen(in_port(node, *bounds, input_index)); + let points = crate::graph::wire_geometry::bezier_points(source_position, destination); + geometry.wires.push(((materialcraft_engine::core::NodeId(u64::from(node.id)), input_index.to_string()), points)); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke( + points, + false, + Color32::TRANSPARENT, + Stroke::new(2.0, Color32::from_gray(0xb4)), + )); + } + } + } + + // Nodes + let font = FontId::proportional((11.0 * editor.zoom).min(16.0)); + let mut ports = Vec::new(); + for node in &graph.nodes { + let id = node.id; + let Some((_, bounds)) = layouts.get(&id) else { continue }; + + let bounds = *bounds; + let screen_rect = Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max)); + geometry.rects.push((materialcraft_engine::core::NodeId(u64::from(id)), screen_rect)); + + let definition = materialcraft_engine::nodes::function::definition(&node.op); + let label = definition.map_or("?", |definition| definition.label); + let dot = node.op == "passthrough"; + let show_labels = crate::graph::port_label::visible(ui, screen_rect); + let is_output = graph.output == Some(id); + let selected = selected.contains(&id); + let outline = if selected { + tokens.accent + } else if dot { + Color32::from_gray(0xb4) + } else { + Color32::from_gray(0x10) + }; + + if dot { + node_card::paint_dot(&painter, screen_rect, outline); + } else { + node_card::paint(&painter, screen_rect, editor.zoom, label, category_color(definition.map_or("", |definition| definition.category))); + node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); + let body = node_card::body(screen_rect, editor.zoom); + if node.value.is_none() { + painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); + } + if is_output { + let header = node_card::header(screen_rect, editor.zoom); + painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD); + } + } + + let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0); + let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value); + if let Some(definition) = definition { + for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() { + let position = camera.to_screen(in_port(node, bounds, input_index)); + painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); + if show_labels { + crate::graph::port_label::paint( + &painter, + position - vec2(10.0, 0.0), + Align2::RIGHT_CENTER, + port_label(identifier), + editor.zoom, + tokens.text_strong, + ); + } + ports.push(FunctionPort { + node: id, + slot: Some(input_index), + position, + radius: if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }, + label: port_label(identifier), + }); + } + } + + let output_position = camera.to_screen(out_port(node, bounds)); + painter.circle(output_position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); + if show_labels { + crate::graph::port_label::paint( + &painter, + output_position + vec2(10.0, 0.0), + Align2::LEFT_CENTER, + port_label("output"), + editor.zoom, + tokens.text_strong, + ); + } + ports.push(FunctionPort { + node: id, + slot: None, + position: output_position, + radius: if dot { (3.5 * editor.zoom).max(2.0) } else { 9.0 }, + label: port_label("output"), + }); + + let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); + crate::widgets::name(&body, egui::Role::Button, label); + + if !dot && node.value.is_some() { + let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content)); + child.set_clip_rect(content.intersect(canvas_bounds)); + if let Some(mut value) = node.value.clone() + && crate::value_editor::show(&mut child, &mut value) + { + values.push((id, value)); + } + } + + if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed() && !input.modifiers.alt)) || body.secondary_clicked() { + let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) }; + + crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); + if standalone && app.session.annotation_selection.is_some() { + clear_annotation = true; + } + } + + if body.drag_started() && !ui.input(|input| input.modifiers.alt) && editor.selection.contains(&id) && editor.drag.is_none() && !app.graph.is_dragging() + { + editor.drag = Some(FunctionDrag::Node(id, Vec2::ZERO)); + } + + nodes.push((id, body)); + } + + geometry.ports = ports + .iter() + .map(|port| crate::graph::PortHit { + node: materialcraft_engine::core::NodeId(u64::from(port.node)), + port: port.slot.map_or_else(|| "output".into(), |slot| slot.to_string()), + label: port.label.into(), + output: port.slot.is_none(), + kind: materialcraft_engine::nodes::PortKind::Value, + pos: port.position, + }) + .collect(); + + let comments = document.as_ref().map(|document| crate::graph::annotation_canvas::comments(app, ui, &document.comments, &camera)).unwrap_or_default(); + if let Some(document) = &document { + crate::graph::annotation_canvas::pins(app, ui, &document.pins, &camera); + } + Some(FunctionCanvas { response, camera, geometry, ports, nodes, values, frames: frame_hits, comments, clear_annotation }) +} diff --git a/crates/ui-egui/src/function/selection.rs b/crates/ui-egui/src/function/selection.rs deleted file mode 100644 index baf41e3d..00000000 --- a/crates/ui-egui/src/function/selection.rs +++ /dev/null @@ -1,104 +0,0 @@ -use super::FunctionEditor; -use materialcraft_engine::core::{FunctionGraph, FunctionNode}; -use std::collections::{BTreeMap, BTreeSet}; - -pub(super) fn enabled(editor: &FunctionEditor, command: &str) -> Option<bool> { - Some(match command { - "edit.selectAll" | "edit.selectNone" => true, - "edit.paste" | "edit.pasteWithoutLinks" => !editor.clipboard.is_empty(), - "edit.copy" - | "edit.cut" - | "edit.delete" - | "edit.deleteRelink" - | "edit.duplicate" - | "edit.duplicateWithoutLinks" - | "graph.selectUpstream" - | "graph.selectDownstream" => !editor.selection.is_empty(), - "graph.node.disable" => false, - _ => return None, - }) -} - -pub(super) fn run(editor: &mut FunctionEditor, graph: &mut FunctionGraph, command: &str, snap: bool) -> bool { - match command { - "edit.selectAll" => editor.selection = graph.nodes.iter().map(|node| node.id).collect(), - "edit.selectNone" => editor.selection.clear(), - "edit.copy" | "edit.cut" => { - editor.clipboard = graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect(); - if command == "edit.cut" { - return remove(editor, graph, false); - } - } - "edit.delete" | "edit.deleteRelink" => return remove(editor, graph, command == "edit.deleteRelink"), - "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { - let duplicate = command.starts_with("edit.duplicate"); - let nodes: Vec<FunctionNode> = - if duplicate { graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect() } else { editor.clipboard.clone() }; - let anchor = nodes.first().map_or([0.0; 2], |node| node.pos); - let offset = if duplicate { [32.0; 2] } else { [editor.menu_at.x - anchor[0], editor.menu_at.y - anchor[1]] }; - let mut ids = BTreeMap::new(); - for mut node in nodes { - let source = node.id; - node.id = graph.next_id(); - node.pos = materialcraft_engine::graph_grid::snap_position([node.pos[0] + offset[0], node.pos[1] + offset[1]], snap); - ids.insert(source, node.id); - graph.nodes.push(node); - } - editor.selection = ids.values().copied().collect(); - for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { - for input in &mut node.inputs { - *input = input.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks")).then_some(id))); - } - } - return !ids.is_empty(); - } - "graph.selectUpstream" | "graph.selectDownstream" => { - let upstream = command == "graph.selectUpstream"; - let mut visited = BTreeSet::new(); - let mut pending = editor.selection.clone(); - while let Some(id) = pending.pop() { - if !visited.insert(id) { - continue; - } - if upstream { - if let Some(node) = graph.node(id) { - pending.extend(node.inputs.iter().flatten()); - } - } else { - pending.extend(graph.nodes.iter().filter(|node| node.inputs.contains(&Some(id))).map(|node| node.id)); - } - } - editor.selection = visited.into_iter().collect(); - } - _ => {} - } - false -} - -fn remove(editor: &mut FunctionEditor, graph: &mut FunctionGraph, relink: bool) -> bool { - let replacements: BTreeMap<_, _> = graph - .nodes - .iter() - .filter(|node| editor.selection.contains(&node.id)) - .map(|node| (node.id, if relink { node.inputs.first().copied().flatten() } else { None })) - .collect(); - graph.nodes.retain(|node| !editor.selection.contains(&node.id)); - for node in &mut graph.nodes { - for input in &mut node.inputs { - let mut seen = BTreeSet::new(); - while let Some(id) = *input { - let Some(replacement) = replacements.get(&id) else { break }; - if !seen.insert(id) { - *input = None; - break; - } - *input = *replacement; - } - } - } - if graph.output.is_some_and(|id| editor.selection.contains(&id)) { - graph.output = None; - } - editor.selection.clear(); - !replacements.is_empty() -} diff --git a/crates/ui-egui/src/graph/actions.rs b/crates/ui-egui/src/graph/actions.rs index 84d38eed..9c0dddeb 100644 --- a/crates/ui-egui/src/graph/actions.rs +++ b/crates/ui-egui/src/graph/actions.rs @@ -2,6 +2,7 @@ use crate::{MaterialCraftApp, docking::Panel}; pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { match command { + "ui.graph.viewOutputs" | "ui.graph.resetViewOutputs" => Some(app.session.graph().is_ok_and(|graph| graph.function.is_none())), "ui.graph.previousPin" | "ui.graph.nextPin" => Some(app.session.graph().is_ok_and(|graph| !graph.pins.is_empty())), command if command.starts_with("ui.graph.") => Some(app.session.graph().is_ok()), _ => None, @@ -18,18 +19,27 @@ pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { let Some(result) = app.run(command, serde_json::Value::Null) else { return true }; let Some(node) = result.get("node").and_then(serde_json::Value::as_u64) else { return true }; - app.function_editor = None; - app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, materialcraft_engine::core::NodeId(node))); + let node = materialcraft_engine::core::NodeId(node); + match result.get("kind").and_then(serde_json::Value::as_str) { + Some("pattern") => { + app.function_editor = None; + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, node)); + } + Some("function") => { + super::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Parameter("function".into())); + } + Some("graph") => { + if let Some(index) = result.get("graph").and_then(serde_json::Value::as_u64).and_then(|index| usize::try_from(index).ok()) { + super::subgraph_navigation::open_instance(app, index); + } + } + _ => {} + } app.ui.dock.focus(Panel::Graph); } "ui.graph.snapToGrid" => app.ui.prefs.snap_to_grid = !app.ui.prefs.snap_to_grid, "ui.graph.viewOutputs" | "ui.graph.resetViewOutputs" => { - if command == "ui.graph.resetViewOutputs" { - app.run("view.3d.reset", serde_json::Value::Null); - } - - app.ui.dock.focus(Panel::View3d); - app.session.dirty = true; + app.run("view.3d.outputs", serde_json::json!({"reset": command == "ui.graph.resetViewOutputs"})); } "ui.graph.computeThumbnails" => { app.graph.thumbnails_cleared = false; @@ -68,4 +78,9 @@ fn navigate_pin(app: &mut MaterialCraftApp, forward: bool) { let Some(pin) = graph.pins.get(index) else { return }; camera.pan = [pin.pos[0] - app.graph.view.width() * 0.5 / zoom, pin.pos[1] - app.graph.view.height() * 0.5 / zoom]; + if let Some(editor) = &mut app.function_editor + && editor.target == crate::function::FunctionTarget::Graph + { + editor.set_camera(*camera); + } } diff --git a/crates/ui-egui/src/graph/annotation_canvas.rs b/crates/ui-egui/src/graph/annotation_canvas.rs index 0071f915..e37bb4d0 100644 --- a/crates/ui-egui/src/graph/annotation_canvas.rs +++ b/crates/ui-egui/src/graph/annotation_canvas.rs @@ -1,16 +1,19 @@ use egui::{Align2, Color32, FontId, Rect, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; -use materialcraft_engine::{AnnotationSelection, core::Graph}; +use materialcraft_engine::{ + AnnotationSelection, + core::{Comment, Frame, Pin}, +}; use super::{GraphCamera, GraphDrag, frame_hit::FrameHit}; use crate::{MaterialCraftApp, theme::Tokens}; -pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) -> Vec<FrameHit> { +pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, frames: &[Frame], camera: &GraphCamera) -> Vec<FrameHit> { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - let mut hits = Vec::with_capacity(graph.frames.len()); + let mut hits = Vec::with_capacity(frames.len()); - let mut frames: Vec<_> = graph.frames.iter().collect(); + let mut frames: Vec<_> = frames.iter().collect(); frames.sort_by(|first, second| (second.rect[2] * second.rect[3]).total_cmp(&(first.rect[2] * first.rect[3]))); for frame in frames { @@ -29,6 +32,7 @@ pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &Gr let fill = Color32::from_rgba_unmultiplied(channel(color[0]), channel(color[1]), channel(color[2]), (color[3] * 255.0).round() as u8); let selected = app.session.annotation_selection == Some(AnnotationSelection::Frame(frame.id)); let outline = if selected { Stroke::new(2.0, theme.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(180)) }; + painter.rect(rect, 0.0, fill, outline, StrokeKind::Outside); let title = if frame.title_visible { @@ -58,12 +62,12 @@ pub(crate) fn frames(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &Gr hits } -pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) -> Vec<(u64, Rect)> { +pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, comments: &[Comment], camera: &GraphCamera) -> Vec<(u64, Rect)> { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - let mut hits = Vec::with_capacity(graph.comments.len()); + let mut hits = Vec::with_capacity(comments.len()); - for comment in &graph.comments { + for comment in comments { let mut position = pos2(comment.pos[0], comment.pos[1]) + offset(app, |contents| contents.comments.contains(&comment.id)); if let Some(GraphDrag::Comment { id, delta }) = &app.graph.drag && *id == comment.id @@ -73,6 +77,7 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: & let selected = app.session.annotation_selection == Some(AnnotationSelection::Comment(comment.id)); let color = if selected { theme.accent } else { theme.text }; + let text = painter.layout(comment.text.clone(), FontId::proportional((14.0 * camera.zoom).clamp(6.0, 36.0)), color, comment.size[0] * camera.zoom); let rect = Rect::from_min_size(camera.to_screen(position), text.size().max(vec2(24.0, 16.0))); painter.galley(rect.min, text, color); @@ -82,11 +87,11 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: & hits } -pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, graph: &Graph, camera: &GraphCamera) { +pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - for pin in &graph.pins { + for pin in pins { let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); let position = camera.to_screen(position); painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent); diff --git a/crates/ui-egui/src/graph/annotation_input.rs b/crates/ui-egui/src/graph/annotation_input.rs index a6bae1ec..565462af 100644 --- a/crates/ui-egui/src/graph/annotation_input.rs +++ b/crates/ui-egui/src/graph/annotation_input.rs @@ -4,23 +4,21 @@ use egui::{Rect, Ui, Vec2}; use serde_json::json; pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, frames: &[FrameHit], comments: &[(u64, Rect)]) { + if super::gesture::cancelled(ui) { + app.graph.drag = None; + return; + } + let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return }; + let pressed = ui.input(|input| input.pointer.primary_pressed()); let motion = ui.input(|input| input.pointer.delta()) / camera.zoom; if pressed && app.graph.view.contains(pointer) && app.graph.drag.is_none() && !app.graph.rects.iter().any(|(_, rect)| rect.contains(pointer)) { if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(pointer)) { - app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - app.graph.drag = Some(GraphDrag::Comment { id: *id, delta: Vec2::ZERO }); + begin_comment(app, *id); } else if let Some(hit) = frames.iter().rev().find(|hit| hit.contains(pointer)) { - let contents = app - .session - .graph() - .ok() - .and_then(|graph| graph.frames.iter().find(|frame| frame.id == hit.id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame))) - .unwrap_or_default(); - app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); - app.graph.drag = Some(GraphDrag::Frame { id: hit.id, delta: Vec2::ZERO, resize: hit.grip.contains(pointer), contents }); + begin_frame(app, hit.id, hit.grip.contains(pointer)); } else { app.run("graph.annotation.select", json!({})); } @@ -28,25 +26,47 @@ pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, *delta += motion; } - if ui.input(|input| input.pointer.primary_released()) { - match app.graph.drag.take() { - Some(GraphDrag::Frame { id, delta, resize, .. }) if delta.length() > 0.5 => { - if resize { - if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { - let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; - app.run("graph.frame.edit", json!({"id": id, "rect": rect})); - } - } else { - app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); + if super::gesture::finished(ui, egui::PointerButton::Primary) + && let Some(drag) = app.graph.drag.take() + { + finish(app, drag); + } +} + +pub(super) fn begin_comment(app: &mut MaterialCraftApp, id: u64) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + app.graph.drag = Some(GraphDrag::Comment { id, delta: Vec2::ZERO }); +} + +pub(super) fn begin_frame(app: &mut MaterialCraftApp, id: u64, resize: bool) { + let contents = app + .session + .graph() + .ok() + .and_then(|graph| graph.frames.iter().find(|frame| frame.id == id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame))) + .unwrap_or_default(); + app.run("graph.annotation.select", json!({"kind": "frame", "id": id})); + app.graph.drag = Some(GraphDrag::Frame { id, delta: Vec2::ZERO, resize, contents }); +} + +pub(super) fn finish(app: &mut MaterialCraftApp, drag: GraphDrag) { + match drag { + GraphDrag::Frame { id, delta, resize, .. } if delta.length() > 0.5 => { + if resize { + if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { + let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; + app.run("graph.frame.edit", json!({"id": id, "rect": rect})); } + } else { + app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); } - Some(GraphDrag::Comment { id, delta }) if delta.length() > 0.5 => { - if let Some(comment) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)) { - let position = [comment.pos[0] + delta.x, comment.pos[1] + delta.y]; - app.run("graph.comment.edit", json!({"id": id, "at": position})); - } + } + GraphDrag::Comment { id, delta } if delta.length() > 0.5 => { + if let Some(comment) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)) { + let position = [comment.pos[0] + delta.x, comment.pos[1] + delta.y]; + app.run("graph.comment.edit", json!({"id": id, "at": position})); } - _ => {} } + _ => {} } } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 6efaf7a5..c876e19b 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -1,283 +1,46 @@ -use super::node_card; -use super::node_card::port as port_pos; -use super::node_layout::NodeLayout; -use super::{GraphCamera, GraphDrag, LibraryDrag, NodeSearch, PortHit, WireRef}; -use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; +use super::node_style::{PORT_RADIUS, header_color, node_label, node_rect, port_color}; +use super::{GraphCamera, GraphDrag, PortHit, WireRef}; +use super::{ + navigation::frame, + port_hit::nearest as nearest_port, + wire_geometry::{bezier, bezier_points, wire_at}, +}; +use super::{node_card, node_card::port as port_pos, node_layout::NodeLayout}; +use crate::{MaterialCraftApp, theme::Tokens}; +use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; -use materialcraft_engine::core::{Node, NodeId, Value}; -use materialcraft_engine::nodes::PortKind; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -pub const NODE_W: f32 = node_card::WIDTH; -const PORT_R: f32 = 4.5; - -/// Pointer distance (points) within which a wire is hit -const WIRE_HIT: f32 = 5.0; - -/// Header strip color of a node by its library category -pub fn header_color(def: &str) -> Color32 { - let cat = materialcraft_engine::nodes::find(def).map_or("", |d| d.category); - match def { - "output" => Color32::from_rgb(0x2c, 0x8f, 0x5e), - "input_color" | "input_grayscale" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "graph_instance" => Color32::from_rgb(0x1e, 0x8a, 0xa0), - _ if cat.starts_with("Atomic") => Color32::from_rgb(0x5c, 0x62, 0x6e), - _ if cat.contains("Noises") => Color32::from_rgb(0xa8, 0x3c, 0x34), - _ if cat.contains("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ if cat.starts_with("Material") => Color32::from_rgb(0x3a, 0x66, 0xb0), - _ if cat.starts_with("Filters") => Color32::from_rgb(0x3b, 0x7f, 0x4c), - _ => Color32::from_rgb(0x5c, 0x62, 0x6e), - } -} - -pub fn port_color(kind: PortKind) -> Color32 { - match kind { - PortKind::Gray => Color32::from_rgb(0xc8, 0xc8, 0xc8), - PortKind::Color => Color32::from_rgb(0xe8, 0xa9, 0x3c), - PortKind::Value => Color32::from_rgb(0x8b, 0xc6, 0x74), - PortKind::Any => Color32::from_rgb(0x8c, 0xb4, 0xe0), - } -} - -/// A node's display label -pub fn node_label(n: &Node) -> String { - if !n.label.is_empty() { - return n.label.clone(); - } - match n.def.as_str() { - "graph_instance" => match n.params.get("graph") { - Some(Value::Text(g)) => g.clone(), - _ => tr("Graph instance").into(), - }, - "output" | "input_color" | "input_grayscale" => materialcraft_engine::eval::identifier(n), - d => materialcraft_engine::nodes::find(d).map_or(d, |d| d.label).to_string(), - } -} - -/// Graph-space rectangle of a node card -pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect { - node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot") -} - -fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { - let dx = ((b.x - a.x).abs() * 0.5).max(30.0); - [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b] -} - -fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { - p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke)); -} - -/// The point at `t` (0..1) along a cubic bezier -fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 { - let u = 1.0 - t; - let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; - pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum()) -} - -/// Distance from `p` to a cubic bezier (sampled as a polyline) -fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { - const N: usize = 32; - let mut best = f32::INFINITY; - let mut prev = c[0]; - for i in 1..=N { - let q = bezier_at(c, i as f32 / N as f32); - let (seg, rel) = (q - prev, p - prev); - let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; - best = best.min((prev + seg * t).distance(p)); - prev = q; - } - best -} - -/// The wire nearest `p` within [`WIRE_HIT`] points -fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { - wires - .iter() - .filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p)) - .map(|(w, c)| (w, bezier_distance(c, p))) - .filter(|(_, d)| *d <= WIRE_HIT) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(w, _)| w) -} +use materialcraft_engine::core::NodeId; /// The graph panel: toolbar row and canvas pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + app.reconcile_editors(); + if !crate::pattern::active(app) { + app.pattern_editor = None; + if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + let target = crate::function::FunctionTarget::Graph; + if app.function_editor.as_ref().is_none_or(|editor| editor.target != target) { + app.function_editor = Some(crate::function::FunctionEditor::standalone(app.session.graph)); + } + } else if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph)) { + app.function_editor = None; + } + } + + super::toolbar::show(app, ui); + if app.function_editor.is_some() { + crate::function::show_graph(app, ui); + return; + } if crate::pattern::active(app) { crate::pattern::show(app, ui); return; } - app.pattern_editor = None; - if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { - crate::function::show_graph(app, ui); - return; - } - if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph(_))) { - app.function_editor = None; - } - - toolbar(app, ui); canvas(app, ui); } -fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - let b = |ui: &mut Ui, ic: &str, tip: &str| crate::widgets::icon_button(ui, ic, tip, false, 22.0).clicked(); - if b(ui, icon::CORNERS_OUT, tr("Frame all (F)")) { - app.ui.frame_all = true; - } - for (ic, mode, tip) in [ - (icon::ALIGN_LEFT, "left", "Align left"), - (icon::ALIGN_TOP, "top", "Align top"), - (icon::ALIGN_CENTER_HORIZONTAL, "hcenter", "Align centers horizontally"), - (icon::ALIGN_CENTER_VERTICAL, "vcenter", "Align centers vertically"), - (icon::COLUMNS, "hdistribute", "Distribute horizontally"), - (icon::ROWS, "vdistribute", "Distribute vertically"), - ] { - if b(ui, ic, tr(tip)) { - app.run("graph.align", json!({"mode": mode})); - } - } - ui.separator(); - if b(ui, icon::SELECTION, tr("Add frame around the selection")) { - app.run("graph.frame.add", json!({})); - } - if b(ui, icon::NOTE, tr("Add comment")) { - app.run("graph.comment.add", json!({})); - } - if b(ui, icon::MAP_PIN, tr("Add navigation pin")) { - let c = view_center(app); - app.run("graph.pin.add", json!({"at": [c.x, c.y]})); - } - ui.separator(); - if crate::widgets::icon_button(ui, icon::GRID_FOUR, tr("Snap to grid"), app.ui.prefs.snap_to_grid, 22.0).clicked() { - crate::menus::invoke(app, ui.ctx(), "ui.graph.snapToGrid"); - } - - // Quick insert of the atomic nodes - for (ic, def) in [ - (icon::IMAGE, "bitmap"), - (icon::PALETTE, "uniform"), - (icon::STACK, "blend"), - (icon::DROP, "blur"), - (icon::SHUFFLE, "channels_shuffle"), - (icon::CHART_LINE, "curve"), - (icon::WIND, "directional_blur"), - (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), - (icon::RULER, "distance"), - (icon::MOUNTAINS, "emboss"), - (icon::GRADIENT, "gradient_map"), - (icon::CIRCLE_HALF, "grayscale_conversion"), - (icon::SWATCHES, "hsl"), - (icon::SLIDERS_HORIZONTAL, "levels"), - (icon::CUBE, "normal"), - (icon::CODE, "pixel_processor"), - (icon::DIAMOND, "sharpen"), - (icon::ARROWS_CLOCKWISE, "transformation"), - (icon::WAVES, "warp"), - (icon::SIGN_IN, "input_grayscale"), - (icon::SIGN_OUT, "output"), - ] { - let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); - if b(ui, ic, label) { - add_node_near_selection(app, def); - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let thumbs = app.ui.prefs.thumbnails; - if crate::widgets::icon_button(ui, icon::IMAGE, tr("Show node thumbnails"), thumbs, 22.0).clicked() { - app.ui.prefs.thumbnails = !thumbs; - } - parent_size(app, ui); - }); - }); - }); -} - -/// "Parent size: [1024 ▾] × [1024 ▾]" -fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Ok(g) = app.session.graph() else { return }; - let [w, h] = g.size; - let mut nw = w; - let mut nh = h; - let combo = |ui: &mut Ui, id: &str, v: &mut u32| { - let r = egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| { - for l in 4..=13u32 { - ui.selectable_value(v, l, format!("{}", 1u32 << l)); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); - }; - - combo(ui, "parent-h", &mut nh); - ui.label("x"); - combo(ui, "parent-w", &mut nw); - ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim)); - if (nw, nh) != (w, h) { - app.run("graph.size", json!({"log2": [nw, nh]})); - } -} - -fn view_center(app: &MaterialCraftApp) -> Pos2 { - let c = &app.ui.graph_camera; - let v = app.graph.view; - pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) -} - -/// Add `def` right of the last selected node (wired from it when it fits), else mid-view -pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { - let sel = app.session.selection.last().copied(); - let has_inputs = materialcraft_engine::nodes::find(def).is_some_and(|d| !d.inputs.is_empty()); - let params = match sel { - Some(id) if has_inputs && !app.session.output_ports(id).is_empty() => json!({"def": def, "connectFrom": {"node": id.0}}), - _ => { - let c = view_center(app); - json!({"def": def, "at": [c.x - NODE_W * 0.5, c.y - 60.0]}) - } - }; - - app.run("graph.node.add", params); -} - -/// Frame the graph (or the selection) in the view -fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { - let thumbs = app.ui.prefs.thumbnails; - let Ok(g) = app.session.graph() else { return }; - let mut r = Rect::NOTHING; - for n in &g.nodes { - if only_selection && !app.session.selection.contains(&n.id) { - continue; - } - - let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); - let visible = super::input_visibility::count(inputs.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); - r = r.union(node_rect(n, visible, outputs.len(), thumbs)); - } - for f in &g.frames { - if !only_selection { - r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1] - 32.0), vec2(f.rect[2], f.rect[3] + 32.0))); - } - } - if !r.is_finite() || r.width() <= 0.0 { - app.ui.graph_camera = crate::state::GraphCamera::default(); - return; - } - let r = r.expand(40.0); - let zoom = (view.width() / r.width()).min(view.height() / r.height()).clamp(0.1, 1.5); - let pan = r.center().to_vec2() - vec2(view.width(), view.height()) * 0.5 / zoom; - app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; -} - fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + 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"); @@ -291,31 +54,17 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let painter = ui.painter_at(rect); // Background and grid painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31)); - let cam = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; - grid(&painter, &cam, rect); + let mut camera = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; + 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 = ctx.input(|i| i.pointer.hover_pos()); - let hovered_canvas = pointer.is_some_and(|p| rect.contains(p)) && resp.hovered(); + let show_thumbnails = app.ui.prefs.thumbnails; + let Ok(graph) = app.session.graph() else { return }; - // Zoom around the pointer - if hovered_canvas || ui.rect_contains_pointer(rect) { - let scroll = ctx.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0); - if scroll.abs() > 0.0 - && let Some(p) = pointer - && rect.contains(p) - { - let before = cam.to_graph(p); - let zoom = (cam.zoom * (scroll * 0.0025).exp()).clamp(0.08, 4.0); - let pan = before.to_vec2() - (p - rect.min) / zoom; - app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; - } - } - let cam = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; - - let thumbs_on = app.ui.prefs.thumbnails; - let Ok(g) = app.session.graph() else { return }; - let g = g.clone(); - let selection = app.session.selection.clone(); + let index = materialcraft_engine::core::GraphIndex::new(graph); + let selection: std::collections::BTreeSet<_> = app.session.selection.iter().copied().collect(); let node_delta = match &app.graph.drag { Some(GraphDrag::Nodes { delta }) => *delta, _ => Vec2::ZERO, @@ -323,40 +72,42 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Layout every node and its ports - let mut laid: Vec<NodeLayout> = Vec::with_capacity(g.nodes.len()); - for n in &g.nodes { - let (mut ins, outs) = materialcraft_engine::eval::ports(&app.session.pkg, &g, n); - let visible = super::input_visibility::count(ins.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); + let mut layouts: Vec<NodeLayout> = Vec::with_capacity(graph.nodes.len()); + for node in &graph.nodes { + let (mut ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); + let visible = + super::input_visibility::count(ins.iter().map(|port| index.input_of(node.id, &port.id).is_some()), if node.def == "fx_map" { 2 } else { 1 }); ins.truncate(visible); - let mut r = node_rect(n, ins.len(), outs.len(), thumbs_on); - if selection.contains(&n.id) && node_delta.length() > 0.5 { - let position = materialcraft_engine::graph_grid::snap_position([n.pos[0] + node_delta.x, n.pos[1] + node_delta.y], app.ui.prefs.snap_to_grid); - r = r.translate(vec2(position[0] - n.pos[0], position[1] - n.pos[1])); + let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails); + if selection.contains(&node.id) && node_delta.length() > 0.5 { + let position = materialcraft_engine::graph_grid::translate(node.pos, node_delta.into(), app.ui.prefs.snap_to_grid); + r = r.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1])); } - r = r.translate(super::annotation_canvas::offset(app, |contents| contents.nodes.contains(&n.id))); - let dot = n.def == "dot"; - let pi = |i: usize, output: bool, total: usize| port_pos(r, i, total, output, dot); - laid.push(NodeLayout { - id: n.id, + r = r.translate(super::annotation_canvas::offset(app, |contents| contents.nodes.contains(&node.id))); + let dot = node.def == "dot"; + let port_position = |i: usize, output: bool, total: usize| port_pos(r, i, total, output, dot); + layouts.push(NodeLayout { + id: node.id, rect: r, - ins: ins.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, false, ins.len()))).collect(), - outs: outs.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, true, outs.len()))).collect(), + ins: ins.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, port_position(i, false, ins.len()))).collect(), + outs: outs.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, port_position(i, true, outs.len()))).collect(), }); } - app.graph.rects = laid.iter().map(|l| (l.id, Rect::from_min_max(cam.to_screen(l.rect.min), cam.to_screen(l.rect.max)))).collect(); - app.graph.ports = laid + app.graph.rects = + layouts.iter().map(|layout| (layout.id, Rect::from_min_max(camera.to_screen(layout.rect.min), camera.to_screen(layout.rect.max)))).collect(); + app.graph.ports = layouts .iter() - .flat_map(|l| { - let ins = l.ins.iter().map(move |(id, label, kind, p)| PortHit { - node: l.id, + .flat_map(|layout| { + let ins = layout.ins.iter().map(move |(id, label, kind, p)| PortHit { + node: layout.id, output: false, port: id.clone(), label: label.clone(), pos: *p, kind: *kind, }); - let outs = l.outs.iter().map(move |(id, label, kind, p)| PortHit { - node: l.id, + let outs = layout.outs.iter().map(move |(id, label, kind, p)| PortHit { + node: layout.id, output: true, port: id.clone(), label: label.clone(), @@ -366,14 +117,19 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { ins.chain(outs) }) .map(|mut h| { - h.pos = cam.to_screen(h.pos); + h.pos = camera.to_screen(h.pos); h }) .collect(); - let frame_hits = super::annotation_canvas::frames(app, ui, &g, &cam); + let frame_hits = super::annotation_canvas::frames(app, ui, &graph.frames, &camera); app.graph.frames = frame_hits.iter().map(|frame| (frame.id, frame.rect)).collect(); + let mut layout_indices = std::collections::BTreeMap::new(); + for (index, layout) in layouts.iter().enumerate() { + layout_indices.entry(layout.id).or_insert(index); + } + // Wires let cooked = &app.session.cooked; let detached = match &app.graph.drag { @@ -381,15 +137,15 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { _ => None, }; - let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(g.connections.len()); - for c in &g.connections { - if detached.as_ref().is_some_and(|(n, p)| *n == c.to && *p == c.to_port) { + let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(graph.connections.len()); + for c in &graph.connections { + if detached.as_ref().is_some_and(|(node, p)| *node == c.to && *p == c.to_port) { continue; } - let a = laid.iter().find(|l| l.id == c.from).and_then(|l| l.outs.iter().find(|p| p.0 == c.from_port)); - let b = laid.iter().find(|l| l.id == c.to).and_then(|l| l.ins.iter().find(|p| p.0 == c.to_port)); + let a = layout_indices.get(&c.from).and_then(|index| layouts.get(*index)).and_then(|layout| layout.outs.iter().find(|p| p.0 == c.from_port)); + let b = layout_indices.get(&c.to).and_then(|index| layouts.get(*index)).and_then(|layout| layout.ins.iter().find(|p| p.0 == c.to_port)); if let (Some(a), Some(b)) = (a, b) { - wires.push(((c.to, c.to_port.clone()), bezier_points(cam.to_screen(a.3), cam.to_screen(b.3)))); + wires.push(((c.to, c.to_port.clone()), bezier_points(camera.to_screen(a.3), camera.to_screen(b.3)))); } } // Hover: not where a node card or a port sits on top of the wire @@ -401,17 +157,18 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { }; for (w, ctrl) in &wires { - let Some(c) = g.input_of(w.0, &w.1) else { continue }; + let Some(c) = index.input_of(w.0, &w.1) else { continue }; + let hot = selection.contains(&c.from) || selection.contains(&c.to); let picked = app.graph.selected_wires.contains(w); let hovered = wire_hover.as_ref() == Some(w); - let base = (2.0 * cam.zoom).clamp(1.0, 3.0); + let base = (2.0 * camera.zoom).clamp(1.0, 3.0); let stroke = if picked { - Stroke::new(base + 2.0, tk.accent) + Stroke::new(base + 2.0, theme.accent) } else if hovered { Stroke::new(base + 1.0, Color32::WHITE) } else { - Stroke::new(base, if hot { tk.accent } else { Color32::from_gray(0xb4) }) + Stroke::new(base, if hot { theme.accent } else { Color32::from_gray(0xb4) }) }; painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke)); @@ -419,80 +176,82 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { app.graph.wires = wires; // Nodes - let font = FontId::proportional((10.5 * cam.zoom).clamp(6.0, 16.0)); - let small = FontId::proportional((9.0 * cam.zoom).clamp(5.5, 13.0)); - let mut node_resps: Vec<(NodeId, egui::Response)> = Vec::new(); - for l in &laid { - let Ok(n) = g.node(l.id) else { continue }; - let sr = Rect::from_min_max(cam.to_screen(l.rect.min), cam.to_screen(l.rect.max)); - if !sr.intersects(rect) { + let font = FontId::proportional((10.5 * camera.zoom).clamp(6.0, 16.0)); + let small = FontId::proportional((9.0 * camera.zoom).clamp(5.5, 13.0)); + let mut node_responses: Vec<(NodeId, egui::Response)> = Vec::new(); + for layout in &layouts { + let Some(node) = index.node(layout.id) else { continue }; + + let screen_rect = Rect::from_min_max(camera.to_screen(layout.rect.min), camera.to_screen(layout.rect.max)); + if !screen_rect.intersects(rect) { continue; } - let selected = selection.contains(&n.id); - let result = cooked.nodes.get(&n.id); - let error = result.and_then(|r| r.error.clone()); - let resp = ui.interact(sr, ui.scope_id().with(("node", n.id.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Button, &node_label(n)); - if n.def == "dot" { - node_card::paint_dot(&painter, sr, if selected { tk.accent } else { Color32::from_gray(0xb4) }); + let selected = selection.contains(&node.id); + let result = cooked.nodes.get(&node.id); + let error = result.and_then(|r| r.error.as_ref()); + let resp = ui.interact(screen_rect, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); + crate::widgets::name(&resp, 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, sr, cam.zoom, &node_label(n), header_color(&n.def)); - let header = node_card::header(sr, cam.zoom); - let body = node_card::body(sr, cam.zoom); + 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) - && thumbs_on + && show_thumbnails && !app.graph.thumbnails_cleared { - let side = body.width().min(body.height()) - 6.0 * cam.zoom; + let side = body.width().min(body.height()) - 6.0 * camera.zoom; let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); 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 n.disabled { Color32::from_gray(90) } else { Color32::WHITE }); + 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 }); } else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) { let text = match value { materialcraft_engine::core::Value::Float(value) => value.to_string(), _ => serde_json::to_value(value).ok().and_then(|value| value.get("v").map(ToString::to_string)).unwrap_or_default(), }; - let text = crate::widgets::elided(&painter, text, font.size, tk.text, body.width() - 8.0); - painter.galley(body.center() - text.size() * 0.5, text, tk.text); + let text = crate::widgets::elided(&painter, text, font.size, theme.text, body.width() - 8.0); + painter.galley(body.center() - text.size() * 0.5, text, theme.text); } else if result.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), tk.text_dim); + painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), theme.text_dim); } // Footer: size and format - let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max); + 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)) { - let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }; + let bits = if node.base.format == materialcraft_engine::core::OutputFormat::Inherit { graph.format.bits() } else { node.base.format.bits() }; + let txt = format!("{}x{} - {}{}", img.w, img.h, if img.is_gray() { "L" } else { "C" }, bits); - painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim); + painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim); } - if n.def == "output" { + if node.def == "output" { painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE); } let outline = if error.is_some() { Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0)) } else if selected { - Stroke::new(2.0, tk.accent) + Stroke::new(2.0, theme.accent) } else if resp.hovered() { Stroke::new(1.0, Color32::from_gray(0x90)) } else { Stroke::new(1.0, Color32::from_gray(0x10)) }; - node_card::outline(&painter, sr, cam.zoom, outline); - if n.disabled { - painter.line_segment([sr.left_top(), sr.right_bottom()], Stroke::new(1.5, tk.danger)); + node_card::outline(&painter, screen_rect, camera.zoom, outline); + if node.disabled { + painter.line_segment([screen_rect.left_top(), screen_rect.right_bottom()], Stroke::new(1.5, theme.danger)); } - if let Some(e) = &error { + if let Some(e) = error { resp.clone().on_hover_text(e); } } - node_resps.push((n.id, resp)); + node_responses.push((node.id, resp)); } - let comment_hits = super::annotation_canvas::comments(app, ui, &g, &cam); + let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera); app.graph.comments = comment_hits.clone(); - super::annotation_canvas::pins(app, ui, &g, &cam); + super::annotation_canvas::pins(app, ui, &graph.pins, &camera); // Ports (drawn last, interactable over the node cards) let port_hover = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 9.0)).cloned(); @@ -501,7 +260,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { continue; } let hot = port_hover.as_ref().is_some_and(|x| x.node == h.node && x.port == h.port && x.output == h.output); - let r = (PORT_R * cam.zoom).clamp(2.5, 7.0) * if hot { 1.4 } else { 1.0 }; + let r = (PORT_RADIUS * camera.zoom).clamp(2.5, 7.0) * if hot { 1.4 } else { 1.0 }; + painter.circle(h.pos, r, port_color(h.kind), Stroke::new(1.0, Color32::from_gray(0x18))); } let hovered_node = app.graph.rects.iter().rev().find(|(_, bounds)| super::port_label::visible(ui, *bounds)).map(|(id, _)| *id); @@ -511,8 +271,10 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { } let anchor = if port.output { Align2::LEFT_CENTER } else { Align2::RIGHT_CENTER }; + let offset = if port.output { vec2(10.0, 0.0) } else { vec2(-10.0, 0.0) }; - super::port_label::paint(&painter, port.pos + offset, anchor, &port.label, cam.zoom, tk.text_strong); + + super::port_label::paint(&painter, port.pos + offset, anchor, &port.label, camera.zoom, theme.text_strong); } // A wire under a comment is not hit @@ -521,706 +283,34 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { ctx.set_cursor_icon(egui::CursorIcon::PointingHand); } app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); - handle_input(app, ui, &resp, rect, &cam, &node_resps, &frame_hits, &comment_hits, port_hover, wire_hover); + super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, port_hover, wire_hover); app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node); // GraphDrag previews match &app.graph.drag { Some(GraphDrag::Box { start }) => { if let Some(p) = pointer { - let r = Rect::from_two_pos(*start, p); - painter.rect(r, 0.0, tk.accent.gamma_multiply(0.12), Stroke::new(1.0, tk.accent), StrokeKind::Inside); + super::node_selection::paint_box(&painter, *start, p, theme.accent); } } Some(GraphDrag::Wire { from, .. }) => { if let (Some(p), Some(src)) = (pointer, app.graph.ports.iter().find(|h| h.output && h.node == from.0 && h.port == from.1)) { - bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent)); + bezier(&painter, src.pos, p, Stroke::new(2.0, theme.accent)); } } _ => {} } - search_popup(app, ui, &cam); + super::search::show(app, ui, &camera); let (failed, placeholders) = app.session.cook_failures(); let mut at = rect.right_bottom() - vec2(8.0, 8.0); if !failed.is_empty() { let text = format!("{} {} node(s) failed", icon::WARNING, failed.len()); - at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.danger).top() - 2.0; + at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), theme.danger).top() - 2.0; } // Placeholders for missing SBS nodes are a soft warning, not a failure if placeholders > 0 { let text = format!("{} {placeholders} missing node(s), see the Console", icon::WARNING); - painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.warning); - } -} - -pub(crate) fn grid(p: &egui::Painter, cam: &GraphCamera, rect: Rect) { - for (step, alpha) in [(materialcraft_engine::graph_grid::GRID_SPACING, 10u8), (256.0, 22)] { - let s = step * cam.zoom; - if s < 8.0 { - continue; - } - let col = Color32::from_white_alpha(alpha); - let x0 = cam.pan.x - (cam.pan.x.rem_euclid(step)); - let mut x = x0; - while cam.to_screen(pos2(x, 0.0)).x < rect.right() { - let sx = cam.to_screen(pos2(x, 0.0)).x; - p.line_segment([pos2(sx, rect.top()), pos2(sx, rect.bottom())], Stroke::new(1.0, col)); - x += step; - } - let y0 = cam.pan.y - (cam.pan.y.rem_euclid(step)); - let mut y = y0; - while cam.to_screen(pos2(0.0, y)).y < rect.bottom() { - let sy = cam.to_screen(pos2(0.0, y)).y; - p.line_segment([pos2(rect.left(), sy), pos2(rect.right(), sy)], Stroke::new(1.0, col)); - y += step; - } - } -} - -fn nearest_port(ports: &[PortHit], p: Pos2, radius: f32) -> Option<&PortHit> { - ports.iter().filter(|h| h.pos.distance(p) <= radius).min_by(|a, b| a.pos.distance(p).total_cmp(&b.pos.distance(p))) -} - -#[allow(clippy::too_many_arguments)] -fn handle_input( - app: &mut MaterialCraftApp, - ui: &mut Ui, - canvas: &egui::Response, - rect: Rect, - cam: &GraphCamera, - nodes: &[(NodeId, egui::Response)], - frames: &[super::frame_hit::FrameHit], - comments: &[(u64, Rect)], - port_hover: Option<PortHit>, - wire_hover: Option<WireRef>, -) { - let ctx = ui.ctx().clone(); - let (pointer, mods, primary_pressed, primary_down, middle_down, released) = ctx.input(|i| { - (i.pointer.interact_pos(), i.modifiers, i.pointer.primary_pressed(), i.pointer.primary_down(), i.pointer.middle_down(), i.pointer.any_released()) - }); - let zoom = cam.zoom; - let motion = ctx.input(|i| i.pointer.delta()) / zoom; - - // Starting gestures (only on a press inside the canvas, with no gesture running) - if app.graph.drag.is_none() - && let Some(p) = pointer - && rect.contains(p) - && app.graph.search.is_none() - { - if middle_down || (primary_pressed && mods.alt) { - app.graph.drag = Some(GraphDrag::Pan); - } else if primary_pressed { - if app.session.annotation_selection.is_some() { - app.run("graph.annotation.select", json!({})); - } - - let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); - let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); - // Any press other than on a wire drops the wire selection - if wire.is_none() { - app.graph.selected_wires.clear(); - } - if let Some(w) = wire { - app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); - } else if let Some(h) = &port_hover { - if h.output { - app.graph.drag = Some(GraphDrag::Wire { from: (h.node, h.port.clone()), detached: None }); - } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { - app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); - } - } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { - app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - app.graph.drag = Some(GraphDrag::Comment { id: *id, delta: Vec2::ZERO }); - } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { - super::node_selection::select(&mut app.session.selection, Some(*id), mods); - app.graph.drag = Some(GraphDrag::Nodes { delta: Vec2::ZERO }); - } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { - let resize = hit.grip.contains(p); - let contents = app - .session - .graph() - .ok() - .and_then(|graph| { - graph.frames.iter().find(|frame| frame.id == hit.id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame)) - }) - .unwrap_or_default(); - app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); - app.graph.drag = Some(GraphDrag::Frame { id: hit.id, delta: Vec2::ZERO, resize, contents }); - } else { - app.graph.drag = Some(GraphDrag::Box { start: p }); - } - } - } - - // Continuing gestures - match &mut app.graph.drag { - Some(GraphDrag::Pan) => { - let d = ctx.input(|i| i.pointer.delta()) / zoom; - app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; - } - Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, - Some(GraphDrag::WirePress { wire, start }) => { - // Dragged far enough: a reroute dot where the press was, carried by the pointer - if let Some(p) = pointer - && p.distance(*start) > 4.0 - { - let (wire, start) = (wire.clone(), *start); - let at = cam.to_graph(start); - app.graph.drag = None; - if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { - app.graph.drag = Some(GraphDrag::Nodes { delta: (p - start) / zoom }); - } - } - } - _ => {} - } - - // Ending gestures - let ended = released && !primary_down && !middle_down; - if ended && let Some(drag) = app.graph.drag.take() { - match drag { - GraphDrag::Pan => {} - GraphDrag::WirePress { wire, .. } => { - app.session.selection.clear(); - let sel = &mut app.graph.selected_wires; - if mods.ctrl && sel.contains(&wire) { - // Ctrl+click toggles a wire out of the selection - sel.retain(|w| *w != wire); - } else if mods.ctrl || mods.shift { - if !sel.contains(&wire) { - sel.push(wire); - } - } else { - *sel = vec![wire]; - } - } - GraphDrag::Nodes { delta } => { - if delta.length() > 0.5 { - app.run("graph.node.move", json!({"by": [delta.x, delta.y]})); - } - } - GraphDrag::Box { start } => { - if let Some(p) = pointer { - let r = Rect::from_two_pos(start, p); - if r.width() > 3.0 || r.height() > 3.0 { - let hit: Vec<NodeId> = app.graph.rects.iter().filter(|(_, nr)| r.intersects(*nr)).map(|(id, _)| *id).collect(); - if mods.ctrl || mods.shift { - for id in hit { - if !app.session.selection.contains(&id) { - app.session.selection.push(id); - } - } - } else { - app.session.selection = hit; - } - } else { - super::node_selection::select(&mut app.session.selection, None, mods); - } - } - } - GraphDrag::Wire { from, detached } => { - let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); - match target { - Some(t) => { - let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); - if let Some((node, port)) = detached { - parameters["detach"] = json!({"to": node.0, "toPort": port}); - } - - app.run("graph.connect", parameters); - } - None => { - if let Some((n, p)) = &detached { - app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); - } else if let Some(p) = pointer - && rect.contains(p) - { - open_search(app, cam.to_graph(p), Some(from)); - } - } - } - } - GraphDrag::Frame { id, delta, resize, .. } => { - if delta.length() > 0.5 { - if resize { - if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) { - let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y]; - app.run("graph.frame.edit", json!({"id": id, "rect": rect})); - } - } else { - app.run("graph.frame.move", json!({"id": id, "by": [delta.x, delta.y]})); - } - } - } - GraphDrag::Comment { id, delta } => { - if delta.length() > 0.5 - && let Some(c) = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == id)).cloned() - { - app.run("graph.comment.edit", json!({"id": id, "at": [c.pos[0] + delta.x, c.pos[1] + delta.y]})); - } - } - } - } - - // Clicks - for (id, r) in nodes { - if r.double_clicked() { - let def = app.session.graph().ok().and_then(|g| g.node(*id).ok()).map(|n| (n.def.clone(), n.params.get("graph").cloned())); - match def { - Some((d, Some(Value::Text(name)))) if d == "graph_instance" => { - app.run("graph.open", json!({"graph": name})); - } - Some((d, _)) if d == "pixel_processor" || d == "value_processor" => { - app.run("view.2d", json!({"node": id.0, "port": 0})); - app.function_editor = Some(crate::function::FunctionEditor::new(*id, crate::function::FunctionTarget::Parameter("function".into()))); - } - _ => { - app.run("view.2d", json!({"node": id.0, "port": 0})); - } - } - } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { - // Keep the current output when deselecting or clicking the node already shown - app.run("view.2d", json!({"node": id.0})); - } - if r.secondary_clicked() - && let Some(pointer) = pointer - { - app.graph.menu_at = cam.to_graph(pointer); - } - - let at = app.graph.menu_at; - r.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); - } - if let Some(h) = &port_hover - && h.output - && ctx.input(|i| i.pointer.primary_clicked()) - { - let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); - app.run("view.2d", json!({"node": h.node.0, "port": idx})); - } - let on_node = pointer.is_some_and(|p| { - nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)) || frames.iter().any(|frame| frame.contains(p)) - }); - if canvas.double_clicked() - && !on_node - && let Some(p) = pointer - { - match &wire_hover { - // Double-click a wire: a reroute dot there - Some(w) => { - let at = cam.to_graph(p); - app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); - app.graph.selected_wires.clear(); - } - None => open_search(app, cam.to_graph(p), None), - } - } - if canvas.secondary_clicked() - && let Some(p) = pointer - { - app.graph.menu_at = cam.to_graph(p); - if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { - app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); - } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { - app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); - } - app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); - // Right-clicking a selected wire keeps the selection (to swap or delete them all) - if let Some(w) = &app.graph.menu_wire - && !app.graph.selected_wires.contains(w) - { - app.session.selection.clear(); - app.graph.selected_wires = vec![w.clone()]; - } - } - let at = app.graph.menu_at; - canvas.context_menu(|ui| match app.graph.menu_wire.clone() { - Some(w) => wire_menu(app, ui, w, at), - None => super::context_menu::show(app, ui, at, None), - }); - - // Library drops - if let Some(payload) = canvas.dnd_release_payload::<LibraryDrag>() - && let Some(p) = pointer - { - let gp = cam.to_graph(p); - let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; - match payload.0.strip_prefix('@') { - Some(graph) => app.run("graph.node.add", json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})), - None => app.run("graph.node.add", json!({"def": payload.0, "at": at})), - }; - } - - // Keys over the canvas - let hovered = pointer.is_some_and(|p| rect.contains(p)); - if hovered && app.graph.search.is_none() { - let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); - let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); - if (space || tab) - && let Some(p) = pointer - { - open_search(app, cam.to_graph(p), None); - } - if !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::F) && i.modifiers.is_none()) { - let sel = !app.session.selection.is_empty(); - frame(app, rect, sel); - } - } -} - -fn open_search(app: &mut MaterialCraftApp, at: Pos2, connect: Option<(NodeId, String)>) { - app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, focus: true }); -} - -/// Catalog entries matching `text` (label or id contains every word) -fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDefinition> { - let words: Vec<String> = text.split_whitespace().map(str::to_ascii_lowercase).collect(); - let mut v: Vec<_> = materialcraft_engine::nodes::catalog() - .iter() - .filter(|d| d.id != "graph_instance") - .filter(|d| { - let hay = format!("{} {} {}", d.label.to_ascii_lowercase(), d.id, d.category.to_ascii_lowercase()); - words.iter().all(|w| hay.contains(w.as_str())) - }) - .collect(); - if let Some(w) = words.first() { - v.sort_by_key(|d| !d.label.to_ascii_lowercase().starts_with(w.as_str())); - } - v -} - -fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { - let Some(s) = app.graph.search.as_mut() else { return }; - let tk = Tokens::get(ui.ctx()); - let screen = cam.to_screen(s.at); - let mut close = false; - let mut pick: Option<&'static str> = None; - egui::Area::new(egui::Id::unique("node-search")).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { - ui.set_width(260.0); - ui.horizontal(|ui| { - ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - let r = ui.add(egui::TextEdit::singleline(&mut s.text).hint_text(tr("Search nodes...")).desired_width(220.0)); - crate::widgets::name(&r, egui::Role::SearchInput, "Search nodes"); - if s.focus { - r.request_focus(); - s.focus = false; - } - if r.changed() { - s.sel = 0; - } - }); - let list = matches(&s.text); - let (up, down, enter, esc) = ui.input(|i| { - (i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)) - }); - if down { - s.sel = (s.sel + 1).min(list.len().saturating_sub(1)); - } - if up { - s.sel = s.sel.saturating_sub(1); - } - if esc { - close = true; - } - if enter && let Some(d) = list.get(s.sel) { - pick = Some(d.id); - } - egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { - for (i, d) in list.iter().enumerate().take(60) { - let r = ui.add( - egui::Button::selectable(i == s.sel, format!("{} ", d.label)) - .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), - ); - if i == s.sel && (up || down) { - r.scroll_to_me(None); - } - if r.clicked() { - pick = Some(d.id); - } - } - if list.is_empty() { - ui.label(egui::RichText::new(tr("No matching node")).color(tk.text_dim)); - } - }); - }); - }); - let clicked_out = ui.input(|i| i.pointer.any_pressed()) - && ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == egui::Id::unique("node-search"))); - if let Some(def) = pick { - let s = app.graph.search.take(); - if let Some(s) = s { - let mut p = json!({"def": def, "at": [s.at.x, s.at.y - 20.0]}); - if let Some((n, port)) = s.connect { - p["connectFrom"] = json!({"node": n.0, "port": port}); - } - app.run("graph.node.add", p); - } - } else if close || clicked_out { - app.graph.search = None; - } -} - -/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands -fn wires_json(wires: &[WireRef]) -> serde_json::Value { - json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()}) -} - -/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none is selected -pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { - let wires = std::mem::take(&mut app.graph.selected_wires); - if wires.is_empty() { - return false; - } - app.run("graph.wire.delete", wires_json(&wires)); - true -} - -/// Reverse the sources of selected wires so pressing X again restores them -pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { - if app.graph.selected_wires.is_empty() { - return false; - } - let params = wires_json(&app.graph.selected_wires); - app.run("graph.wire.swap", params); - true -} - -fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) { - let n = app.graph.selected_wires.len(); - if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() { - app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]})); - app.graph.selected_wires.clear(); - ui.close(); - } - if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() { - swap_selected_wires(app); - ui.close(); - } - let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") }; - if ui.button(format!("{} {label}", icon::TRASH)).clicked() { - if n < 2 { - app.graph.selected_wires = vec![(to, port)]; - } - delete_selected_wires(app); - ui.close(); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use super::super::frames::Frames; - - /// Three primitive nodes framed on screen - fn three_nodes() -> (Frames, [NodeId; 3]) { - let mut s = materialcraft_engine::sample_session(); - materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); - let ids = ["uniform", "uniform", "channels_shuffle"].iter().enumerate().map(|(i, def)| { - let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); - NodeId(added["id"].as_u64().unwrap()) - }); - let ids: [NodeId; 3] = ids.collect::<Vec<_>>().try_into().unwrap(); - s.selection.clear(); - (Frames::new(s), ids) - } - - #[test] - fn clicking_a_node_shows_it_in_the_2d_view() { - let (mut f, [noise, checker, _]) = three_nodes(); - // Shown explicitly first (a double-click, an output port or "View in 2D view") - f.app.run("view.2d", json!({"node": noise.0})); - assert_eq!(f.shown(), Some(noise)); - let at = f.center(checker); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.app.session.view2d.node, Some(checker)); - assert_eq!(f.shown(), Some(checker)); - // And back - let at = f.center(noise); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.view2d.node, Some(noise)); - assert_eq!(f.shown(), Some(noise)); - // Ctrl+click adds a node to the selection and shows it too - let at = f.center(checker); - f.click(at, egui::Modifiers::CTRL); - assert_eq!(f.app.session.selection, vec![noise, checker]); - assert_eq!(f.shown(), Some(checker)); - } - - #[test] - fn ctrl_click_that_deselects_a_node_does_not_show_it() { - let (mut f, [noise, checker, _]) = three_nodes(); - f.app.session.selection = vec![noise, checker]; - f.app.run("view.2d", json!({"node": checker.0})); - let at = f.center(noise); - f.click(at, egui::Modifiers::CTRL); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.shown(), Some(checker)); - } - - #[test] - fn dragging_a_node_keeps_the_2d_view() { - let (mut f, [noise, checker, _]) = three_nodes(); - f.app.run("view.2d", json!({"node": noise.0})); - let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; - let from = f.center(checker); - let none = egui::Modifiers::NONE; - f.run(vec![egui::Event::PointerMoved(from)], none); - f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); - for step in 1..=8 { - f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); - } - let to = from + vec2(40.0, 0.0); - f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); - let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; - let moved = 40.0 / f.app.ui.graph_camera.zoom; - assert_eq!(after, materialcraft_engine::graph_grid::snap_position([before[0] + moved, before[1]], true)); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.shown(), Some(noise)); - } - - #[test] - fn clicking_the_shown_node_keeps_its_port() { - let (mut f, [_, _, split]) = three_nodes(); - f.app.run("view.2d", json!({"node": split.0, "port": 2})); - let at = f.center(split); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.selection, vec![split]); - assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); - } - - #[test] - fn tab_opens_search_in_the_full_workspace() { - let mut f = Frames::new(materialcraft_engine::sample_session()); - let pointer = f.app.graph.view.center(); - let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); - assert!(f.app.graph.search.is_some()); - } - - #[test] - fn clicked_wires_swap_with_x_and_delete_together() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - app.run("file.new", json!({"template": "empty"})); - let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap(); - let a = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, -150]}))); - let b = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, 150]}))); - let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); - app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); - app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); - let ctx = egui::Context::default(); - let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| { - events.insert(0, egui::Event::ModifiersChanged(modifiers)); - let input = egui::RawInput { events, ..Default::default() }; - ctx.run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - }; - - for _ in 0..3 { - frame(&mut app, Vec::new(), egui::Modifiers::NONE); - } - let mid = - |app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap(); - let click = - |app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec<egui::Event>, egui::Modifiers), port: &str, m: egui::Modifiers| { - let p = mid(app, port); - let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; - frame(app, vec![egui::Event::PointerMoved(p)], m); - frame(app, vec![button(true)], m); - frame(app, vec![button(false)], m); - }; - - click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE); - click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT); - assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires); - let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; - frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); - assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a)); - // Still selected: X again swaps back - frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); - assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b)); - frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE); - assert!(app.session.graph().unwrap().connections.is_empty()); - assert!(app.graph.selected_wires.is_empty()); - } - - #[test] - fn node_search_shortcuts_respect_hover_and_keyboard_focus() { - for key in [egui::Key::Space, egui::Key::Tab] { - for (hovered, editing) in [(true, false), (false, false), (true, true)] { - let ctx = egui::Context::default(); - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - let mut text = String::new(); - let mut draw = |ui: &mut Ui| { - if editing { - ui.text_edit_singleline(&mut text).request_focus(); - } - app.graph.keyboard_was_focused = ui.ctx().egui_wants_keyboard_input(); - show(&mut app, ui); - }; - - ctx.run_ui(egui::RawInput::default(), &mut draw).textures_delta.clear(); - let pointer = if hovered { pos2(200.0, 200.0) } else { pos2(-10.0, -10.0) }; - let input = egui::RawInput { - events: vec![ - egui::Event::PointerMoved(pointer), - egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - ], - ..Default::default() - }; - - ctx.run_ui(input, &mut draw).textures_delta.clear(); - assert_eq!(app.graph.search.is_some(), hovered && !editing, "{key:?}: hovered={hovered}, editing={editing}"); - if let Some(search) = &app.graph.search { - let cam = GraphCamera { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; - assert_eq!(search.at, cam.to_graph(pointer)); - assert!(search.text.is_empty()); - } - } - } - } - - #[test] - fn search_finds_by_label_and_category() { - assert!(matches("uniform").iter().any(|d| d.id == "uniform")); - assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); - assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); - assert!(matches("zzzz").is_empty()); - } - - #[test] - fn wires_are_hit_near_their_curve_only() { - let a = (NodeId(1), "input".to_string()); - let b = (NodeId(2), "input".to_string()); - let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))]; - // The midpoint of a symmetric wire lies on the line between its ends - let mid = bezier_at(&wires[0].1, 0.5); - assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}"); - assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a)); - assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b)); - assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None); - assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None); - // The ends are on the wire - assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); - assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); - } - - #[test] - fn port_positions_stay_on_the_card() { - let n = Node::new(NodeId(1), "blend", [0.0, 0.0]); - let r = node_rect(&n, 3, 1, true); - for i in 0..3 { - let p = port_pos(r, i, 3, false, false); - assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); - assert!(p.y > r.top() + node_card::HEADER_HEIGHT && p.y < r.bottom() - node_card::FOOTER_HEIGHT); - } + painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), theme.warning); } } diff --git a/crates/ui-egui/src/graph/canvas_geometry.rs b/crates/ui-egui/src/graph/canvas_geometry.rs new file mode 100644 index 00000000..c5a88ef8 --- /dev/null +++ b/crates/ui-egui/src/graph/canvas_geometry.rs @@ -0,0 +1,19 @@ +use super::{GraphView, PortHit, WireRef}; +use egui::{Pos2, Rect}; +use materialcraft_engine::core::NodeId; + +#[derive(Default)] +pub(crate) struct CanvasGeometry { + pub rects: Vec<(NodeId, Rect)>, + pub ports: Vec<PortHit>, + pub wires: Vec<(WireRef, [Pos2; 4])>, +} + +impl CanvasGeometry { + pub fn publish(self, view: &mut GraphView, bounds: Rect) { + view.view = bounds; + view.rects = self.rects; + view.ports = self.ports; + view.wires = self.wires; + } +} diff --git a/crates/ui-egui/src/graph/canvas_tests.rs b/crates/ui-egui/src/graph/canvas_tests.rs new file mode 100644 index 00000000..5462b88f --- /dev/null +++ b/crates/ui-egui/src/graph/canvas_tests.rs @@ -0,0 +1,221 @@ +use super::canvas::*; +use super::node_card::port as port_pos; +use super::search::matches; +use super::wire_geometry::{WIRE_HIT, bezier_at, bezier_distance, bezier_points, wire_at}; +use super::{GraphCamera, node_card, node_rect}; +use crate::MaterialCraftApp; +use egui::{Ui, Vec2, pos2, vec2}; +use materialcraft_engine::core::{Node, NodeId}; +use serde_json::json; + +use super::frames::Frames; + +/// Three primitive nodes framed on screen +fn three_nodes() -> (Frames, [NodeId; 3]) { + let mut s = materialcraft_engine::sample_session(); + materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); + let ids = ["uniform", "uniform", "channels_shuffle"].iter().enumerate().map(|(i, def)| { + let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); + NodeId(added["id"].as_u64().unwrap()) + }); + let ids: [NodeId; 3] = ids.collect::<Vec<_>>().try_into().unwrap(); + s.selection.clear(); + (Frames::new(s), ids) +} + +#[test] +fn clicking_a_node_shows_it_in_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + // Shown explicitly first (a double-click, an output port or "View in 2D view") + f.app.run("view.2d", json!({"node": noise.0})); + assert_eq!(f.shown(), Some(noise)); + let at = f.center(checker); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.app.session.view2d.node, Some(checker)); + assert_eq!(f.shown(), Some(checker)); + // And back + let at = f.center(noise); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.view2d.node, Some(noise)); + assert_eq!(f.shown(), Some(noise)); + // Ctrl+click adds a node to the selection and shows it too + let at = f.center(checker); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![noise, checker]); + assert_eq!(f.shown(), Some(checker)); +} + +#[test] +fn ctrl_click_that_deselects_a_node_does_not_show_it() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.session.selection = vec![noise, checker]; + f.app.run("view.2d", json!({"node": checker.0})); + let at = f.center(noise); + f.click(at, egui::Modifiers::CTRL); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(checker)); +} + +#[test] +fn dragging_a_node_keeps_the_2d_view() { + let (mut f, [noise, checker, _]) = three_nodes(); + f.app.run("view.2d", json!({"node": noise.0})); + let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let from = f.center(checker); + let none = egui::Modifiers::NONE; + f.run(vec![egui::Event::PointerMoved(from)], none); + f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); + for step in 1..=8 { + f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); + } + let to = from + vec2(40.0, 0.0); + f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); + let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; + let moved = 40.0 / f.app.ui.graph_camera.zoom; + assert_eq!(after, materialcraft_engine::graph_grid::snap_position([before[0] + moved, before[1]], true)); + assert_eq!(f.app.session.selection, vec![checker]); + assert_eq!(f.shown(), Some(noise)); +} + +#[test] +fn clicking_the_shown_node_keeps_its_port() { + let (mut f, [_, _, split]) = three_nodes(); + f.app.run("view.2d", json!({"node": split.0, "port": 2})); + let at = f.center(split); + f.click(at, egui::Modifiers::NONE); + assert_eq!(f.app.session.selection, vec![split]); + assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); +} + +#[test] +fn tab_opens_search_in_the_full_workspace() { + let mut f = Frames::new(materialcraft_engine::sample_session()); + let pointer = f.app.graph.view.center(); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); + assert!(f.app.graph.search.is_some()); +} + +#[test] +fn clicked_wires_swap_with_x_and_delete_together() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.run("file.new", json!({"template": "empty"})); + let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap(); + let a = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, -150]}))); + let b = id(app.run("graph.node.add", json!({"def": "uniform", "at": [0, 150]}))); + let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); + app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); + app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); + let ctx = egui::Context::default(); + let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| { + events.insert(0, egui::Event::ModifiersChanged(modifiers)); + let input = egui::RawInput { events, ..Default::default() }; + ctx.run_ui(input, |ui| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }) + .textures_delta + .clear(); + }; + + for _ in 0..3 { + frame(&mut app, Vec::new(), egui::Modifiers::NONE); + } + let mid = |app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap(); + let click = + |app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec<egui::Event>, egui::Modifiers), port: &str, m: egui::Modifiers| { + let p = mid(app, port); + let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; + frame(app, vec![egui::Event::PointerMoved(p)], m); + frame(app, vec![button(true)], m); + frame(app, vec![button(false)], m); + }; + + click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE); + click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT); + assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires); + let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; + frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); + assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a)); + // Still selected: X again swaps back + frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); + assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b)); + frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE); + assert!(app.session.graph().unwrap().connections.is_empty()); + assert!(app.graph.selected_wires.is_empty()); +} + +#[test] +fn node_search_shortcuts_respect_hover_and_keyboard_focus() { + for key in [egui::Key::Space, egui::Key::Tab] { + for (hovered, editing) in [(true, false), (false, false), (true, true)] { + let ctx = egui::Context::default(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + let mut text = String::new(); + let mut draw = |ui: &mut Ui| { + if editing { + ui.text_edit_singleline(&mut text).request_focus(); + } + app.graph.keyboard_was_focused = ui.ctx().egui_wants_keyboard_input(); + show(&mut app, ui); + }; + + ctx.run_ui(egui::RawInput::default(), &mut draw).textures_delta.clear(); + let pointer = if hovered { pos2(200.0, 200.0) } else { pos2(-10.0, -10.0) }; + + let input = egui::RawInput { + events: vec![ + egui::Event::PointerMoved(pointer), + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, + ], + ..Default::default() + }; + + ctx.run_ui(input, &mut draw).textures_delta.clear(); + assert_eq!(app.graph.search.is_some(), hovered && !editing, "{key:?}: hovered={hovered}, editing={editing}"); + if let Some(search) = &app.graph.search { + let cam = GraphCamera { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; + assert_eq!(search.at, cam.to_graph(pointer)); + assert!(search.text.is_empty()); + } + } + } +} + +#[test] +fn search_finds_by_label_and_category() { + assert!(matches("uniform").iter().any(|d| d.id == "uniform")); + assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); + assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); + assert!(matches("zzzz").is_empty()); +} + +#[test] +fn wires_are_hit_near_their_curve_only() { + let a = (NodeId(1), "input".to_string()); + let b = (NodeId(2), "input".to_string()); + let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))]; + // The midpoint of a symmetric wire lies on the line between its ends + let mid = bezier_at(&wires[0].1, 0.5); + assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}"); + assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a)); + assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b)); + assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None); + assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None); + // The ends are on the wire + assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); + assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); +} + +#[test] +fn port_positions_stay_on_the_card() { + let n = Node::new(NodeId(1), "blend", [0.0, 0.0]); + let r = node_rect(&n, 3, 1, true); + for i in 0..3 { + let p = port_pos(r, i, 3, false, false); + assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); + assert!(p.y > r.top() + node_card::HEADER_HEIGHT && p.y < r.bottom() - node_card::FOOTER_HEIGHT); + } +} diff --git a/crates/ui-egui/src/graph/context_menu.rs b/crates/ui-egui/src/graph/context_menu.rs index ab305ff2..194d0404 100644 --- a/crates/ui-egui/src/graph/context_menu.rs +++ b/crates/ui-egui/src/graph/context_menu.rs @@ -31,31 +31,24 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2, node: Opti action(app, ui, "Add Dot node", "graph.node.add", json!({"def": "dot", "at": [at.x, at.y]})); ui.separator(); - action(app, ui, "View outputs in 3D view", "ui.graph.viewOutputs", Value::Null); - action(app, ui, "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", Value::Null); + if let Some(node) = node { + if let Some(parameters) = crate::material_preview_menu::show(ui, &app.session, app.session.graph, node) { + app.run("view.3d.assign", parameters); + } + } else { + action(app, ui, "View outputs in 3D view", "ui.graph.viewOutputs", Value::Null); + action(app, ui, "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", Value::Null); + } outputs(app, ui, node); action(app, ui, "Compute nodes thumbnails", "ui.graph.computeThumbnails", Value::Null); action(app, ui, "Clear nodes thumbnails", "ui.graph.clearThumbnails", Value::Null); action(app, ui, "Save package", "file.save", Value::Null); - action(app, ui, "Paste", "edit.paste", json!({"at": [at.x, at.y]})); - action(app, ui, "Paste without link", "edit.pasteWithoutLinks", json!({"at": [at.x, at.y]})); - action(app, ui, "Select all", "edit.selectAll", Value::Null); + if let Some(command) = super::edit_menu::selection(ui, |command| menus::enabled(app, command)) { + let parameters = if matches!(command, "edit.paste" | "edit.pasteWithoutLinks") { json!({"at": [at.x, at.y]}) } else { Value::Null }; + app.run(command, parameters); + } action(app, ui, "Previous pin", "ui.graph.previousPin", Value::Null); action(app, ui, "Next pin", "ui.graph.nextPin", Value::Null); - ui.separator(); - - for (label, command) in [ - ("Copy selection", "edit.copy"), - ("Delete selection", "edit.delete"), - ("Delete and relink", "edit.deleteRelink"), - ("Duplicate selection", "edit.duplicate"), - ("Duplicate selection without link", "edit.duplicateWithoutLinks"), - ("Select upstream nodes", "graph.selectUpstream"), - ("Select downstream nodes", "graph.selectDownstream"), - ("Disable selection", "graph.node.disable"), - ] { - action(app, ui, label, command, Value::Null); - } } fn add_nodes(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { @@ -101,12 +94,7 @@ fn outputs(app: &mut MaterialCraftApp, ui: &mut Ui, node: Option<NodeId>) { } fn action(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, command: &str, parameters: Value) { - let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { - button = button.shortcut_text(shortcut); - } - - if ui.add_enabled(menus::enabled(app, command), button).clicked() { + if super::edit_menu::button(ui, label, command, menus::enabled(app, command)) { if command.starts_with("ui.") || matches!(command, "file.save" | "graph.node.edit") { menus::invoke(app, ui.ctx(), command); } else { diff --git a/crates/ui-egui/src/graph/edit_menu.rs b/crates/ui-egui/src/graph/edit_menu.rs new file mode 100644 index 00000000..b419bc8b --- /dev/null +++ b/crates/ui-egui/src/graph/edit_menu.rs @@ -0,0 +1,40 @@ +use crate::{i18n::tr, menus}; +use egui::Ui; + +pub(crate) fn button(ui: &mut Ui, label: &str, command: &str, enabled: bool) -> bool { + let mut button = egui::Button::new(tr(label)); + if let Some(shortcut) = menus::shortcut_of(command) { + button = button.shortcut_text(shortcut); + } + let clicked = ui.add_enabled(enabled, button).clicked(); + if clicked { + ui.close(); + } + clicked +} + +pub(crate) fn selection(ui: &mut Ui, enabled: impl Fn(&str) -> bool) -> Option<&'static str> { + let mut chosen = None; + for (label, command) in [ + ("Paste", "edit.paste"), + ("Paste without link", "edit.pasteWithoutLinks"), + ("Select all", "edit.selectAll"), + ("Copy selection", "edit.copy"), + ("Cut selection", "edit.cut"), + ("Delete selection", "edit.delete"), + ("Delete and relink", "edit.deleteRelink"), + ("Duplicate selection", "edit.duplicate"), + ("Duplicate selection without link", "edit.duplicateWithoutLinks"), + ("Select upstream nodes", "graph.selectUpstream"), + ("Select downstream nodes", "graph.selectDownstream"), + ("Disable selection", "graph.node.disable"), + ] { + if command == "edit.copy" { + ui.separator(); + } + if button(ui, label, command, enabled(command)) { + chosen = Some(command); + } + } + chosen +} diff --git a/crates/ui-egui/src/graph/editor_actions.rs b/crates/ui-egui/src/graph/editor_actions.rs new file mode 100644 index 00000000..d1ffcc3b --- /dev/null +++ b/crates/ui-egui/src/graph/editor_actions.rs @@ -0,0 +1,25 @@ +use super::editor_target::EditorTarget; +use crate::MaterialCraftApp; + +pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { + if command == "ui.graph.parent" { + return Some(super::subgraph_navigation::can_return(app)); + } + match EditorTarget::resolve(app) { + EditorTarget::Function => crate::function::enabled(app, command), + EditorTarget::Pattern => crate::pattern::enabled(app, command), + EditorTarget::Material => None, + } +} + +pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { + if command == "ui.graph.parent" { + super::subgraph_navigation::parent(app); + return true; + } + match EditorTarget::resolve(app) { + EditorTarget::Function => crate::function::invoke(app, command), + EditorTarget::Pattern => crate::pattern::invoke(app, command), + EditorTarget::Material => false, + } +} diff --git a/crates/ui-egui/src/graph/editor_target.rs b/crates/ui-egui/src/graph/editor_target.rs new file mode 100644 index 00000000..18f7b31f --- /dev/null +++ b/crates/ui-egui/src/graph/editor_target.rs @@ -0,0 +1,31 @@ +use crate::{MaterialCraftApp, function::FunctionTarget}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EditorTarget { + Material, + Function, + Pattern, +} + +impl EditorTarget { + pub(crate) fn annotation_active(app: &MaterialCraftApp) -> bool { + app.session.annotation_selection.is_some() + && match Self::resolve(app) { + Self::Material => true, + Self::Function => app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph)), + Self::Pattern => false, + } + } + + pub(crate) fn resolve(app: &MaterialCraftApp) -> Self { + if app.function_editor.as_ref().is_some_and(|editor| editor.current(app).is_some()) { + Self::Function + } else if crate::pattern::active(app) { + Self::Pattern + } else if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { + Self::Function + } else { + Self::Material + } + } +} diff --git a/crates/ui-egui/src/graph/gesture.rs b/crates/ui-egui/src/graph/gesture.rs new file mode 100644 index 00000000..94d18680 --- /dev/null +++ b/crates/ui-egui/src/graph/gesture.rs @@ -0,0 +1,13 @@ +use egui::{PointerButton, Ui}; + +pub(crate) fn pan_button(ui: &Ui) -> PointerButton { + if ui.input(|input| input.pointer.button_pressed(PointerButton::Middle)) { PointerButton::Middle } else { PointerButton::Primary } +} + +pub(crate) fn finished(ui: &Ui, owner: PointerButton) -> bool { + ui.input(|input| input.pointer.button_released(owner)) +} + +pub(crate) fn cancelled(ui: &Ui) -> bool { + ui.input(|input| !input.focused || input.key_pressed(egui::Key::Escape)) +} diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs index 7ce3c3ff..cbc75a0f 100644 --- a/crates/ui-egui/src/graph/graph_camera.rs +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -1,4 +1,4 @@ -use egui::{Pos2, Vec2}; +use egui::{Pos2, Rect, Ui, Vec2}; pub(crate) struct GraphCamera { pub(crate) origin: Pos2, @@ -7,10 +7,54 @@ pub(crate) struct GraphCamera { } impl GraphCamera { - pub(crate) fn to_screen(&self, p: Pos2) -> Pos2 { - self.origin + (p.to_vec2() - self.pan) * self.zoom + pub(crate) fn to_screen(&self, position: Pos2) -> Pos2 { + self.origin + (position.to_vec2() - self.pan) * self.zoom } - pub(crate) fn to_graph(&self, s: Pos2) -> Pos2 { - ((s - self.origin) / self.zoom + self.pan).to_pos2() + + pub(crate) fn to_graph(&self, position: Pos2) -> Pos2 { + ((position - self.origin) / self.zoom + self.pan).to_pos2() + } + + pub(crate) fn state(&self) -> crate::state::GraphCamera { + crate::state::GraphCamera { pan: self.pan.into(), zoom: self.zoom } + } + + pub(crate) fn fit(view: Rect, destination: Rect) -> Self { + if !destination.is_finite() || destination.width() <= 0.0 { + let state = crate::state::GraphCamera::default(); + return Self { origin: view.min, pan: state.pan.into(), zoom: state.zoom }; + } + + let destination = destination.expand(40.0); + let zoom = (view.width() / destination.width()).min(view.height() / destination.height()).clamp(0.1, 1.5); + let pan = destination.center().to_vec2() - view.size() * 0.5 / zoom; + Self { origin: view.min, pan, zoom } + } + + pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect) { + self.zoom = self.zoom.clamp(0.08, 4.0); + if !ui.rect_contains_pointer(view) { + return; + } + + let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|pointer| view.contains(*pointer)) else { return }; + + let scroll = ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0); + if scroll.is_finite() && scroll != 0.0 { + let before = self.to_graph(pointer); + self.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(0.08, 4.0); + self.pan = before.to_vec2() - (pointer - self.origin) / self.zoom; + } + } + + pub(crate) fn pan_started(ui: &Ui, view: Rect) -> bool { + ui.rect_contains_pointer(view) + && ui.input(|input| input.pointer.button_pressed(egui::PointerButton::Middle) || input.pointer.primary_pressed() && input.modifiers.alt) + } + + pub(crate) fn frame_key(ui: &Ui, view: Rect) -> bool { + ui.rect_contains_pointer(view) + && !ui.ctx().egui_wants_keyboard_input() + && ui.input(|input| input.key_pressed(egui::Key::F) && input.modifiers.is_none()) } } diff --git a/crates/ui-egui/src/graph/graph_drag.rs b/crates/ui-egui/src/graph/graph_drag.rs index a2db9255..d2e73bb7 100644 --- a/crates/ui-egui/src/graph/graph_drag.rs +++ b/crates/ui-egui/src/graph/graph_drag.rs @@ -19,7 +19,7 @@ pub(super) enum GraphDrag { wire: WireRef, start: Pos2, }, - Pan, + Pan(egui::PointerButton), Frame { id: u64, delta: Vec2, diff --git a/crates/ui-egui/src/graph/graph_parent.rs b/crates/ui-egui/src/graph/graph_parent.rs new file mode 100644 index 00000000..99fbf1d7 --- /dev/null +++ b/crates/ui-egui/src/graph/graph_parent.rs @@ -0,0 +1,7 @@ +use materialcraft_engine::core::NodeId; + +pub(crate) struct GraphParent { + pub graph: usize, + pub selection: Vec<NodeId>, + pub camera: crate::state::GraphCamera, +} diff --git a/crates/ui-egui/src/graph/grid.rs b/crates/ui-egui/src/graph/grid.rs new file mode 100644 index 00000000..b722fc77 --- /dev/null +++ b/crates/ui-egui/src/graph/grid.rs @@ -0,0 +1,26 @@ +use super::GraphCamera; +use egui::{Color32, Rect, Stroke, pos2}; + +pub(crate) fn paint(p: &egui::Painter, cam: &GraphCamera, rect: Rect) { + for (step, alpha) in [(materialcraft_engine::graph_grid::GRID_SPACING, 10u8), (256.0, 22)] { + let s = step * cam.zoom; + if s < 8.0 { + continue; + } + let col = Color32::from_white_alpha(alpha); + let x0 = cam.pan.x - (cam.pan.x.rem_euclid(step)); + let mut x = x0; + while cam.to_screen(pos2(x, 0.0)).x < rect.right() { + let sx = cam.to_screen(pos2(x, 0.0)).x; + p.line_segment([pos2(sx, rect.top()), pos2(sx, rect.bottom())], Stroke::new(1.0, col)); + x += step; + } + let y0 = cam.pan.y - (cam.pan.y.rem_euclid(step)); + let mut y = y0; + while cam.to_screen(pos2(0.0, y)).y < rect.bottom() { + let sy = cam.to_screen(pos2(0.0, y)).y; + p.line_segment([pos2(rect.left(), sy), pos2(rect.right(), sy)], Stroke::new(1.0, col)); + y += step; + } + } +} diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs new file mode 100644 index 00000000..9092987e --- /dev/null +++ b/crates/ui-egui/src/graph/input.rs @@ -0,0 +1,249 @@ +use super::{GraphCamera, GraphDrag, LibraryDrag, NODE_W, PortHit, WireRef}; +use super::{navigation::frame, port_hit::nearest as nearest_port, search::open_search, wire_actions::wire_menu}; +use crate::MaterialCraftApp; +use egui::{Rect, Ui, Vec2}; +use materialcraft_engine::core::NodeId; +use serde_json::json; + +#[allow(clippy::too_many_arguments)] +pub(super) fn handle( + app: &mut MaterialCraftApp, + ui: &mut Ui, + canvas: &egui::Response, + rect: Rect, + cam: &GraphCamera, + nodes: &[(NodeId, egui::Response)], + frames: &[super::frame_hit::FrameHit], + comments: &[(u64, Rect)], + port_hover: Option<PortHit>, + wire_hover: Option<WireRef>, +) { + let ctx = ui.ctx().clone(); + if super::gesture::cancelled(ui) { + app.graph.drag = None; + return; + } + let (pointer, mods, primary_pressed) = ctx.input(|input| (input.pointer.interact_pos(), input.modifiers, input.pointer.primary_pressed())); + let zoom = cam.zoom; + let motion = ctx.input(|i| i.pointer.delta()) / zoom; + + // Starting gestures (only on a press inside the canvas, with no gesture running) + if app.graph.drag.is_none() + && let Some(p) = pointer + && rect.contains(p) + && ui.rect_contains_pointer(rect) + && app.graph.search.is_none() + { + if GraphCamera::pan_started(ui, rect) { + app.graph.drag = Some(GraphDrag::Pan(super::gesture::pan_button(ui))); + } else if primary_pressed { + if app.session.annotation_selection.is_some() { + app.run("graph.annotation.select", json!({})); + } + + let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); + let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); + // Any press other than on a wire drops the wire selection + if wire.is_none() { + app.graph.selected_wires.clear(); + } + if let Some(w) = wire { + app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); + } else if let Some(h) = &port_hover { + if h.output { + app.graph.drag = Some(GraphDrag::Wire { from: (h.node, h.port.clone()), detached: None }); + } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { + app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); + } + } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { + super::annotation_input::begin_comment(app, *id); + } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { + super::node_selection::select(&mut app.session.selection, Some(*id), mods); + app.graph.drag = Some(GraphDrag::Nodes { delta: Vec2::ZERO }); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + super::annotation_input::begin_frame(app, hit.id, hit.grip.contains(p)); + } else { + app.graph.drag = Some(GraphDrag::Box { start: p }); + } + } + } + + // Continuing gestures + match &mut app.graph.drag { + Some(GraphDrag::Pan(_)) => { + let d = ctx.input(|i| i.pointer.delta()) / zoom; + app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; + } + Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, + Some(GraphDrag::WirePress { wire, start }) => { + // Dragged far enough: a reroute dot where the press was, carried by the pointer + if let Some(p) = pointer + && p.distance(*start) > 4.0 + { + let (wire, start) = (wire.clone(), *start); + let at = cam.to_graph(start); + app.graph.drag = None; + if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { + app.graph.drag = Some(GraphDrag::Nodes { delta: (p - start) / zoom }); + } + } + } + _ => {} + } + + // Ending gestures + let owner = match app.graph.drag { + Some(GraphDrag::Pan(button)) => button, + _ => egui::PointerButton::Primary, + }; + let ended = super::gesture::finished(ui, owner); + if ended && let Some(drag) = app.graph.drag.take() { + match drag { + GraphDrag::Pan(_) => {} + GraphDrag::WirePress { wire, .. } => { + app.session.selection.clear(); + let sel = &mut app.graph.selected_wires; + if mods.ctrl && sel.contains(&wire) { + // Ctrl+click toggles a wire out of the selection + sel.retain(|w| *w != wire); + } else if mods.ctrl || mods.shift { + if !sel.contains(&wire) { + sel.push(wire); + } + } else { + *sel = vec![wire]; + } + } + GraphDrag::Nodes { delta } => { + if delta.length() > 0.5 { + app.run("graph.node.move", json!({"by": [delta.x, delta.y]})); + } + } + GraphDrag::Box { start } => { + if let Some(p) = pointer { + super::node_selection::select_box(&mut app.session.selection, app.graph.rects.iter().copied(), start, p, mods); + } + } + GraphDrag::Wire { from, detached } => { + let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); + match target { + Some(t) => { + let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); + if let Some((node, port)) = detached { + parameters["detach"] = json!({"to": node.0, "toPort": port}); + } + + app.run("graph.connect", parameters); + } + None => { + if let Some((n, p)) = &detached { + app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); + } else if let Some(p) = pointer + && rect.contains(p) + { + open_search(app, cam.to_graph(p), Some(from)); + } + } + } + } + GraphDrag::Frame { .. } | GraphDrag::Comment { .. } => super::annotation_input::finish(app, drag), + } + } + + // Clicks + for (id, r) in nodes { + if r.double_clicked() { + app.run("view.2d", json!({"node": id.0, "port": 0})); + if crate::menus::enabled(app, "graph.node.edit") { + crate::menus::invoke(app, ui.ctx(), "graph.node.edit"); + } + } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { + // Keep the current output when deselecting or clicking the node already shown + app.run("view.2d", json!({"node": id.0})); + } + if r.secondary_clicked() + && let Some(pointer) = pointer + { + app.graph.menu_at = cam.to_graph(pointer); + } + + let at = app.graph.menu_at; + r.context_menu(|ui| super::context_menu::show(app, ui, at, Some(*id))); + } + if let Some(h) = &port_hover + && h.output + && ui.rect_contains_pointer(rect) + && ctx.input(|i| i.pointer.primary_clicked()) + { + let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); + app.run("view.2d", json!({"node": h.node.0, "port": idx})); + } + let on_node = pointer.is_some_and(|p| { + nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)) || frames.iter().any(|frame| frame.contains(p)) + }); + if canvas.double_clicked() + && !on_node + && let Some(p) = pointer + { + match &wire_hover { + // Double-click a wire: a reroute dot there + Some(w) => { + let at = cam.to_graph(p); + app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); + app.graph.selected_wires.clear(); + } + None => open_search(app, cam.to_graph(p), None), + } + } + if canvas.secondary_clicked() + && let Some(p) = pointer + { + app.graph.menu_at = cam.to_graph(p); + if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); + } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { + app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); + } + app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); + // Right-clicking a selected wire keeps the selection (to swap or delete them all) + if let Some(w) = &app.graph.menu_wire + && !app.graph.selected_wires.contains(w) + { + app.session.selection.clear(); + app.graph.selected_wires = vec![w.clone()]; + } + } + let at = app.graph.menu_at; + canvas.context_menu(|ui| match app.graph.menu_wire.clone() { + Some(w) => wire_menu(app, ui, w, at), + None => super::context_menu::show(app, ui, at, None), + }); + + // Library drops + if let Some(payload) = crate::widgets::dnd_release::<LibraryDrag>(canvas) + && let Some(p) = pointer + { + let gp = cam.to_graph(p); + let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; + match payload.0.strip_prefix('@') { + Some(graph) => app.run("graph.node.add", json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})), + None => app.run("graph.node.add", json!({"def": payload.0, "at": at})), + }; + } + + // Keys over the canvas + let hovered = pointer.is_some_and(|p| rect.contains(p)); + if hovered && app.graph.search.is_none() { + let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); + let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); + if (space || tab) + && let Some(p) = pointer + { + open_search(app, cam.to_graph(p), None); + } + if GraphCamera::frame_key(ui, rect) { + let sel = !app.session.selection.is_empty(); + frame(app, rect, sel); + } + } +} diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index f3d93270..7cf5cd2b 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -468,3 +468,65 @@ fn every_canvas_keeps_properties_after_deselection() { } } } + +#[test] +fn box_selection_and_alt_panning_are_shared_by_every_canvas() { + use materialcraft_engine::core::{FunctionGraph, PatternGraph, PatternNodeKind, Value}; + + for kind in ["material", "function", "pattern"] { + let mut frames = Frames::new(new_session()); + match kind { + "function" => { + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for x in [0.0, 320.0] { + graph.add("get_float1", &[], Some(Value::Text("value".into()))); + graph.nodes.last_mut().unwrap().pos = [x, 0.0]; + } + frames.app.run("graph.function.set", json!({"function": graph})).unwrap(); + } + "pattern" => { + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::default(); + for x in [0.0, 320.0] { + graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes.last_mut().unwrap().position = [x, 0.0]; + } + frames.app.run("graph.pattern.set", json!({"id": owner.0, "pattern": graph})).unwrap(); + frames.app.pattern_editor = Some(crate::pattern::PatternEditor::new(frames.app.session.graph, owner)); + } + _ => { + for x in [0, 320] { + frames.app.run("graph.node.add", json!({"def": "uniform", "at": [x, 0]})).unwrap(); + } + } + } + if kind == "function" { + frames.app.run("graph.frame.add", json!({"rect": [-256, 256, 240, 100]})).unwrap(); + } + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let bounds = frames.app.graph.rects.iter().fold(egui::Rect::NOTHING, |bounds, (_, rect)| bounds.union(*rect)).expand(12.0); + drag(&mut frames, bounds.min, bounds.max); + let selection_count = match kind { + "function" => frames.app.function_editor.as_ref().unwrap().selection.len(), + "pattern" => frames.app.pattern_editor.as_ref().unwrap().selection.len(), + _ => frames.app.session.selection.len(), + }; + assert_eq!(selection_count, 2, "{kind} box selection"); + + let before = frames.app.graph.rects[0].1.center(); + let from = frames.app.graph.view.left_bottom() + vec2(20.0, -20.0); + let to = from + vec2(30.0, -20.0); + frames.run(vec![Event::PointerMoved(from)], Modifiers::ALT); + frames.run(vec![Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }], Modifiers::ALT); + frames.run(vec![Event::PointerMoved(to)], Modifiers::ALT); + frames.run(vec![Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }], Modifiers::ALT); + frames.run(Vec::new(), Modifiers::NONE); + let after = frames.app.graph.rects[0].1.center(); + assert!((after - before - (to - from)).length() < 0.01, "{kind} pan: {before:?} -> {after:?}"); + assert_eq!(frames.app.session.pkg, original, "{kind} navigation edited the document"); + } +} diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index 3b37ae1b..64642993 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -4,11 +4,12 @@ pub(crate) mod annotation_canvas; pub(crate) mod annotation_input; pub(crate) mod canvas; mod context_menu; -mod frame_hit; +pub(crate) mod frame_hit; #[cfg(test)] mod frames; mod graph_camera; mod graph_drag; +pub(crate) mod graph_parent; mod graph_view; pub(crate) mod input_visibility; #[cfg(test)] @@ -18,14 +19,40 @@ pub(crate) mod node_card; mod node_layout; mod node_search; pub(crate) mod node_selection; -mod port_hit; +pub(crate) mod port_hit; pub(crate) mod port_label; +pub(crate) mod subgraph_navigation; -pub use canvas::{NODE_W, add_node_near_selection, delete_selected_wires, header_color, node_label, node_rect, port_color, show, swap_selected_wires}; +pub use canvas::show; pub(crate) use graph_camera::GraphCamera; use graph_drag::GraphDrag; pub use graph_view::GraphView; pub use library_drag::LibraryDrag; +pub use navigation::add_node_near_selection; use node_search::NodeSearch; +pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color}; pub use port_hit::PortHit; +pub use wire_actions::{delete_selected_wires, swap_selected_wires}; pub type WireRef = (materialcraft_engine::core::NodeId, String); + +#[cfg(test)] +mod canvas_tests; +pub(crate) mod grid; +mod input; +mod navigation; +mod node_style; +mod search; +pub(crate) mod selection_commands; +pub(crate) mod toolbar; +mod wire_actions; +pub(crate) mod wire_geometry; + +#[cfg(test)] +mod review_tests; + +pub(crate) mod edit_menu; +pub(crate) mod editor_actions; +pub(crate) mod editor_target; +pub(crate) mod gesture; + +pub(crate) mod canvas_geometry; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs new file mode 100644 index 00000000..46bf08f2 --- /dev/null +++ b/crates/ui-egui/src/graph/navigation.rs @@ -0,0 +1,48 @@ +use super::{NODE_W, node_rect}; +use crate::MaterialCraftApp; +use egui::{Pos2, Rect, pos2, vec2}; +use serde_json::json; + +pub(super) fn view_center(app: &MaterialCraftApp) -> Pos2 { + let c = &app.ui.graph_camera; + let v = app.graph.view; + pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) +} + +/// Add `def` right of the last selected node (wired from it when it fits), else mid-view +pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { + let sel = app.session.selection.last().copied(); + let has_inputs = materialcraft_engine::nodes::find(def).is_some_and(|d| !d.inputs.is_empty()); + let params = match sel { + Some(id) if has_inputs && !app.session.output_ports(id).is_empty() => json!({"def": def, "connectFrom": {"node": id.0}}), + _ => { + let c = view_center(app); + json!({"def": def, "at": [c.x - NODE_W * 0.5, c.y - 60.0]}) + } + }; + + app.run("graph.node.add", params); +} + +/// Frame the graph (or the selection) in the view +pub(super) fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { + let thumbs = app.ui.prefs.thumbnails; + let Ok(g) = app.session.graph() else { return }; + + let mut r = Rect::NOTHING; + for n in &g.nodes { + if only_selection && !app.session.selection.contains(&n.id) { + continue; + } + + let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); + let visible = super::input_visibility::count(inputs.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); + r = r.union(node_rect(n, visible, outputs.len(), thumbs)); + } + for f in &g.frames { + if !only_selection { + r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1] - 32.0), vec2(f.rect[2], f.rect[3] + 32.0))); + } + } + app.ui.graph_camera = super::GraphCamera::fit(view, r).state(); +} diff --git a/crates/ui-egui/src/graph/node_selection.rs b/crates/ui-egui/src/graph/node_selection.rs index 35a1d982..eaacf56c 100644 --- a/crates/ui-egui/src/graph/node_selection.rs +++ b/crates/ui-egui/src/graph/node_selection.rs @@ -25,3 +25,27 @@ pub(crate) fn select<T: Copy + Eq>(selection: &mut Vec<T>, node: Option<T>, modi pub(crate) fn inspected<T: Copy>(selection: &[T], previous: Option<T>) -> Option<T> { selection.last().copied().or(previous) } + +pub(crate) fn select_box<T: Copy + Eq>( + selection: &mut Vec<T>, + nodes: impl IntoIterator<Item = (T, egui::Rect)>, + start: egui::Pos2, + end: egui::Pos2, + modifiers: Modifiers, +) { + let bounds = egui::Rect::from_two_pos(start, end); + select(selection, None, modifiers); + if bounds.width() <= 3.0 && bounds.height() <= 3.0 { + return; + } + + for (id, rect) in nodes { + if bounds.intersects(rect) && !selection.contains(&id) { + selection.push(id); + } + } +} + +pub(crate) fn paint_box(painter: &egui::Painter, start: egui::Pos2, end: egui::Pos2, color: egui::Color32) { + painter.rect(egui::Rect::from_two_pos(start, end), 0.0, color.gamma_multiply(0.12), egui::Stroke::new(1.0, color), egui::StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/graph/node_style.rs b/crates/ui-egui/src/graph/node_style.rs new file mode 100644 index 00000000..b9104c5c --- /dev/null +++ b/crates/ui-egui/src/graph/node_style.rs @@ -0,0 +1,85 @@ +use super::node_card; +use crate::i18n::tr; +use egui::{Color32, Rect}; +use materialcraft_engine::{ + core::{Node, Value}, + nodes::PortKind, +}; +pub const NODE_W: f32 = node_card::WIDTH; +pub(super) const PORT_RADIUS: f32 = 4.5; + +/// Header strip color of a node by its library category +pub fn header_color(def: &str) -> Color32 { + let cat = materialcraft_engine::nodes::find(def).map_or("", |d| d.category); + match def { + "output" => Color32::from_rgb(0x2c, 0x8f, 0x5e), + "input_color" | "input_grayscale" | "input_value" => Color32::from_rgb(0x6d, 0x52, 0xb5), + "graph_instance" => Color32::from_rgb(0x1e, 0x8a, 0xa0), + _ if cat.starts_with("Atomic") => Color32::from_rgb(0x5c, 0x62, 0x6e), + _ if cat.contains("Noises") => Color32::from_rgb(0xa8, 0x3c, 0x34), + _ if cat.contains("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c), + _ if cat.starts_with("Material") => Color32::from_rgb(0x3a, 0x66, 0xb0), + _ if cat.starts_with("Filters") => Color32::from_rgb(0x3b, 0x7f, 0x4c), + _ => Color32::from_rgb(0x5c, 0x62, 0x6e), + } +} + +pub fn port_color(kind: PortKind) -> Color32 { + match kind { + PortKind::Gray => Color32::from_rgb(0xc8, 0xc8, 0xc8), + PortKind::Color => Color32::from_rgb(0xe8, 0xa9, 0x3c), + PortKind::Value => Color32::from_rgb(0x8b, 0xc6, 0x74), + PortKind::Any => Color32::from_rgb(0x8c, 0xb4, 0xe0), + } +} + +/// A node's display label +pub fn node_label(n: &Node) -> String { + if !n.label.is_empty() { + return n.label.clone(); + } + let label = match n.def.as_str() { + "graph_instance" => match n.params.get("graph") { + Some(Value::Text(g)) => g.clone(), + _ => tr("Graph instance").into(), + }, + "output" | "input_color" | "input_grayscale" | "input_value" => materialcraft_engine::eval::identifier(n), + d => materialcraft_engine::nodes::find(d).map_or(d, |d| d.label).to_string(), + }; + label.split(['_', ' ']).filter(|word| !word.is_empty()).fold(String::with_capacity(label.len()), |mut display, word| { + if !display.is_empty() { + display.push(' '); + } + let mut letters = word.chars(); + if let Some(first) = letters.next() { + display.extend(first.to_uppercase()); + display.extend(letters); + } + display + }) +} + +/// Graph-space rectangle of a node card +pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect { + node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot") +} + +#[cfg(test)] +mod tests { + use super::*; + use materialcraft_engine::core::NodeId; + + #[test] + fn default_labels_are_capitalized_without_changing_identifiers_or_custom_labels() { + for definition in ["input_color", "input_grayscale", "input_value", "output"] { + let mut node = Node::new(NodeId(1), definition, [0.0; 2]); + node.params.insert("identifier".into(), Value::Text("échantillon_value".into())); + assert_eq!(node_label(&node), "Échantillon Value"); + assert_eq!(materialcraft_engine::eval::identifier(&node), "échantillon_value"); + node.label = "my exact_label".into(); + assert_eq!(node_label(&node), "my exact_label"); + } + let node = Node::new(NodeId(2), "unknown_primitive", [0.0; 2]); + assert_eq!(node_label(&node), "Unknown Primitive"); + } +} diff --git a/crates/ui-egui/src/graph/port_hit.rs b/crates/ui-egui/src/graph/port_hit.rs index e2ef8bbc..268f5415 100644 --- a/crates/ui-egui/src/graph/port_hit.rs +++ b/crates/ui-egui/src/graph/port_hit.rs @@ -12,3 +12,19 @@ pub struct PortHit { pub pos: Pos2, pub kind: PortKind, } + +pub(super) fn nearest(ports: &[PortHit], pointer: Pos2, radius: f32) -> Option<&PortHit> { + nearest_by(ports, pointer, |port| (port.pos, radius)) +} + +pub(crate) fn nearest_by<T>(items: &[T], pointer: Pos2, hit_area: impl Fn(&T) -> (Pos2, f32)) -> Option<&T> { + items + .iter() + .filter_map(|item| { + let (position, radius) = hit_area(item); + let distance = position.distance_sq(pointer); + (distance <= radius * radius).then_some((item, distance)) + }) + .min_by(|left, right| left.1.total_cmp(&right.1)) + .map(|(item, _)| item) +} diff --git a/crates/ui-egui/src/graph/review_tests.rs b/crates/ui-egui/src/graph/review_tests.rs new file mode 100644 index 00000000..98de7f91 --- /dev/null +++ b/crates/ui-egui/src/graph/review_tests.rs @@ -0,0 +1,343 @@ +use crate::{ + MaterialCraftApp, UiState, + function::{FunctionEditor, FunctionTarget}, + menus, +}; +use materialcraft_engine::{ + core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value}, + new_session, +}; +use serde_json::json; + +#[test] +fn embedded_function_commands_do_not_edit_the_parent_selection() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Parameter("function".into()))); + app.session.selection = vec![owner]; + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + menus::invoke(&mut app, &context, "edit.delete"); + let node = app.session.graph().unwrap().node(owner).expect("Delete must stay in the Function editor"); + let Value::Function(function) = &node.params["function"] else { panic!("missing function") }; + assert!(function.nodes.is_empty()); +} + +#[test] +fn nested_function_commands_take_priority_over_fx_map_selection() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); + let node = graph.nodes[0].id; + graph.nodes[0].parameters.insert("patternrotation".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float(0.0))))); + app.run("graph.pattern.set", json!({"id": owner.0, "pattern": graph})).unwrap(); + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, owner)); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Pattern { node, parameter: "patternrotation".into() })); + menus::invoke(&mut app, &context, "edit.selectAll"); + let inspected = crate::control::handle(&mut app, &context, "ui.inspect", &json!({})); + assert_eq!(inspected["result"]["subgraph"]["kind"], "function"); + menus::invoke(&mut app, &context, "edit.delete"); + let Value::PatternGraph(graph) = &app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing pattern") }; + assert_eq!(graph.nodes.len(), 1); + let Value::Function(function) = &graph.nodes[0].parameters["patternrotation"] else { panic!("missing function") }; + assert!(function.nodes.is_empty()); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert!(app.function_editor.is_none()); + assert_eq!(app.pattern_editor.as_ref().unwrap().selection, vec![node]); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert!(app.pattern_editor.is_none()); + assert_eq!(app.session.selection, vec![owner]); +} + +#[test] +fn graph_gestures_ignore_other_button_releases_and_escape_cancels() { + use super::frames::Frames; + use egui::{Event, Key, Modifiers, PointerButton, vec2}; + for kind in ["material", "function", "pattern"] { + let mut frames = Frames::new(new_session()); + frames.app.ui.prefs.snap_to_grid = false; + match kind { + "function" => { + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + graph.add("mul", &[], None); + frames.app.run("graph.function.set", json!({"function": graph})).unwrap(); + } + "pattern" => { + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + frames.app.run("graph.pattern.set", json!({"id": owner.0, "pattern": PatternGraph::with_root(PatternNodeKind::Quadrant)})).unwrap(); + frames.app.pattern_editor = Some(crate::pattern::PatternEditor::new(frames.app.session.graph, owner)); + } + _ => { + frames.app.run("graph.node.add", json!({"def": "uniform"})).unwrap(); + } + } + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + for cancel in [false, true] { + frames.run(Vec::new(), Modifiers::NONE); + let original = frames.app.session.pkg.clone(); + let from = frames.app.graph.rects[0].1.center(); + let middle = from + vec2(20.0, 0.0); + let to = from + vec2(60.0, 0.0); + let button = |pos, button, pressed| Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }; + frames.run(vec![Event::PointerMoved(from)], Modifiers::NONE); + frames.run(vec![button(from, PointerButton::Primary, true)], Modifiers::NONE); + frames.run(vec![Event::PointerMoved(middle)], Modifiers::NONE); + for pressed in [true, false] { + frames.run(vec![button(middle, PointerButton::Middle, pressed)], Modifiers::NONE); + } + assert_eq!(frames.app.session.pkg, original, "{kind}: unrelated release committed movement"); + frames.run(vec![Event::PointerMoved(to)], Modifiers::NONE); + if cancel { + frames + .run(vec![Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + } + frames.run(vec![button(to, PointerButton::Primary, false)], Modifiers::NONE); + frames.run(Vec::new(), Modifiers::NONE); + if cancel { + assert_eq!(frames.app.session.pkg, original, "{kind}: cancelled movement committed"); + } else { + assert!((frames.app.graph.rects[0].1.center().x - from.x - 60.0).abs() < 0.1, "{kind}: gesture ended early"); + } + } + } +} + +#[test] +fn processors_edit_inline_and_return_to_the_parent_without_document_changes() { + use super::{editor_target::EditorTarget, frames::Frames}; + for definition in ["pixel_processor", "value_processor"] { + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + frames.run(Vec::new(), egui::Modifiers::NONE); + let parent_camera = frames.app.ui.graph_camera; + let original = frames.app.session.pkg.clone(); + let history = frames.app.session.history(); + menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit"); + for _ in 0..3 { + frames.run(Vec::new(), egui::Modifiers::NONE); + } + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Function); + let inspected = crate::control::handle(&mut frames.app, &frames.ctx, "ui.inspect", &json!({})); + assert_eq!(inspected["result"]["graphView"][0], json!(frames.app.graph.view.min.x)); + assert_eq!(inspected["result"]["subgraph"]["kind"], "function"); + let point = frames.app.graph.view.left_bottom() + egui::vec2(20.0, -20.0); + frames.click(point, egui::Modifiers::NONE); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Function); + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); + frames.run(Vec::new(), egui::Modifiers::NONE); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Material); + assert_eq!(frames.app.ui.graph_camera, parent_camera); + assert_eq!(frames.app.session.selection, vec![owner]); + assert_eq!(frames.app.session.pkg, original); + assert_eq!(frames.app.session.history(), history); + } +} + +#[test] +fn instance_navigation_preserves_parent_view_and_material_across_renames() { + use materialcraft_engine::core::Graph; + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = app.session.graph_mut().unwrap().add_node("graph_instance", [0.0; 2]); + app.session.graph_mut().unwrap().node_mut(owner).unwrap().params.insert("graph".into(), Value::Text("Child".into())); + app.session.pkg.graphs.push(Graph::new("Child")); + app.session.selection = vec![owner]; + app.ui.graph_camera = crate::state::GraphCamera { pan: [123.0, -456.0], zoom: 1.5 }; + let camera = app.ui.graph_camera; + let material = app.session.material_preview.clone(); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "graph.node.edit"); + assert_eq!(app.session.graph, 1); + assert_eq!(app.session.material_preview, material); + assert!(menus::enabled(&app, "ui.graph.parent")); + app.run("graph.rename", json!({"graph": 0, "name": "Renamed parent"})).unwrap(); + assert!(super::subgraph_navigation::breadcrumb(&app).starts_with("Renamed parent / Child")); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert_eq!(app.session.graph, 0); + assert_eq!(app.session.selection, vec![owner]); + assert_eq!(app.ui.graph_camera, camera); + assert_eq!(app.session.material_preview, material); + assert!(!menus::enabled(&app, "ui.graph.parent")); + menus::invoke(&mut app, &context, "graph.node.edit"); + app.run("graph.open", json!({"graph": 0})).unwrap(); + assert!(!menus::enabled(&app, "ui.graph.parent")); +} + +#[test] +fn dynamic_parameter_functions_return_to_the_owning_node() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); + app.run("graph.node.function", json!({"id": owner, "param": "intensity"})).unwrap(); + super::subgraph_navigation::open_function(&mut app, owner, FunctionTarget::Dynamic("intensity".into())); + assert!(super::subgraph_navigation::breadcrumb(&app).ends_with("Blur / intensity")); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + menus::invoke(&mut app, &context, "edit.delete"); + assert!(app.session.graph().unwrap().node(owner).unwrap().functions["intensity"].nodes.is_empty()); + menus::invoke(&mut app, &context, "ui.graph.parent"); + assert_eq!(app.session.selection, vec![owner]); + assert!(app.function_editor.is_none()); +} + +#[test] +fn idle_ui_frames_preserve_explicit_automation_undo_groups() { + use super::frames::Frames; + use egui::{Event, Modifiers, PointerButton}; + let mut frames = Frames::new(new_session()); + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + let added = frames.app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})).unwrap(); + let id = added["id"].as_u64().unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + frames.app.session.reset_history(); + for value in [1.0, 2.0, 3.0] { + frames.app.run("graph.function.edit", json!({"merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(value)}})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + } + assert_eq!(frames.app.session.history().len(), 1); + frames.app.run("edit.finish", json!({})).unwrap(); + let position = frames.app.graph.view.left_bottom() + egui::vec2(20.0, -20.0); + frames.run( + vec![Event::PointerMoved(position), Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], + Modifiers::NONE, + ); + frames.app.run("graph.function.edit", json!({"merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(4.0)}})).unwrap(); + frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], Modifiers::NONE); + frames.app.run("graph.function.edit", json!({"merge": true, "edit": {"action": "value", "id": id, "value": Value::Float(5.0)}})).unwrap(); + assert_eq!(frames.app.session.history().len(), 3); +} + +#[test] +#[ignore = "release canvas timing, run with --nocapture"] +fn canvas_frame_cost() { + for count in [128, 4096] { + for kind in ["function", "pattern"] { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + if kind == "function" { + app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + let mut previous = None; + for index in 0..count { + let id = graph.add("passthrough", &previous.into_iter().collect::<Vec<_>>(), None); + graph.nodes.last_mut().unwrap().pos = [(index % 64) as f32 * 200.0, (index / 64) as f32 * 180.0]; + previous = Some(id); + } + app.session.graph_mut().unwrap().function = Some(graph); + } else { + let owner = NodeId(app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::default(); + for index in 0..count { + graph.add(PatternNodeKind::Quadrant).unwrap(); + let node = graph.nodes.last_mut().unwrap(); + node.position = [(index % 64) as f32 * 200.0, (index / 64) as f32 * 180.0]; + node.parameters.insert("rotation".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float(0.0))))); + } + app.session.graph_mut().unwrap().node_mut(owner).unwrap().params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, owner)); + } + let context = egui::Context::default(); + crate::theme::install(&context); + let mut frame = || { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; + std::hint::black_box(context.run_ui(input, |ui| super::show(&mut app, ui))); + }; + for _ in 0..3 { + frame(); + } + let mut samples = Vec::new(); + for _ in 0..3 { + let start = std::time::Instant::now(); + for _ in 0..8 { + frame(); + } + samples.push(start.elapsed().as_secs_f64() * 1000.0 / 8.0); + } + samples.sort_by(f64::total_cmp); + println!("{kind} {count} nodes: {:.3} ms/frame", samples[1]); + } + } +} + +#[test] +fn undo_closes_an_embedded_editor_when_its_owning_graph_changes() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + app.run("graph.duplicate", json!({})).unwrap(); + app.session.reset_history(); + app.run("graph.open", json!({"graph": 0})).unwrap(); + app.run("graph.size", json!({"log2": [8, 8]})).unwrap(); + app.run("graph.open", json!({"graph": 1})).unwrap(); + app.function_editor = Some(FunctionEditor::new(app.session.graph, owner, FunctionTarget::Parameter("function".into()))); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + menus::invoke(&mut app, &context, "edit.undo"); + assert_eq!(app.session.graph, 0); + assert!(app.function_editor.is_none()); + for graph in &app.session.pkg.graphs { + let node = graph.node(owner).unwrap(); + assert!(!matches!(node.params.get("function"), Some(Value::Function(graph)) if graph.nodes.is_empty())); + } +} + +#[test] +fn rejected_duplicate_keeps_the_function_editor_selection() { + let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); + app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for _ in 0..2049 { + graph.add("passthrough", &[], None); + } + app.run("graph.function.set", json!({"function": graph})).unwrap(); + app.function_editor = Some(FunctionEditor::standalone(app.session.graph)); + let context = egui::Context::default(); + menus::invoke(&mut app, &context, "edit.selectAll"); + let before = app.function_editor.as_ref().unwrap().selection.clone(); + menus::invoke(&mut app, &context, "edit.duplicate"); + assert_eq!(app.function_editor.as_ref().unwrap().selection, before); + assert_eq!(app.session.graph().unwrap().function.as_ref().unwrap().nodes.len(), 2049); +} + +#[test] +fn properties_and_library_follow_the_active_embedded_function() { + use super::{editor_target::EditorTarget, frames::Frames}; + let mut frames = Frames::new(new_session()); + let owner = NodeId(frames.app.run("graph.node.add", json!({"def": "pixel_processor"})).unwrap()["id"].as_u64().unwrap()); + let target = materialcraft_engine::FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + frames.app.run("graph.function.set", json!({"target": target, "function": FunctionGraph::constant(Value::Float(0.5))})).unwrap(); + frames.app.function_editor = Some(FunctionEditor::new(frames.app.session.graph, owner, FunctionTarget::Parameter("function".into()))); + menus::invoke(&mut frames.app, &frames.ctx, "edit.selectAll"); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Function); + let label = materialcraft_engine::nodes::function::definition("const_float1").unwrap().label; + assert!(crate::properties::title(&frames.app).starts_with(label)); + frames.app.ui.library_search.clear(); + let output = frames + .ctx + .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 800.0))), ..Default::default() }, |ui| { + crate::library::show(&mut frames.app, ui) + }); + assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.job.text.contains("Search functions")))); + menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); + assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Material); + assert!(crate::properties::title(&frames.app).starts_with("Pixel Processor")); +} + +#[test] +fn standalone_function_creation_keeps_selection_after_the_next_frame() { + use super::frames::Frames; + let mut frames = Frames::new(new_session()); + frames.app.run("file.new", json!({"kind": "function"})).unwrap(); + frames.run(Vec::new(), egui::Modifiers::NONE); + let mut editor = frames.app.function_editor.take().unwrap(); + editor.edit(&mut frames.app, materialcraft_engine::FunctionEdit::Add { operation: "const_float1".into(), at: [0.0; 2], snap: false }, false); + let selected = editor.selection.clone(); + frames.app.function_editor = Some(editor); + frames.run(Vec::new(), egui::Modifiers::NONE); + assert!(!selected.is_empty()); + assert_eq!(frames.app.function_editor.as_ref().unwrap().selection, selected); + menus::invoke(&mut frames.app, &frames.ctx, "edit.delete"); + menus::invoke(&mut frames.app, &frames.ctx, "edit.undo"); + frames.run(Vec::new(), egui::Modifiers::NONE); + assert_eq!(frames.app.function_editor.as_ref().unwrap().selection, selected); +} diff --git a/crates/ui-egui/src/graph/search.rs b/crates/ui-egui/src/graph/search.rs new file mode 100644 index 00000000..3ce3d587 --- /dev/null +++ b/crates/ui-egui/src/graph/search.rs @@ -0,0 +1,100 @@ +use super::{GraphCamera, NodeSearch}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{Pos2, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::NodeId; +use serde_json::json; + +pub(super) fn open_search(app: &mut MaterialCraftApp, at: Pos2, connect: Option<(NodeId, String)>) { + app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, focus: true }); +} + +/// Catalog entries matching `text` (label or id contains every word) +pub(super) fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDefinition> { + let words: Vec<String> = text.split_whitespace().map(str::to_ascii_lowercase).collect(); + let mut v: Vec<_> = materialcraft_engine::nodes::catalog() + .iter() + .filter(|d| d.id != "graph_instance") + .filter(|d| { + let hay = format!("{} {} {}", d.label.to_ascii_lowercase(), d.id, d.category.to_ascii_lowercase()); + words.iter().all(|w| hay.contains(w.as_str())) + }) + .collect(); + if let Some(w) = words.first() { + v.sort_by_key(|d| !d.label.to_ascii_lowercase().starts_with(w.as_str())); + } + v +} + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { + let Some(s) = app.graph.search.as_mut() else { return }; + + let tk = Tokens::get(ui.ctx()); + let screen = cam.to_screen(s.at); + let mut close = false; + let mut pick: Option<&'static str> = None; + egui::Area::new(egui::Id::unique("node-search")).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_width(260.0); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); + let r = ui.add(egui::TextEdit::singleline(&mut s.text).hint_text(tr("Search nodes...")).desired_width(220.0)); + crate::widgets::name(&r, egui::Role::SearchInput, "Search nodes"); + if s.focus { + r.request_focus(); + s.focus = false; + } + if r.changed() { + s.sel = 0; + } + }); + let list = matches(&s.text); + let (up, down, enter, esc) = ui.input(|i| { + (i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)) + }); + if down { + s.sel = (s.sel + 1).min(list.len().saturating_sub(1)); + } + if up { + s.sel = s.sel.saturating_sub(1); + } + if esc { + close = true; + } + if enter && let Some(d) = list.get(s.sel) { + pick = Some(d.id); + } + egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { + for (i, d) in list.iter().enumerate().take(60) { + let r = ui.add( + egui::Button::selectable(i == s.sel, format!("{} ", d.label)) + .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), + ); + if i == s.sel && (up || down) { + r.scroll_to_me(None); + } + if r.clicked() { + pick = Some(d.id); + } + } + if list.is_empty() { + ui.label(egui::RichText::new(tr("No matching node")).color(tk.text_dim)); + } + }); + }); + }); + let clicked_out = ui.input(|i| i.pointer.any_pressed()) + && ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == egui::Id::unique("node-search"))); + if let Some(def) = pick { + let s = app.graph.search.take(); + if let Some(s) = s { + let mut p = json!({"def": def, "at": [s.at.x, s.at.y - 20.0]}); + if let Some((n, port)) = s.connect { + p["connectFrom"] = json!({"node": n.0, "port": port}); + } + app.run("graph.node.add", p); + } + } else if close || clicked_out { + app.graph.search = None; + } +} diff --git a/crates/ui-egui/src/graph/selection_commands.rs b/crates/ui-egui/src/graph/selection_commands.rs new file mode 100644 index 00000000..736492eb --- /dev/null +++ b/crates/ui-egui/src/graph/selection_commands.rs @@ -0,0 +1,11 @@ +use crate::MaterialCraftApp; +use serde_json::Value; + +pub(crate) fn invoke(app: &mut MaterialCraftApp, selection: &mut Vec<u32>, command: &str, parameters: Value) { + if let Some(mut result) = app.run(command, parameters) + && let Some(ids) = result.get_mut("ids") + && let Ok(updated) = serde_json::from_value(ids.take()) + { + *selection = updated; + } +} diff --git a/crates/ui-egui/src/graph/subgraph_navigation.rs b/crates/ui-egui/src/graph/subgraph_navigation.rs new file mode 100644 index 00000000..f9e1eecd --- /dev/null +++ b/crates/ui-egui/src/graph/subgraph_navigation.rs @@ -0,0 +1,86 @@ +use crate::{ + MaterialCraftApp, + docking::Panel, + function::{FunctionEditor, FunctionTarget}, +}; +use serde_json::json; + +use super::graph_parent::GraphParent; + +pub(crate) fn can_return(app: &MaterialCraftApp) -> bool { + app.function_editor.as_ref().is_some_and(|editor| editor.target != FunctionTarget::Graph) || crate::pattern::active(app) || !app.graph_parents.is_empty() +} + +pub(crate) fn parent(app: &mut MaterialCraftApp) { + if app.function_editor.as_ref().is_some_and(|editor| editor.target != FunctionTarget::Graph) { + app.function_editor = None; + } else if crate::pattern::active(app) { + app.pattern_editor = None; + } else if let Some(parent) = app.graph_parents.pop() + && open_graph(app, parent.graph) + { + app.session.selection = parent.selection.into_iter().filter(|id| app.session.graph().is_ok_and(|graph| graph.node(*id).is_ok())).collect(); + app.ui.graph_camera = parent.camera; + app.graph.framed_graph = Some(parent.graph); + app.ui.frame_all = false; + } + app.ui.dock.focus(Panel::Graph); +} + +pub(crate) fn open_function(app: &mut MaterialCraftApp, node: materialcraft_engine::core::NodeId, target: FunctionTarget) { + if !matches!(target, FunctionTarget::Pattern { .. }) { + app.pattern_editor = None; + } + app.graph.drag = None; + app.function_editor = Some(FunctionEditor::new(app.session.graph, node, target)); + app.ui.dock.focus(Panel::Graph); +} + +pub(crate) fn open_instance(app: &mut MaterialCraftApp, graph: usize) { + let parent = GraphParent { graph: app.session.graph, selection: app.session.selection.clone(), camera: app.ui.graph_camera }; + if open_graph(app, graph) { + app.graph_parents.push(parent); + app.ui.dock.focus(Panel::Graph); + } +} + +fn open_graph(app: &mut MaterialCraftApp, index: usize) -> bool { + let parents = std::mem::take(&mut app.graph_parents); + let material = app.session.material_preview.clone(); + let opened = app.run("graph.open", json!({"graph": index})).is_some(); + app.graph_parents = parents; + app.session.material_preview = material; + opened +} + +pub(crate) fn breadcrumb(app: &MaterialCraftApp) -> String { + let mut path: Vec<String> = + app.graph_parents.iter().filter_map(|parent| app.session.pkg.graphs.get(parent.graph).map(|graph| graph.name.clone())).collect(); + if let Ok(graph) = app.session.graph() { + path.push(graph.name.clone()); + let owner = app.function_editor.as_ref().and_then(|editor| editor.node).or_else(|| app.pattern_editor.as_ref().map(|editor| editor.node)); + if let Some(node) = owner.and_then(|id| graph.node(id).ok()) { + path.push(super::node_label(node)); + } + } + if let Some(editor) = &app.function_editor { + match &editor.target { + FunctionTarget::Pattern { node, parameter } => { + let label = app + .pattern_editor + .as_ref() + .and_then(|editor| editor.current(app)) + .and_then(|graph| graph.nodes.iter().find(|item| item.id == *node)) + .map(|node| node.kind.label()); + if let Some(label) = label { + path.push(label.into()); + } + path.push(parameter.clone()); + } + FunctionTarget::Dynamic(parameter) => path.push(parameter.clone()), + FunctionTarget::Parameter(parameter) if parameter != "function" => path.push(parameter.clone()), + _ => {} + } + } + path.join(" / ") +} diff --git a/crates/ui-egui/src/graph/toolbar.rs b/crates/ui-egui/src/graph/toolbar.rs new file mode 100644 index 00000000..086c66fb --- /dev/null +++ b/crates/ui-egui/src/graph/toolbar.rs @@ -0,0 +1,186 @@ +use super::navigation::{add_node_near_selection, view_center}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::Ui; +use egui_phosphor::regular as icon; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let function = app.function_editor.is_some(); + let pattern = !function && crate::pattern::active(app); + let embedded_function = app.function_editor.as_ref().is_some_and(|editor| editor.target != crate::function::FunctionTarget::Graph); + let function_target = app.function_editor.as_ref().and_then(|editor| editor.command_target()); + let selection: Vec<u64> = if pattern { + app.pattern_editor.as_ref().map(|editor| editor.selection.iter().copied().map(u64::from).collect()).unwrap_or_default() + } else if function { + app.function_editor.as_ref().map(|editor| editor.selection.iter().copied().map(u64::from).collect()).unwrap_or_default() + } else { + app.session.selection.iter().map(|id| id.0).collect() + }; + let graph = app.session.graph; + let owner = pattern.then(|| app.pattern_editor.as_ref().map(|editor| editor.node.0)).flatten(); + row(ui, |ui| { + let b = button; + if common(app, ui, selection.len(), || { + let mut parameters = json!({"graph": graph, "ids": selection}); + if let Some(owner) = owner { + parameters["pattern"] = json!(owner); + } + if let Some(target) = &function_target { + parameters["function"] = json!(target); + } + parameters + }) { + app.ui.frame_all = true; + } + if !pattern && !embedded_function { + ui.separator(); + if b(ui, icon::SELECTION, tr("Add frame around the selection")) { + let parameters = if function { function_frame(app, &selection) } else { json!({}) }; + app.run("graph.frame.add", parameters); + } + if b(ui, icon::NOTE, tr("Add comment")) { + app.run("graph.comment.add", json!({})); + } + if b(ui, icon::MAP_PIN, tr("Add navigation pin")) { + let center = view_center(app); + app.run("graph.pin.add", json!({"at": [center.x, center.y]})); + } + } + + if !pattern && !function { + // Quick insert of the atomic nodes + for (ic, def) in [ + (icon::IMAGE, "bitmap"), + (icon::PALETTE, "uniform"), + (icon::STACK, "blend"), + (icon::DROP, "blur"), + (icon::SHUFFLE, "channels_shuffle"), + (icon::CHART_LINE, "curve"), + (icon::WIND, "directional_blur"), + (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), + (icon::RULER, "distance"), + (icon::MOUNTAINS, "emboss"), + (icon::GRADIENT, "gradient_map"), + (icon::CIRCLE_HALF, "grayscale_conversion"), + (icon::SWATCHES, "hsl"), + (icon::SLIDERS_HORIZONTAL, "levels"), + (icon::CUBE, "normal"), + (icon::CODE, "pixel_processor"), + (icon::DIAMOND, "sharpen"), + (icon::ARROWS_CLOCKWISE, "transformation"), + (icon::WAVES, "warp"), + (icon::SIGN_IN, "input_grayscale"), + (icon::SIGN_OUT, "output"), + ] { + let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); + if b(ui, ic, label) { + add_node_near_selection(app, def); + } + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if super::subgraph_navigation::can_return(app) { + if b(ui, icon::ARROW_BEND_UP_LEFT, tr("Return to parent graph")) { + crate::menus::invoke(app, ui.ctx(), "ui.graph.parent"); + } + ui.label(super::subgraph_navigation::breadcrumb(app)); + } + if pattern { + if app.pattern_editor.as_ref().and_then(|editor| editor.current(app)).is_some_and(|graph| graph.root.is_none()) { + ui.label(tr("Set a node as the root")); + } + } else { + thumbnails(app, ui); + if function { + if app.function_editor.as_ref().and_then(|editor| editor.current(app)).is_some_and(|graph| graph.output.is_none()) { + ui.label(tr("Set a node as the output")); + } + } else { + parent_size(app, ui); + } + } + }); + }); +} + +fn row(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { + let tokens = Tokens::get(ui.ctx()); + egui::Frame::NONE.fill(tokens.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + draw(ui); + }); + }); +} + +fn button(ui: &mut Ui, icon: &str, tooltip: &str) -> bool { + crate::widgets::icon_button(ui, icon, tooltip, false, 22.0).clicked() +} + +fn common(app: &mut MaterialCraftApp, ui: &mut Ui, selection_count: usize, parameters: impl Fn() -> serde_json::Value) -> bool { + let frame = button(ui, icon::CORNERS_OUT, tr("Frame all (F)")); + let can_align = selection_count > 1; + for (icon, mode, tooltip) in [ + (icon::ALIGN_LEFT, "left", "Align left"), + (icon::ALIGN_TOP, "top", "Align top"), + (icon::ALIGN_CENTER_HORIZONTAL, "hcenter", "Align centers horizontally"), + (icon::ALIGN_CENTER_VERTICAL, "vcenter", "Align centers vertically"), + (icon::COLUMNS, "hdistribute", "Distribute horizontally"), + (icon::ROWS, "vdistribute", "Distribute vertically"), + ] { + if ui.add_enabled_ui(can_align, |ui| button(ui, icon, tr(tooltip))).inner { + let mut parameters = parameters(); + parameters["mode"] = json!(mode); + app.run("graph.align", parameters); + } + } + ui.separator(); + if crate::widgets::icon_button(ui, icon::GRID_FOUR, tr("Snap to grid"), app.ui.prefs.snap_to_grid, 22.0).clicked() { + crate::menus::invoke(app, ui.ctx(), "ui.graph.snapToGrid"); + } + frame +} + +fn thumbnails(app: &mut MaterialCraftApp, ui: &mut Ui) { + let thumbnails = app.ui.prefs.thumbnails; + if crate::widgets::icon_button(ui, icon::IMAGE, tr("Show node thumbnails"), thumbnails, 22.0).clicked() { + app.ui.prefs.thumbnails = !thumbnails; + } +} + +/// "Parent size: [1024 ▾] × [1024 ▾]" +fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { + let Ok(g) = app.session.graph() else { return }; + + let [w, h] = g.size; + let mut nw = w; + let mut nh = h; + let combo = |ui: &mut Ui, id: &str, v: &mut u32| { + let r = egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| { + for l in 4..=13u32 { + ui.selectable_value(v, l, format!("{}", 1u32 << l)); + } + }); + crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); + }; + + combo(ui, "parent-h", &mut nh); + ui.label("x"); + combo(ui, "parent-w", &mut nw); + ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim)); + if (nw, nh) != (w, h) { + app.run("graph.size", json!({"log2": [nw, nh]})); + } +} + +fn function_frame(app: &MaterialCraftApp, selection: &[u64]) -> serde_json::Value { + let camera = super::GraphCamera { origin: app.graph.view.min, pan: app.ui.graph_camera.pan.into(), zoom: app.ui.graph_camera.zoom }; + let bounds = app.graph.rects.iter().filter(|(id, _)| selection.contains(&id.0)).fold(egui::Rect::NOTHING, |bounds, (_, rect)| bounds.union(*rect)); + if !bounds.is_finite() { + return json!({}); + } + + let start = camera.to_graph(bounds.min); + let size = bounds.size() / camera.zoom; + json!({"rect": [start.x - 24.0, start.y - 44.0, size.x + 48.0, size.y + 68.0]}) +} diff --git a/crates/ui-egui/src/graph/wire_actions.rs b/crates/ui-egui/src/graph/wire_actions.rs new file mode 100644 index 00000000..74834581 --- /dev/null +++ b/crates/ui-egui/src/graph/wire_actions.rs @@ -0,0 +1,52 @@ +use super::WireRef; +use crate::{MaterialCraftApp, i18n::tr}; +use egui::{Pos2, Ui}; +use egui_phosphor::regular as icon; +use serde_json::json; + +/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands +fn wires_json(wires: &[WireRef]) -> serde_json::Value { + json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()}) +} + +/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none is selected +pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { + let wires = std::mem::take(&mut app.graph.selected_wires); + if wires.is_empty() { + return false; + } + app.run("graph.wire.delete", wires_json(&wires)); + true +} + +/// Reverse the sources of selected wires so pressing X again restores them +pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { + if app.graph.selected_wires.is_empty() { + return false; + } + let params = wires_json(&app.graph.selected_wires); + app.run("graph.wire.swap", params); + true +} + +pub(super) fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) { + let n = app.graph.selected_wires.len(); + if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() { + app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]})); + app.graph.selected_wires.clear(); + ui.close(); + } + if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() { + swap_selected_wires(app); + ui.close(); + } + let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") }; + + if ui.button(format!("{} {label}", icon::TRASH)).clicked() { + if n < 2 { + app.graph.selected_wires = vec![(to, port)]; + } + delete_selected_wires(app); + ui.close(); + } +} diff --git a/crates/ui-egui/src/graph/wire_geometry.rs b/crates/ui-egui/src/graph/wire_geometry.rs new file mode 100644 index 00000000..7bfb10a6 --- /dev/null +++ b/crates/ui-egui/src/graph/wire_geometry.rs @@ -0,0 +1,52 @@ +use super::WireRef; +use egui::{Color32, Pos2, Rect, Stroke, pos2}; + +/// Pointer distance in points within which a wire is hit +pub(super) const WIRE_HIT: f32 = 5.0; + +pub(crate) fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { + curve_points(a, b, egui::Vec2::X) +} + +pub(crate) fn curve_points(source: Pos2, destination: Pos2, axis: egui::Vec2) -> [Pos2; 4] { + let offset = axis * ((destination - source).dot(axis).abs() * 0.5).max(30.0); + [source, source + offset, destination - offset, destination] +} + +pub(crate) fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { + p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke)); +} + +/// The point at `t` (0..1) along a cubic bezier +pub(super) fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 { + let u = 1.0 - t; + let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; + pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum()) +} + +/// Distance from `p` to a cubic bezier (sampled as a polyline) +pub(super) fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { + const N: usize = 32; + let mut best = f32::INFINITY; + let mut prev = c[0]; + for i in 1..=N { + let q = bezier_at(c, i as f32 / N as f32); + let (seg, rel) = (q - prev, p - prev); + let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + + best = best.min((prev + seg * t).distance(p)); + prev = q; + } + best +} + +/// The wire nearest `p` within [`WIRE_HIT`] points +pub(super) fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { + wires + .iter() + .filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p)) + .map(|(w, c)| (w, bezier_distance(c, p))) + .filter(|(_, d)| *d <= WIRE_HIT) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(w, _)| w) +} diff --git a/crates/ui-egui/src/graph_drag_payload.rs b/crates/ui-egui/src/graph_drag_payload.rs new file mode 100644 index 00000000..c4cc3da9 --- /dev/null +++ b/crates/ui-egui/src/graph_drag_payload.rs @@ -0,0 +1,4 @@ +/// A graph resource dragged from Explorer to a material preview +pub(crate) struct GraphDragPayload { + pub name: String, +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7937e5c6..9b6eaa26 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -9,11 +9,14 @@ pub mod explorer; pub mod fonts; pub mod function; pub mod graph; +mod graph_drag_payload; pub mod i18n; pub mod levels_editor; pub mod library; +mod material_preview_menu; mod menu_item; pub mod menus; +#[path = "property/mod.rs"] pub mod properties; pub mod state; pub mod theme; diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 639eee81..7815eba5 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -39,14 +39,16 @@ fn category_icon(top: &str) -> &'static str { } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - if crate::pattern::active(app) { - crate::pattern::library::show(app, ui); - return; - } - - if app.session.graph().is_ok_and(|graph| graph.function.is_some()) { - crate::function::library::show(app, ui); - return; + match crate::graph::editor_target::EditorTarget::resolve(app) { + crate::graph::editor_target::EditorTarget::Function => { + crate::function::library::show(app, ui); + return; + } + crate::graph::editor_target::EditorTarget::Pattern => { + crate::pattern::library::show(app, ui); + return; + } + crate::graph::editor_target::EditorTarget::Material => {} } let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 85ba045f..8739b835 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -19,9 +19,10 @@ pub struct MaterialCraftApp { pub graph: graph::GraphView, pub view3d: view3d::View3dState, pub view2d: view2d::View2dState, - /// The function graph editor window, when open + /// Embedded graph editors in the main graph panel pub pattern_editor: Option<pattern::PatternEditor>, pub function_editor: Option<function::FunctionEditor>, + pub(crate) graph_parents: Vec<graph::graph_parent::GraphParent>, /// Synthetic input from the control channel, fed to egui on the next frames pub input_queue: VecDeque<control::Scripted>, /// Replies waiting for the next window capture (`ui.screenshot`) @@ -39,6 +40,7 @@ pub struct MaterialCraftApp { pub fonts: fonts::UiFonts, /// The icon font is installed (it takes effect on the frame after `set_fonts`) fonts_ready: bool, + ui_gesture_active: bool, } impl MaterialCraftApp { @@ -68,6 +70,7 @@ impl MaterialCraftApp { view3d: view3d::View3dState::default(), view2d: view2d::View2dState::default(), function_editor: None, + graph_parents: Vec::new(), pattern_editor: None, input_queue: VecDeque::new(), pending_screenshots: Vec::new(), @@ -79,6 +82,7 @@ impl MaterialCraftApp { styled: None, fonts: fonts::UiFonts::default(), fonts_ready: false, + ui_gesture_active: false, }; i18n::set_language(&app.ui.prefs.language); app.apply_prefs(); @@ -122,6 +126,9 @@ impl MaterialCraftApp { match materialcraft_engine::execute(&mut self.session, id, ¶ms) { Ok(v) => { self.close_subgraph_after(id); + if matches!(id, "view.3d.assign" | "view.3d.outputs") { + self.ui.dock.focus(docking::Panel::View3d); + } Some(v) } Err(e) => { @@ -134,9 +141,26 @@ impl MaterialCraftApp { pub(crate) fn close_subgraph_after(&mut self, command: &str) { if command.starts_with("file.new") || matches!(command, "file.open" | "graph.open" | "graph.delete" | "graph.duplicate") { self.graph.inspected_node = None; + self.graph_parents.clear(); self.pattern_editor = None; self.function_editor = None; } + self.reconcile_editors(); + if (materialcraft_engine::selection_commands::supports(command) || matches!(command, "edit.undo" | "edit.redo")) + && let Some(editor) = &mut self.function_editor + && matches!(editor.target, function::FunctionTarget::Graph) + { + editor.selection = self.session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(); + } + } + + pub(crate) fn reconcile_editors(&mut self) { + if self.function_editor.as_ref().is_some_and(|editor| editor.current(self).is_none()) { + self.function_editor = None; + } + if self.pattern_editor.as_ref().is_some_and(|editor| editor.current(self).is_none()) { + self.pattern_editor = None; + } } pub fn toast(&mut self, text: impl Into<String>, error: bool) { @@ -224,6 +248,9 @@ impl MaterialCraftApp { if (ctx.zoom_factor() - scale).abs() > 1e-3 { ctx.set_zoom_factor(scale); } + if ctx.input(|input| input.pointer.any_pressed()) { + self.session.finish_edit(); + } control::poll(self, ctx); web_files::poll(self); for f in ctx.input(|i| i.raw.dropped_files.clone()) { @@ -233,6 +260,7 @@ impl MaterialCraftApp { cook::drive(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.autosave(now); + self.reconcile_editors(); menus::shortcuts(self, ctx); self.toasts.retain(|t| t.until > now); if !self.input_queue.is_empty() { @@ -255,7 +283,11 @@ impl MaterialCraftApp { toolbar::status_bar(self, ui); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); windows::show(self, &ctx); - function::show(self, &ctx); + let gesture_active = ctx.input(|input| input.pointer.any_down()) || ctx.egui_wants_keyboard_input(); + if !gesture_active && (self.ui_gesture_active || ctx.input(|input| input.pointer.any_released())) { + self.session.finish_edit(); + } + self.ui_gesture_active = gesture_active; crate::toast::show(self, &ctx); control::request_screenshots(self, &ctx); let dt = (now_ms() - t0) as f32; diff --git a/crates/ui-egui/src/material_preview_menu.rs b/crates/ui-egui/src/material_preview_menu.rs new file mode 100644 index 00000000..539486b2 --- /dev/null +++ b/crates/ui-egui/src/material_preview_menu.rs @@ -0,0 +1,44 @@ +use egui::Ui; +use materialcraft_engine::{ + MaterialSource, Session, + core::{MaterialChannel, NodeId}, +}; +use serde_json::{Value, json}; + +use crate::i18n::tr; + +/// Shared node/output assignment menu for the canvas and Explorer +pub(crate) fn show(ui: &mut Ui, session: &Session, graph_index: usize, node_id: NodeId) -> Option<Value> { + let graph = session.pkg.graphs.get(graph_index)?; + let node = graph.node(node_id).ok()?; + let ports = if node.def == "output" { + vec![("output".to_string(), materialcraft_engine::eval::identifier(node))] + } else { + materialcraft_engine::eval::ports(&session.pkg, graph, node).1.into_iter().map(|port| (port.id, port.label)).collect() + }; + let ports: Vec<_> = + ports.into_iter().filter(|(port, _)| MaterialSource { graph: graph_index, node: node_id, port: port.clone() }.is_image(&session.pkg)).collect(); + let mut action = None; + ui.add_enabled_ui(!ports.is_empty(), |ui| { + for (label, reset) in [("View in 3D view", false), ("Reset and view in 3D view", true)] { + ui.menu_button(tr(label), |ui| { + for (port, label) in &ports { + let mut channels = |ui: &mut Ui| { + for channel in MaterialChannel::ALL { + if ui.button(tr(channel.label())).clicked() { + action = Some(json!({"graph": graph_index, "node": node_id.0, "port": port, "channel": channel.id(), "reset": reset})); + ui.close(); + } + } + }; + if ports.len() == 1 { + channels(ui); + } else { + ui.menu_button(label, channels); + } + } + }); + } + }); + action +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 99bf6871..cecf4920 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -97,11 +97,7 @@ fn is_ui(id: &str) -> bool { /// Whether an item can run now pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { - if let Some(enabled) = crate::pattern::enabled(app, id) { - return enabled; - } - - if let Some(enabled) = crate::function::enabled(app, id) { + if let Some(enabled) = crate::graph::editor_actions::enabled(app, id) { return enabled; } @@ -126,11 +122,7 @@ pub fn implemented(id: &str) -> bool { /// Invoke a menu item (menus, shortcuts, the control channel's `ui.menu.invoke`) pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { - if crate::pattern::invoke(app, id) { - return; - } - - if crate::function::invoke(app, id) { + if crate::graph::editor_actions::invoke(app, id) { return; } @@ -288,7 +280,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { } // Selected wires handle deletion and swapping before nodes - if !crate::pattern::active(app) && !app.graph.selected_wires.is_empty() { + if crate::graph::editor_target::EditorTarget::resolve(app) == crate::graph::editor_target::EditorTarget::Material && !app.graph.selected_wires.is_empty() { if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { crate::graph::delete_selected_wires(app); } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) { diff --git a/crates/ui-egui/src/pattern/actions.rs b/crates/ui-egui/src/pattern/actions.rs index a8aa13d9..65b1ea09 100644 --- a/crates/ui-egui/src/pattern/actions.rs +++ b/crates/ui-egui/src/pattern/actions.rs @@ -1,4 +1,4 @@ -use super::selection; +use super::PatternEditor; use crate::MaterialCraftApp; pub(crate) fn active(app: &MaterialCraftApp) -> bool { @@ -8,18 +8,15 @@ pub(crate) fn active(app: &MaterialCraftApp) -> bool { } pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { - if command == "ui.graph.parent" { - return Some(active(app)); - } if !active(app) { return None; } - if let Some(enabled) = selection::enabled(app.pattern_editor.as_ref()?, command) { + if let Some(enabled) = editor_enabled(app, app.pattern_editor.as_ref()?, command) { return Some(enabled); } match command { - "ui.graph.snapToGrid" | "graph.cook" => None, + "ui.graph.snapToGrid" | "graph.cook" | "edit.finish" => None, command if command.starts_with("graph.") || command.starts_with("ui.graph.") @@ -32,24 +29,33 @@ pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> { } pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool { - if command == "ui.graph.parent" { - app.pattern_editor = None; - app.function_editor = None; - return true; - } let Some(allowed) = enabled(app, command) else { return false }; + if !allowed { return true; } let Some(mut editor) = app.pattern_editor.take() else { return true }; - if let Some(mut graph) = editor.current(app) { - match selection::run(&mut editor, &mut graph, command, app.ui.prefs.snap_to_grid) { - Ok(true) => editor.commit(app, graph), - Ok(false) => {} - Err(error) => app.toast(error, true), - } - } + + invoke_editor(app, &mut editor, command); app.pattern_editor = Some(editor); true } + +pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut PatternEditor, command: &str) { + if editor_enabled(app, editor, command) != Some(true) { + return; + } + let parameters = editor.selection_parameters(command); + crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters); +} + +pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &PatternEditor, command: &str) -> Option<bool> { + materialcraft_engine::selection_commands::enabled_for( + &app.session, + &materialcraft_engine::SelectionTarget::Pattern(editor.node), + &editor.selection, + command, + ) + .map(|enabled| enabled && editor.current(app).is_some()) +} diff --git a/crates/ui-egui/src/pattern/canvas.rs b/crates/ui-egui/src/pattern/canvas.rs index 41e6e6a1..296eb3a4 100644 --- a/crates/ui-egui/src/pattern/canvas.rs +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -1,5 +1,6 @@ +use crate::graph::canvas_geometry::CanvasGeometry; use egui::{Color32, Rect, Sense, Stroke, Ui, vec2}; -use materialcraft_engine::core::{NodeId, PatternGraph}; +use materialcraft_engine::core::NodeId; use materialcraft_engine::nodes::PortKind; use std::collections::BTreeMap; @@ -15,94 +16,79 @@ const PORT_COLOR: Color32 = Color32::from_rgb(165, 157, 215); pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let Some(mut editor) = app.pattern_editor.take() else { return }; - let Some(mut graph) = editor.current(app) else { return }; - editor.selection.retain(|id| graph.nodes.iter().any(|node| node.id == *id)); - let parent = app.session.graph().map(|graph| graph.name.clone()).unwrap_or_default(); - let label = app.session.graph().ok().and_then(|graph| graph.node(editor.node).ok()).map(crate::graph::node_label).unwrap_or_default(); - let mut back = false; - ui.horizontal(|ui| { - back = ui.button(&parent).on_hover_text(tr("Return to parent graph")).clicked(); - ui.label("›"); - ui.label(label); - }); - ui.horizontal(|ui| { - if ui.button(tr("Frame all")).clicked() { - editor.framed = false; - } - ui.checkbox(&mut app.ui.prefs.snap_to_grid, tr("Snap to grid")); - if graph.root.is_none() { - ui.label(tr("Set a node as the root")); - } - }); + if let Some(graph) = editor.current(app) { + let present: std::collections::BTreeSet<_> = graph.nodes.iter().map(|node| node.id).collect(); + editor.selection.retain(|id| present.contains(id)); + } + let Some((geometry, response, camera)) = paint(app, &mut editor, ui) else { return }; + + app.ui.frame_all = false; + geometry.publish(&mut app.graph, response.rect); + app.graph.frames.clear(); + app.graph.comments.clear(); + super::input::handle(app, &mut editor, ui, &response, &camera); + if let Some(PatternDrag::Wire { node, slot }) = editor.drag + && let Some(source) = app.graph.ports.iter().find(|port| { + port.node.0 == u64::from(node) + && port.output == slot.is_some() + && slot.is_none_or(|slot| port.port == format!("output{slot}") || slot == 0 && port.port == "output") + }) + && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) + { + let points = if slot.is_some() { geometry::wire(source.pos, pointer) } else { geometry::wire(pointer, source.pos) }; + ui.painter_at(response.rect).add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); + } + response.context_menu(|ui| super::context_menu::show(app, &mut editor, ui)); editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - let changed = canvas(app, &mut editor, &mut graph, ui); - editor.inspected_node = - crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node).filter(|id| graph.nodes.iter().any(|node| node.id == *id)); - if changed { - editor.commit(app, graph); - } - if back { - app.function_editor = None; - } else { - app.pattern_editor = Some(editor); - } + app.pattern_editor = Some(editor); } -fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut PatternGraph, ui: &mut Ui) -> bool { +fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Option<(CanvasGeometry, egui::Response, GraphCamera)> { + let graph = editor.current(app)?; + let selected: std::collections::BTreeSet<_> = editor.selection.iter().copied().collect(); + let mut geometry = CanvasGeometry::default(); let (bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(100.0, 100.0)), Sense::click_and_drag()); crate::widgets::name(&response, egui::Role::Canvas, "FX-Map graph"); let painter = ui.painter_at(bounds); painter.rect_filled(bounds, 0.0, Color32::from_rgb(0x26, 0x28, 0x2c)); let snap = app.ui.prefs.snap_to_grid; - let frame_key = response.hovered() && !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::F)); + let frame_key = GraphCamera::frame_key(ui, bounds); if !editor.framed || app.ui.frame_all || frame_key { - let destination = graph.nodes.iter().map(|node| geometry::bounds(node, editor, snap)).fold(Rect::NOTHING, |all, node| all.union(node)); - if destination.is_finite() { - let destination = destination.expand(48.0); - editor.zoom = (bounds.width() / destination.width()).min(bounds.height() / destination.height()).clamp(0.15, 1.2); - editor.pan = destination.center().to_vec2() - bounds.size() * 0.5 / editor.zoom; - } + let selected_only = frame_key && !editor.selection.is_empty(); + let destination = graph + .nodes + .iter() + .filter(|node| !selected_only || selected.contains(&node.id)) + .map(|node| geometry::bounds(node, editor, snap, selected.contains(&node.id))) + .fold(Rect::NOTHING, |all, node| all.union(node)); + let camera = GraphCamera::fit(bounds, destination); + editor.pan = camera.pan; + editor.zoom = camera.zoom; editor.framed = true; - app.ui.frame_all = false; } let mut camera = GraphCamera { origin: bounds.min, pan: editor.pan, zoom: editor.zoom }; - if response.hovered() - && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) - { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); - if scroll != 0.0 { - let before = camera.to_graph(pointer); - editor.zoom = (editor.zoom * (scroll * 0.0025).exp()).clamp(0.15, 3.0); - editor.pan = before.to_vec2() - (pointer - bounds.min) / editor.zoom; - camera.pan = editor.pan; - camera.zoom = editor.zoom; - } - } - crate::graph::canvas::grid(&painter, &camera, bounds); - app.graph.view = bounds; - app.graph.rects.clear(); - app.graph.ports.clear(); - app.graph.wires.clear(); - app.graph.frames.clear(); - app.graph.comments.clear(); - + camera.zoom_from_input(ui, bounds); + editor.pan = camera.pan; + editor.zoom = camera.zoom; + crate::graph::grid::paint(&painter, &camera, bounds); let rectangles: BTreeMap<_, _> = graph .nodes .iter() .map(|node| { - let bounds = geometry::bounds(node, editor, snap); + let bounds = geometry::bounds(node, editor, snap, selected.contains(&node.id)); (node.id, Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max))) }) .collect(); for node in &graph.nodes { let Some(bounds) = rectangles.get(&node.id) else { continue }; + for (slot, child) in node.children.iter().enumerate() { if let Some(child_bounds) = child.and_then(|id| rectangles.get(&id)) { let points = geometry::wire(geometry::port(*bounds, Some(slot), node.children.len()), child_bounds.center_top()); painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); - app.graph.wires.push(((NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()), points)); + geometry.wires.push(((NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()), points)); } } } @@ -110,8 +96,10 @@ fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut Pa let tokens = Tokens::get(ui.ctx()); for node in &graph.nodes { let Some(bounds) = rectangles.get(&node.id).copied() else { continue }; - app.graph.rects.push((NodeId(u64::from(node.id)), bounds)); - let outline = if editor.selection.contains(&node.id) { tokens.accent } else { Color32::from_gray(30) }; + + geometry.rects.push((NodeId(u64::from(node.id)), bounds)); + let outline = if selected.contains(&node.id) { tokens.accent } else { Color32::from_gray(30) }; + super::node_canvas::paint(&painter, bounds, node.kind, editor.zoom, outline); if graph.root == Some(node.id) { painter.text( @@ -132,7 +120,7 @@ fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut Pa painter.circle_stroke(position, 5.0 * editor.zoom, Stroke::new(1.5, Color32::from_gray(30))); ui.interact(Rect::from_center_size(position, vec2(16.0, 16.0)), response.id.with((node.id, slot)), Sense::hover()) .on_hover_text(tr("Drag to connect; Alt-click to disconnect")); - app.graph.ports.push(PortHit { + geometry.ports.push(PortHit { node: NodeId(u64::from(node.id)), output: slot.is_some(), port: slot.map_or_else(|| "input".into(), |slot| node.kind.child_port(slot).unwrap_or_default().to_string()), @@ -143,16 +131,5 @@ fn canvas(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut Pa } } - let mut changed = super::input::handle(app, editor, graph, ui, &response, &camera); - if let Some(PatternDrag::Wire { node, slot }) = editor.drag - && let Some(bounds) = rectangles.get(&node) - && let Some(pointer) = ui.input(|input| input.pointer.hover_pos()) - { - let count = graph.nodes.iter().find(|candidate| candidate.id == node).map_or(0, |node| node.children.len()); - let source = geometry::port(*bounds, slot, count); - let points = if slot.is_some() { geometry::wire(source, pointer) } else { geometry::wire(pointer, source) }; - painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); - } - response.context_menu(|ui| changed |= super::context_menu::show(app, editor, graph, ui)); - changed + Some((geometry, response, camera)) } diff --git a/crates/ui-egui/src/pattern/context_menu.rs b/crates/ui-egui/src/pattern/context_menu.rs index eb960e76..b0a4b54b 100644 --- a/crates/ui-egui/src/pattern/context_menu.rs +++ b/crates/ui-egui/src/pattern/context_menu.rs @@ -1,71 +1,39 @@ +use super::PatternEditor; +use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus}; use egui::Ui; -use materialcraft_engine::core::{PatternGraph, PatternNodeKind}; +use materialcraft_engine::{PatternEdit, core::PatternNodeKind}; -use super::{PatternEditor, selection}; -use crate::{MaterialCraftApp, i18n::tr, menus}; - -pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, graph: &mut PatternGraph, ui: &mut Ui) -> bool { - let mut changed = false; +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) { + let mut add = None; ui.menu_button(tr("Add node"), |ui| { - let kinds = PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot); - let entries = kinds.map(|kind| (kind.native_id(), kind.label(), "FX-Map")); - if let Some(id) = crate::graph::add_node_menu::show(ui, entries) - && let Some(kind) = PatternNodeKind::ALL.into_iter().find(|kind| kind.native_id() == id) - { - match editor.add(graph, kind, app.ui.prefs.snap_to_grid) { - Ok(()) => changed = true, - Err(error) => app.toast(error, true), - } + let entries = PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot).map(|kind| (kind.native_id(), kind.label(), "FX-Map")); + if let Some(id) = crate::graph::add_node_menu::show(ui, entries) { + add = PatternNodeKind::ALL.into_iter().find(|kind| kind.native_id() == id); } }); if ui.button(tr("Add Dot node")).clicked() { - match editor.add(graph, PatternNodeKind::Dot, app.ui.prefs.snap_to_grid) { - Ok(()) => changed = true, - Err(error) => app.toast(error, true), - } + add = Some(PatternNodeKind::Dot); ui.close(); } + if let Some(kind) = add { + editor.edit(app, PatternEdit::Add { kind, at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); + } if let Some(id) = editor.selection.last().copied() && ui.button(tr("Set as root")).clicked() { - graph.root = Some(id); - changed = true; + editor.edit(app, PatternEdit::Root { id }, false); ui.close(); } ui.separator(); - - for (label, command) in [ - ("Copy selection", "edit.copy"), - ("Cut selection", "edit.cut"), - ("Paste", "edit.paste"), - ("Paste without link", "edit.pasteWithoutLinks"), - ("Duplicate selection", "edit.duplicate"), - ("Duplicate selection without link", "edit.duplicateWithoutLinks"), - ("Delete selection", "edit.delete"), - ("Select all", "edit.selectAll"), - ("Select upstream nodes", "graph.selectUpstream"), - ("Select downstream nodes", "graph.selectDownstream"), - ] { - let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { - button = button.shortcut_text(shortcut); - } - if ui.add_enabled(selection::enabled(editor, command).unwrap_or(false), button).clicked() { - match selection::run(editor, graph, command, app.ui.prefs.snap_to_grid) { - Ok(edit) => changed |= edit, - Err(error) => app.toast(error, true), - } - ui.close(); - } + if edit_menu::button(ui, "Save package", "file.save", menus::enabled(app, "file.save")) { + menus::invoke(app, ui.ctx(), "file.save"); + } + if let Some(command) = edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or(false)) { + super::actions::invoke_editor(app, editor, command); } ui.separator(); if ui.button(tr("Frame all")).clicked() { editor.framed = false; ui.close(); } - if ui.add(egui::Button::new(tr("Save package")).shortcut_text("Ctrl+S")).clicked() { - menus::invoke(app, ui.ctx(), "file.save"); - ui.close(); - } - changed } diff --git a/crates/ui-egui/src/pattern/geometry.rs b/crates/ui-egui/src/pattern/geometry.rs index 01eba35f..21e98d68 100644 --- a/crates/ui-egui/src/pattern/geometry.rs +++ b/crates/ui-egui/src/pattern/geometry.rs @@ -6,12 +6,12 @@ use super::{PatternDrag, PatternEditor}; pub(super) const NODE_SIZE: f32 = 96.0; pub(super) const HEADER_HEIGHT: f32 = 18.0; -pub(super) fn bounds(node: &PatternNode, editor: &PatternEditor, snap: bool) -> Rect { +pub(super) fn bounds(node: &PatternNode, editor: &PatternEditor, snap: bool, selected: bool) -> Rect { let mut position = materialcraft_engine::graph_grid::snap_position(node.position, false); if let Some(PatternDrag::Nodes { delta, .. }) = editor.drag - && editor.selection.contains(&node.id) + && selected { - position = materialcraft_engine::graph_grid::snap_position([position[0] + delta.x, position[1] + delta.y], snap); + position = materialcraft_engine::graph_grid::translate(position, delta.into(), snap); } let position = pos2(position[0], position[1]); if node.kind == PatternNodeKind::Dot { @@ -39,6 +39,5 @@ pub(super) fn port_label(kind: PatternNodeKind, slot: usize) -> &'static str { } pub(super) fn wire(source: Pos2, destination: Pos2) -> [Pos2; 4] { - let offset = vec2(0.0, ((destination.y - source.y).abs() * 0.5).max(24.0)); - [source, source + offset, destination - offset, destination] + crate::graph::wire_geometry::curve_points(source, destination, egui::Vec2::Y) } diff --git a/crates/ui-egui/src/pattern/input.rs b/crates/ui-egui/src/pattern/input.rs index dea849c2..89a0ed0e 100644 --- a/crates/ui-egui/src/pattern/input.rs +++ b/crates/ui-egui/src/pattern/input.rs @@ -1,42 +1,35 @@ -use egui::{PointerButton, Rect, Response, Ui}; -use materialcraft_engine::core::PatternGraph; +use egui::{PointerButton, Response, Ui}; +use materialcraft_engine::PatternEdit; use super::{PatternDrag, PatternEditor}; use crate::{MaterialCraftApp, graph::GraphCamera}; -pub(super) fn handle( - app: &mut MaterialCraftApp, - editor: &mut PatternEditor, - graph: &mut PatternGraph, - ui: &Ui, - response: &Response, - camera: &GraphCamera, -) -> bool { - let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return false }; +pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &Ui, response: &Response, camera: &GraphCamera) { + if crate::graph::gesture::cancelled(ui) { + editor.drag = None; + return; + } + let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return }; + let position = camera.to_graph(pointer); - let port = app - .graph - .ports - .iter() - .filter(|port| port.pos.distance(pointer) < (6.0 * editor.zoom).clamp(1.5, 8.0)) - .min_by(|left, right| left.pos.distance_sq(pointer).total_cmp(&right.pos.distance_sq(pointer))) - .map(|port| { - ( - port.node.0 as u32, - port.output - .then(|| port.port.strip_prefix("output").and_then(|slot| if slot.is_empty() { Some(0) } else { slot.parse::<usize>().ok() })) - .flatten(), - ) - }); + let port = crate::graph::port_hit::nearest_by(&app.graph.ports, pointer, |port| (port.pos, (6.0 * editor.zoom).clamp(1.5, 8.0))).map(|port| { + ( + port.node.0 as u32, + port.output.then(|| port.port.strip_prefix("output").and_then(|slot| if slot.is_empty() { Some(0) } else { slot.parse::<usize>().ok() })).flatten(), + ) + }); let node = app.graph.rects.iter().rev().find(|(_, bounds)| bounds.contains(pointer)).map(|(id, _)| id.0 as u32); let modifiers = ui.input(|input| input.modifiers); - let mut changed = false; - if response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { + if editor.drag.is_none() + && GraphCamera::pan_started(ui, response.rect) + && !(port.is_some() && modifiers.alt && ui.input(|input| input.pointer.primary_pressed())) + { + editor.drag = Some(PatternDrag::Pan(crate::graph::gesture::pan_button(ui))); + } else if editor.drag.is_none() && response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { if let Some((id, slot)) = port { if modifiers.alt { - disconnect(graph, id, slot); - changed = true; + editor.edit(app, PatternEdit::Disconnect { node: id, slot }, false); } else { editor.drag = Some(PatternDrag::Wire { node: id, slot }); } @@ -46,36 +39,27 @@ pub(super) fn handle( editor.drag = Some(PatternDrag::Nodes { start: position, delta: egui::Vec2::ZERO }); } } else { - let additive = modifiers.shift || modifiers.ctrl || modifiers.command; crate::graph::node_selection::select(&mut editor.selection, None, modifiers); - editor.drag = Some(PatternDrag::Box { start: pointer, additive }); + editor.drag = Some(PatternDrag::Box { start: pointer }); } } - if response.drag_started_by(PointerButton::Middle) { - editor.drag = Some(PatternDrag::Pan); - } match &mut editor.drag { Some(PatternDrag::Nodes { start, delta }) => *delta = position - *start, - Some(PatternDrag::Pan) => editor.pan -= ui.input(|input| input.pointer.delta()) / editor.zoom, + Some(PatternDrag::Pan(_)) => editor.pan -= ui.input(|input| input.pointer.delta()) / editor.zoom, Some(PatternDrag::Box { start, .. }) => { - ui.painter().rect_stroke( - Rect::from_two_pos(*start, pointer), - 0.0, - egui::Stroke::new(1.0, crate::theme::Tokens::get(ui.ctx()).accent), - egui::StrokeKind::Inside, - ); + crate::graph::node_selection::paint_box(ui.painter(), *start, pointer, crate::theme::Tokens::get(ui.ctx()).accent); } _ => {} } - if ui.input(|input| input.pointer.button_released(PointerButton::Primary)) { + let owner = match editor.drag { + Some(PatternDrag::Pan(button)) => button, + _ => PointerButton::Primary, + }; + if crate::graph::gesture::finished(ui, owner) { match editor.drag.take() { - Some(PatternDrag::Nodes { delta, .. }) if delta.length_sq() > 0.01 => { - for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { - node.position = - materialcraft_engine::graph_grid::snap_position([node.position[0] + delta.x, node.position[1] + delta.y], app.ui.prefs.snap_to_grid); - } - changed = true; + Some(PatternDrag::Nodes { delta, .. }) if delta.length() > 0.5 => { + editor.edit(app, PatternEdit::Move { ids: editor.selection.clone(), by: delta.into(), snap: app.ui.prefs.snap_to_grid }, false); } Some(PatternDrag::Wire { node, slot }) => { if let Some((target, target_slot)) = port { @@ -84,32 +68,18 @@ pub(super) fn handle( (None, Some(slot)) => Some((target, slot, node)), _ => None, }; - if let Some((parent, slot, child)) = connection - && let Some(destination) = graph.nodes.iter_mut().find(|node| node.id == parent).and_then(|node| node.children.get_mut(slot)) - { - *destination = Some(child); - changed = true; + if let Some((parent, slot, child)) = connection { + editor.edit(app, PatternEdit::Connect { parent, slot, child }, false); } } } - Some(PatternDrag::Box { start, additive }) => { - if !additive { - editor.selection.clear(); - } - let bounds = Rect::from_two_pos(start, pointer); - for (id, rectangle) in &app.graph.rects { - let id = id.0 as u32; - if bounds.intersects(*rectangle) && !editor.selection.contains(&id) { - editor.selection.push(id); - } - } + Some(PatternDrag::Box { start }) => { + let nodes = app.graph.rects.iter().map(|(id, rect)| (id.0 as u32, *rect)); + crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, modifiers); } _ => {} } } - if ui.input(|input| input.pointer.button_released(PointerButton::Middle)) { - editor.drag = None; - } if response.secondary_clicked() { editor.menu_at = position; if let Some(id) = node @@ -118,23 +88,8 @@ pub(super) fn handle( crate::graph::node_selection::select(&mut editor.selection, Some(id), egui::Modifiers::NONE); } } - if response.hovered() && ui.input(|input| input.key_pressed(egui::Key::Space)) { + if response.hovered() && !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space)) { editor.menu_at = position; egui::Popup::open_id(ui.ctx(), response.id.with("menu")); } - changed -} - -fn disconnect(graph: &mut PatternGraph, id: u32, slot: Option<usize>) { - if let Some(slot) = slot { - if let Some(child) = graph.nodes.iter_mut().find(|node| node.id == id).and_then(|node| node.children.get_mut(slot)) { - *child = None; - } - } else { - for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { - if *child == Some(id) { - *child = None; - } - } - } } diff --git a/crates/ui-egui/src/pattern/library.rs b/crates/ui-egui/src/pattern/library.rs index 945e3d34..b7b1d1ef 100644 --- a/crates/ui-egui/src/pattern/library.rs +++ b/crates/ui-egui/src/pattern/library.rs @@ -9,13 +9,8 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { if ui.selectable_label(false, tr(kind.label())).double_clicked() && let Some(mut editor) = app.pattern_editor.take() { - if let Some(mut graph) = editor.current(app) { - editor.menu_at = (editor.pan + app.graph.view.size() * 0.5 / editor.zoom).to_pos2(); - match editor.add(&mut graph, kind, app.ui.prefs.snap_to_grid) { - Ok(()) => editor.commit(app, graph), - Err(error) => app.toast(error, true), - } - } + editor.menu_at = (editor.pan + app.graph.view.size() * 0.5 / editor.zoom).to_pos2(); + editor.edit(app, materialcraft_engine::PatternEdit::Add { kind, at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); app.pattern_editor = Some(editor); } } diff --git a/crates/ui-egui/src/pattern/mod.rs b/crates/ui-egui/src/pattern/mod.rs index 7a163694..dc56d042 100644 --- a/crates/ui-egui/src/pattern/mod.rs +++ b/crates/ui-egui/src/pattern/mod.rs @@ -9,7 +9,6 @@ mod parameter_value; mod pattern_drag; mod pattern_editor; pub(crate) mod properties; -mod selection; pub(crate) use actions::{active, enabled, invoke}; pub(crate) use canvas::show; diff --git a/crates/ui-egui/src/pattern/pattern_drag.rs b/crates/ui-egui/src/pattern/pattern_drag.rs index 89623bad..71a66eb1 100644 --- a/crates/ui-egui/src/pattern/pattern_drag.rs +++ b/crates/ui-egui/src/pattern/pattern_drag.rs @@ -3,6 +3,6 @@ use egui::{Pos2, Vec2}; pub(super) enum PatternDrag { Nodes { start: Pos2, delta: Vec2 }, Wire { node: u32, slot: Option<usize> }, - Box { start: Pos2, additive: bool }, - Pan, + Box { start: Pos2 }, + Pan(egui::PointerButton), } diff --git a/crates/ui-egui/src/pattern/pattern_editor.rs b/crates/ui-egui/src/pattern/pattern_editor.rs index 08a59674..772ccfe1 100644 --- a/crates/ui-egui/src/pattern/pattern_editor.rs +++ b/crates/ui-egui/src/pattern/pattern_editor.rs @@ -1,5 +1,5 @@ use egui::{Pos2, Vec2}; -use materialcraft_engine::core::{NodeId, PatternGraph, PatternNode, PatternNodeKind, Value}; +use materialcraft_engine::core::{NodeId, PatternGraph, Value}; use serde_json::json; use super::PatternDrag; @@ -10,7 +10,6 @@ pub struct PatternEditor { pub graph: usize, pub(crate) selection: Vec<u32>, pub(crate) inspected_node: Option<u32>, - pub(super) clipboard: Vec<PatternNode>, pub(super) pan: Vec2, pub(super) zoom: f32, pub(super) framed: bool, @@ -20,21 +19,10 @@ pub struct PatternEditor { impl PatternEditor { pub fn new(graph: usize, node: NodeId) -> Self { - Self { - node, - graph, - selection: Vec::new(), - inspected_node: None, - clipboard: Vec::new(), - pan: Vec2::ZERO, - zoom: 1.0, - framed: false, - drag: None, - menu_at: Pos2::ZERO, - } + Self { node, graph, selection: Vec::new(), inspected_node: None, pan: Vec2::ZERO, zoom: 1.0, framed: false, drag: None, menu_at: Pos2::ZERO } } - pub(super) fn current(&self, app: &MaterialCraftApp) -> Option<PatternGraph> { + pub(crate) fn current<'a>(&self, app: &'a MaterialCraftApp) -> Option<&'a PatternGraph> { if app.session.graph != self.graph { return None; } @@ -46,22 +34,29 @@ impl PatternEditor { let default = materialcraft_engine::nodes::find(&node.def)?.param("pattern"); match node.params.get("pattern").or_else(|| default.map(|parameter| ¶meter.default)) { - Some(Value::PatternGraph(graph)) => Some((**graph).clone()), - None => Some(PatternGraph::default()), + Some(Value::PatternGraph(graph)) => Some(graph.as_ref()), + None => { + static EMPTY: std::sync::OnceLock<PatternGraph> = std::sync::OnceLock::new(); + Some(EMPTY.get_or_init(PatternGraph::default)) + } _ => None, } } - pub(super) fn commit(&self, app: &mut MaterialCraftApp, graph: PatternGraph) { - app.run("graph.pattern.set", json!({"id": self.node.0, "pattern": graph})); + pub(crate) fn selection_parameters(&self, command: &str) -> serde_json::Value { + let selection = if matches!(command, "edit.selectAll" | "edit.selectNone") { &[][..] } else { self.selection.as_slice() }; + json!({"graph": self.graph, "pattern": self.node.0, "ids": selection, "at": [self.menu_at.x, self.menu_at.y]}) } - pub(super) fn add(&mut self, graph: &mut PatternGraph, kind: PatternNodeKind, snap: bool) -> Result<(), String> { - let id = graph.add(kind)?; - if let Some(node) = graph.nodes.iter_mut().find(|node| node.id == id) { - node.position = materialcraft_engine::graph_grid::snap_position([self.menu_at.x, self.menu_at.y], snap); + pub(super) fn edit(&mut self, app: &mut MaterialCraftApp, edit: materialcraft_engine::PatternEdit, merge: bool) { + if self.current(app).is_none() { + return; + } + + if let Some(result) = app.run("graph.pattern.edit", json!({"id": self.node.0, "edit": edit, "merge": merge})) + && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) + { + self.selection = vec![id]; } - self.selection = vec![id]; - Ok(()) } } diff --git a/crates/ui-egui/src/pattern/properties.rs b/crates/ui-egui/src/pattern/properties.rs index 5dd8de8b..4942dc5e 100644 --- a/crates/ui-egui/src/pattern/properties.rs +++ b/crates/ui-egui/src/pattern/properties.rs @@ -1,11 +1,7 @@ use egui::Ui; use materialcraft_engine::core::{FunctionGraph, Value}; -use crate::{ - MaterialCraftApp, - function::{FunctionEditor, FunctionTarget}, - i18n::tr, -}; +use crate::{MaterialCraftApp, function::FunctionTarget, i18n::tr}; pub(crate) fn title(app: &MaterialCraftApp) -> String { let kind = app.pattern_editor.as_ref().and_then(|editor| { @@ -17,13 +13,15 @@ pub(crate) fn title(app: &MaterialCraftApp) -> String { } pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Some(editor) = app.pattern_editor.take() else { return }; - let Some(mut graph) = editor.current(app) else { return }; - let mut changed = false; + let Some(mut editor) = app.pattern_editor.take() else { return }; + + let Some(graph) = editor.current(app) else { return }; + + let mut edits = Vec::new(); let mut function_target = None; let inspected = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); - if let Some(node) = graph.nodes.iter_mut().find(|node| Some(node.id) == inspected) { + if let Some(node) = graph.nodes.iter().find(|node| Some(node.id) == inspected) { ui.heading(tr(node.kind.label())); if graph.root == Some(node.id) { ui.label(tr("Root node")); @@ -32,25 +30,33 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { for parameter in &definition.params { ui.push_id(parameter.id, |ui| { ui.label(tr(parameter.label)); - let mut value = node.parameters.get(parameter.id).unwrap_or(¶meter.default).clone(); ui.horizontal_wrapped(|ui| { + let value = node.parameters.get(parameter.id).unwrap_or(¶meter.default); if matches!(value, Value::Function(_)) { if ui.small_button(tr("Edit function")).clicked() { function_target = Some(FunctionTarget::Pattern { node: node.id, parameter: parameter.id.to_string() }); } if ui.small_button(tr("Reset")).clicked() { - node.parameters.remove(parameter.id); - changed = true; + edits.push((materialcraft_engine::PatternEdit::Value { id: node.id, parameter: parameter.id.into(), value: None }, false)); } } else { + let mut value = value.clone(); if super::parameter_value::show(ui, parameter.id, &mut value) { - node.parameters.insert(parameter.id.to_string(), value.clone()); - changed = true; + edits.push(( + materialcraft_engine::PatternEdit::Value { id: node.id, parameter: parameter.id.into(), value: Some(value.clone()) }, + true, + )); } if ui.small_button(tr("Function")).clicked() { - node.parameters.insert(parameter.id.to_string(), Value::Function(Box::new(FunctionGraph::constant(value)))); + edits.push(( + materialcraft_engine::PatternEdit::Value { + id: node.id, + parameter: parameter.id.into(), + value: Some(Value::Function(Box::new(FunctionGraph::constant(value)))), + }, + false, + )); function_target = Some(FunctionTarget::Pattern { node: node.id, parameter: parameter.id.to_string() }); - changed = true; } } }); @@ -62,11 +68,11 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.heading(tr("FX-Map")); ui.label(tr("Select a node to edit its parameters")); } - if changed { - editor.commit(app, graph); + for (edit, merge) in edits { + editor.edit(app, edit, merge); } if let Some(target) = function_target { - app.function_editor = Some(FunctionEditor::new(editor.node, target)); + crate::graph::subgraph_navigation::open_function(app, editor.node, target); } app.pattern_editor = Some(editor); } diff --git a/crates/ui-egui/src/pattern/selection.rs b/crates/ui-egui/src/pattern/selection.rs deleted file mode 100644 index 226a129c..00000000 --- a/crates/ui-egui/src/pattern/selection.rs +++ /dev/null @@ -1,88 +0,0 @@ -use materialcraft_engine::core::PatternGraph; -use std::collections::{BTreeMap, BTreeSet}; - -use super::PatternEditor; - -pub(super) fn enabled(editor: &PatternEditor, command: &str) -> Option<bool> { - Some(match command { - "edit.selectAll" | "edit.selectNone" => true, - "edit.paste" | "edit.pasteWithoutLinks" => !editor.clipboard.is_empty(), - "edit.copy" | "edit.cut" | "edit.delete" | "edit.duplicate" | "edit.duplicateWithoutLinks" | "graph.selectUpstream" | "graph.selectDownstream" => { - !editor.selection.is_empty() - } - _ => return None, - }) -} - -pub(super) fn run(editor: &mut PatternEditor, graph: &mut PatternGraph, command: &str, snap: bool) -> Result<bool, String> { - match command { - "edit.selectAll" => editor.selection = graph.nodes.iter().map(|node| node.id).collect(), - "edit.selectNone" => editor.selection.clear(), - "edit.copy" | "edit.cut" => { - editor.clipboard = graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect(); - if command == "edit.cut" { - return Ok(remove(editor, graph)); - } - } - "edit.delete" => return Ok(remove(editor, graph)), - "edit.duplicate" | "edit.duplicateWithoutLinks" | "edit.paste" | "edit.pasteWithoutLinks" => { - let duplicate = command.starts_with("edit.duplicate"); - let nodes = - if duplicate { graph.nodes.iter().filter(|node| editor.selection.contains(&node.id)).cloned().collect() } else { editor.clipboard.clone() }; - let anchor = nodes.first().map_or([0.0; 2], |node| node.position); - let offset = if duplicate { [32.0; 2] } else { [editor.menu_at.x - anchor[0], editor.menu_at.y - anchor[1]] }; - let present: BTreeSet<_> = graph.nodes.iter().map(|node| node.id).collect(); - let mut ids = BTreeMap::new(); - for mut node in nodes { - let original = node.id; - node.id = graph.add(node.kind)?; - node.position = materialcraft_engine::graph_grid::snap_position([node.position[0] + offset[0], node.position[1] + offset[1]], snap); - ids.insert(original, node.id); - if let Some(destination) = graph.nodes.last_mut() { - *destination = node; - } - } - editor.selection = ids.values().copied().collect(); - for node in graph.nodes.iter_mut().filter(|node| editor.selection.contains(&node.id)) { - for child in &mut node.children { - *child = child.and_then(|id| ids.get(&id).copied().or_else(|| (!command.ends_with("WithoutLinks") && present.contains(&id)).then_some(id))); - } - } - return Ok(!ids.is_empty()); - } - "graph.selectUpstream" | "graph.selectDownstream" => { - let mut visited = BTreeSet::new(); - let mut pending = editor.selection.clone(); - while let Some(id) = pending.pop() { - if !visited.insert(id) { - continue; - } - if command == "graph.selectDownstream" { - if let Some(node) = graph.nodes.iter().find(|node| node.id == id) { - pending.extend(node.children.iter().flatten()); - } - } else { - pending.extend(graph.nodes.iter().filter(|node| node.children.contains(&Some(id))).map(|node| node.id)); - } - } - editor.selection = visited.into_iter().collect(); - } - _ => {} - } - Ok(false) -} - -fn remove(editor: &mut PatternEditor, graph: &mut PatternGraph) -> bool { - let before = graph.nodes.len(); - graph.nodes.retain(|node| !editor.selection.contains(&node.id)); - for child in graph.nodes.iter_mut().flat_map(|node| &mut node.children) { - if child.is_some_and(|id| editor.selection.contains(&id)) { - *child = None; - } - } - if graph.root.is_some_and(|id| editor.selection.contains(&id)) { - graph.root = None; - } - editor.selection.clear(); - graph.nodes.len() != before -} diff --git a/crates/ui-egui/src/properties.rs b/crates/ui-egui/src/properties.rs deleted file mode 100644 index 5046718b..00000000 --- a/crates/ui-egui/src/properties.rs +++ /dev/null @@ -1,810 +0,0 @@ -use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::{Curve, Gradient, NodeId, OutputFormat, SizeMode, Value}; -use materialcraft_engine::nodes::ParameterDefinition; -use serde_json::{Value as J, json}; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// The panel title: "<node> - Properties" or "<graph> - Properties" -pub fn title(app: &MaterialCraftApp) -> String { - if crate::pattern::active(app) { - return crate::pattern::properties::title(app); - } - - if let Some(selection) = app.session.annotation_selection { - let name = match selection { - materialcraft_engine::AnnotationSelection::Frame(_) => tr("Frame"), - materialcraft_engine::AnnotationSelection::Comment(_) => tr("Comment"), - }; - return format!("{name} - {}", tr("Properties")); - } - - if let Some(title) = crate::function::properties::title(app) { - return title; - } - - let sel = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) - .and_then(|id| app.session.graph().ok()?.node(id).ok().map(crate::graph::node_label)); - let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default(); - format!("{name} - {}", tr("Properties")) -} - -pub(crate) fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); - let id = ui.make_persistent_id(id); - let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); - crate::widgets::name(&resp, egui::Role::Button, title); - ui.painter().rect_filled(r, 3.0, tk.row); - let chev = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT }; - ui.painter().text(r.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chev, egui::FontId::proportional(10.0), tk.text_dim); - ui.painter().text(r.left_center() + vec2(20.0, 0.0), egui::Align2::LEFT_CENTER, title.to_uppercase(), egui::FontId::proportional(10.5), tk.text_strong); - if resp.clicked() { - state.toggle(ui); - } - state.show_body_unindented(ui, |ui| { - ui.add_space(3.0); - body(ui); - ui.add_space(6.0); - }); -} - -pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.set_width(ui.available_width()); - if crate::pattern::active(app) { - crate::pattern::properties::show(app, ui); - return; - } - - if let Some(selection) = app.session.annotation_selection { - ui.push_id((app.session.graph, format!("{selection:?}")), |ui| crate::annotation::show(app, ui, selection)); - return; - } - - if crate::function::properties::show(app, ui) { - return; - } - - let node = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) - .and_then(|id| app.session.graph().ok()?.node(id).ok().cloned()); - ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { - Some(n) => node_props(app, ui, &n), - None => graph_props(app, ui), - }); - }); -} - -fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let tk = Tokens::get(ui.ctx()); - let def = materialcraft_engine::nodes::find(&n.def); - // Header: label (renamable) and description - ui.horizontal(|ui| { - ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph::header_color(&n.def)); - ui.add_space(8.0); - let mut label = if n.label.is_empty() { crate::graph::node_label(n) } else { n.label.clone() }; - let r = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)); - crate::widgets::name(&r, egui::Role::TextInput, "Node label"); - if r.changed() { - app.run("graph.node.rename", json!({"id": n.id.0, "label": label})); - } - }); - if let Some(d) = def - && !d.description.is_empty() - { - ui.label(RichText::new(d.description).size(11.0).color(tk.text_dim)); - } - if let Some(r) = app.session.cooked.nodes.get(&n.id) - && let Some(e) = &r.error - { - ui.label(RichText::new(format!("{} {e}", icon::WARNING)).color(tk.danger)); - } - ui.add_space(4.0); - section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, n)); - crate::value_input_editor::show(app, ui, n); - if n.def == "input_value" { - crate::value_input_editor::default_value(app, ui, n); - } - if n.def == "graph_instance" { - section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, n)); - return; - } - let Some(def) = def else { return }; - if def.params.is_empty() { - return; - } - section(ui, "specific", tr("Specific parameters"), |ui| { - if n.def == "levels" { - crate::levels_editor::show(app, ui, n); - ui.add_space(6.0); - } - let exposed: Vec<(String, String)> = - app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default(); - for p in &def.params { - if n.def == "input_value" && p.id == "default" { - continue; - } - let cur = n.params.get(p.id).cloned().unwrap_or_else(|| p.default.clone()); - if n.functions.contains_key(p.id) { - function_row(app, ui, n.id, p.id, p.label); - continue; - } - let bound = n.bindings.get(p.id).cloned(); - param_row(app, ui, n.id, p, cur, bound, &exposed); - } - }); -} - -fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let b = &n.base; - let id = n.id.0; - let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")]; - let cur = modes.iter().find(|m| m.0 == b.size_mode).map_or("", |m| m.1); - crate::widgets::combo(ui, tr("Output size"), tr(cur), |ui| { - for (m, label) in modes { - if ui.selectable_label(b.size_mode == m, tr(label)).clicked() { - let key = match m { - SizeMode::RelativeToInput => "relativeToInput", - SizeMode::RelativeToParent => "relativeToParent", - SizeMode::Absolute => "absolute", - }; - - let size = if m == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; - app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); - } - } - }); - let (lo, hi) = if b.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) }; - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut v = b.size[axis] as f32; - let caption = if b.size_mode == SizeMode::Absolute { - format!("{label} {} px", 1u32 << b.size[axis].clamp(4, 13)) - } else { - format!("{label} x {}", 2f32.powi(b.size[axis])) - }; - - if crate::widgets::slider(ui, &caption, &mut v, lo..=hi, 0).changed() { - let mut size = b.size; - size[axis] = v.round() as i32; - app.run("graph.node.base", json!({"id": id, "size": size})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(b.format.label()), |ui| { - for f in OutputFormat::ALL { - if ui.selectable_label(b.format == f, tr(f.label())).clicked() { - let key = match f { - OutputFormat::Inherit => "inherit", - OutputFormat::U8 => "u8", - OutputFormat::U16 => "u16", - OutputFormat::F16 => "f16", - OutputFormat::F32 => "f32", - }; - - app.run("graph.node.base", json!({"id": id, "format": key})); - } - } - }); - let mut seed = b.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64})); - } - if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { - let s = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000; - app.run("graph.node.base", json!({"id": id, "seed": s})); - } - let mut tiling = b.tiling[0] && b.tiling[1]; - if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() { - app.run("graph.node.base", json!({"id": id, "tiling": tiling})); - } -} - -fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: J) { - app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value})); -} - -fn typed(v: &Value) -> J { - serde_json::to_value(v).unwrap_or(J::Null) -} - -/// One parameter: its editor, plus the expose/bind menu -fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParameterDefinition, cur: Value, bound: Option<String>, exposed: &[(String, String)]) { - let tk = Tokens::get(ui.ctx()); - if let Some(input) = &bound { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tk.accent)); - if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": J::Null})); - } - }); - return; - } - let resp_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| { - resp.context_menu(|ui| { - if ui.button(tr("Reset to default")).clicked() { - app.run("graph.node.reset", json!({"id": node.0, "param": p.id})); - ui.close(); - } - let dynamic = !matches!(p.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_)); - if dynamic && ui.button(tr("Set function...")).clicked() { - if app.run("graph.node.function", json!({"id": node.0, "param": p.id})).is_some() { - app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Dynamic(p.id.to_string()))); - } - ui.close(); - } - if ui.button(tr("Expose as graph input")).clicked() { - app.run("graph.exposed.add", json!({"id": p.id, "label": p.label, "bind": {"node": node.0, "param": p.id}})); - ui.close(); - } - if !exposed.is_empty() { - ui.menu_button(tr("Bind to input"), |ui| { - for (id, label) in exposed { - if ui.button(label).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": id})); - ui.close(); - } - } - }); - } - }); - }; - - match cur { - Value::Float(mut v) => { - if p.angle { - let mut deg = v * 360.0; - let r = crate::widgets::slider(ui, tr(p.label), &mut deg, -360.0..=360.0, 1); - if r.changed() { - v = deg / 360.0; - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } else { - let (lo, hi) = (p.min.min(v), p.max.max(v)); - let r = crate::widgets::slider(ui, tr(p.label), &mut v, lo..=hi, if hi - lo > 20.0 { 1 } else { 3 }); - if r.changed() { - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } - } - Value::Int(i) => { - let mut v = i as f32; - let range = p.min.min(v)..=p.max.max(v); - let r = crate::widgets::slider(ui, tr(p.label), &mut v, range, 0); - if r.changed() && v.round() as i32 != i { - set(app, node, p.id, json!(v.round() as i32)); - } - resp_menu(app, &r); - } - Value::Float2(v) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - let mut nv = v; - for (k, axis) in ["X", "Y"].iter().enumerate() { - let range = p.min.min(nv[k])..=p.max.max(nv[k]); - let r = crate::widgets::slider(ui, axis, &mut nv[k], range, 3); - if r.changed() { - set(app, node, p.id, json!(nv)); - } - resp_menu(app, &r); - } - } - Value::Int2(v) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - for k in 0..2 { - let mut f = v[k] as f32; - if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, p.min..=p.max, 0).changed() { - let mut nv = v; - nv[k] = f.round() as i32; - set(app, node, p.id, json!(nv)); - } - } - } - Value::Bool(b) => { - let mut v = b; - let r = ui.checkbox(&mut v, tr(p.label)); - if r.changed() { - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } - Value::Float3(_) | Value::Float4(_) | Value::Int3(_) | Value::Int4(_) => { - ui.label(tr(p.label)); - let mut value = cur.clone(); - if crate::value_editor::show(ui, &mut value) { - set(app, node, p.id, serde_json::to_value(value).unwrap_or_default()); - } - } - Value::Color(c) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut rgb = [c[0], c[1], c[2]]; - if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, p.id), &mut rgb, 90.0) { - set(app, node, p.id, json!([rgb[0], rgb[1], rgb[2], c[3]])); - } - }); - }); - } - Value::Enum(i) => { - let cur = p.options.get(i as usize).copied().unwrap_or("?"); - crate::widgets::combo(ui, tr(p.label), tr(cur), |ui| { - for (k, o) in p.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, tr(o)).clicked() { - set(app, node, p.id, json!(k)); - } - } - }); - } - Value::Text(t) if p.resource => { - let names: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect(); - crate::widgets::combo(ui, tr(p.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| { - for n in &names { - if ui.selectable_label(*n == t, n).clicked() { - set(app, node, p.id, json!(n)); - } - } - }); - if ui.button(format!("{} {}", icon::IMAGE, tr("Import bitmap..."))).clicked() { - crate::menus::invoke(app, ui.ctx(), "file.importBitmap"); - } - } - Value::Text(t) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - let mut s = t.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, p.label); - if r.changed() { - set(app, node, p.id, json!(s)); - } - }); - } - Value::Curve(c) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, p.id), &c) { - set(app, node, p.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>())); - } - } - Value::Gradient(g) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, p.id), &g) { - set(app, node, p.id, typed(&Value::Gradient(ng))); - } - } - Value::PatternGraph(graph) => { - ui.label(format!("{}: {} nodes", p.label, graph.nodes.len())); - } - Value::Function(f) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - crate::windows::function_summary(app, ui, node, p.id, &f); - } - } -} - -/// A parameter driven by a function: its label, Edit and Remove -fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr(label)).color(tk.text)); - ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tk.accent)); - if ui.small_button(tr("Edit")).clicked() { - app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Dynamic(param.to_string()))); - } - if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { - app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); - } - }); -} - -fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let tk = Tokens::get(ui.ctx()); - let Some((gi, sub)) = materialcraft_engine::eval::instance_graph(&app.session.pkg, n) else { - ui.label(RichText::new(tr("The instanced graph is missing")).color(tk.danger)); - return; - }; - - let exposed = sub.exposed.clone(); - if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() { - app.run("graph.open", json!({"graph": gi})); - return; - } - if exposed.is_empty() { - ui.label(RichText::new(tr("This graph exposes no inputs")).color(tk.text_dim)); - } - for e in exposed { - let cur = n.params.get(&e.id).cloned().unwrap_or_else(|| e.default.clone()); - if let Some(v) = input_editor(ui, &e, &cur) { - app.run("graph.node.param", json!({"id": n.id.0, "param": e.id, "value": v})); - } - } -} - -/// The editor for one exposed input's value; returns the new value as JSON when it changed -fn input_editor(ui: &mut Ui, e: &materialcraft_engine::core::ExposedParameter, cur: &Value) -> Option<J> { - match *cur { - Value::Float(mut f) => { - let v0 = f; - crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 3).changed().then(|| json!(f)) - } - Value::Int(i) => { - let mut f = i as f32; - let v0 = f; - crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 0).changed().then(|| json!(f.round())) - } - Value::Bool(mut b) => ui.checkbox(&mut b, &e.label).changed().then(|| json!(b)), - Value::Enum(i) => { - let mut out = None; - crate::widgets::combo(ui, &e.label, e.options.get(i as usize).cloned().unwrap_or_default(), |ui| { - for (k, o) in e.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, o).clicked() { - out = Some(json!(k)); - } - } - }); - out - } - Value::Color(c) => { - let mut rgb = [c[0], c[1], c[2]]; - let mut out = None; - ui.horizontal(|ui| { - ui.label(&e.label); - if crate::widgets::color_swatch(ui, &format!("exp-{}", e.id), &mut rgb, 80.0) { - out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]])); - } - }); - out - } - ref other => { - ui.label(format!("{}: {}", e.label, other.type_name())); - None - } - } -} - -fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let Ok(g) = app.session.graph() else { - ui.label(tr("No graph is open")); - return; - }; - - let g = g.clone(); - section(ui, "graph-base", tr("Base parameters"), |ui| { - ui.horizontal(|ui| { - ui.label(tr("Name")); - let mut name = g.name.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, "Graph name"); - if r.lost_focus() && name != g.name { - app.run("graph.rename", json!({"name": name})); - } - }); - if g.function.is_some() { - return; - } - - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut v = g.size[axis] as f32; - if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << g.size[axis]), &mut v, 4.0..=13.0, 0).changed() { - let mut s = g.size; - s[axis] = v.round() as u32; - app.run("graph.size", json!({"log2": s})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(g.format.label()), |ui| { - for (f, key) in [(OutputFormat::U8, "u8"), (OutputFormat::U16, "u16"), (OutputFormat::F16, "f16"), (OutputFormat::F32, "f32")] { - if ui.selectable_label(g.format == f, tr(f.label())).clicked() { - app.run("graph.format", json!({"format": key})); - } - } - }); - let mut seed = g.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.seed", json!({"seed": seed.round() as i64})); - } - }); - section(ui, "graph-attr", tr("Attributes"), |ui| { - for (key, label, cur) in [ - ("category", "Category", &g.attributes.category), - ("description", "Description", &g.attributes.description), - ("author", "Author", &g.attributes.author), - ("tags", "Tags", &g.attributes.tags), - ] { - ui.horizontal(|ui| { - ui.label(tr(label)); - let mut s = cur.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, label); - if r.lost_focus() && s != *cur { - app.run("graph.attributes", json!({key: s})); - } - }); - } - }); - section(ui, "graph-inputs", tr("Input parameters"), |ui| { - if g.exposed.is_empty() { - ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tk.text_dim)); - } else { - presets_bar(app, ui, &g); - } - let mut groups: Vec<&str> = Vec::new(); - for e in &g.exposed { - if !groups.contains(&e.group.as_str()) { - groups.push(&e.group); - } - } - let mut last_group: Option<&str> = None; - let mut order: Vec<&materialcraft_engine::core::ExposedParameter> = Vec::new(); - for grp in &groups { - order.extend(g.exposed.iter().filter(|e| e.group == *grp)); - } - for e in order { - if last_group != Some(e.group.as_str()) && !e.group.is_empty() { - ui.label(RichText::new(e.group.to_uppercase()).size(10.5).strong().color(tk.text_dim)); - } - last_group = Some(e.group.as_str()); - let cur = g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()); - ui.horizontal(|ui| { - if crate::widgets::icon_button(ui, icon::X, tr("Delete input"), false, 18.0).clicked() { - app.run("graph.exposed.delete", json!({"id": e.id})); - } - ui.vertical(|ui| { - if let Some(v) = input_editor(ui, e, &cur) { - app.run("graph.exposed.set", json!({"id": e.id, "value": v})); - } - }); - }); - } - }); - input_previews(app, ui, &g); - section(ui, "graph-outputs", tr("Outputs"), |ui| { - for n in g.nodes.iter().filter(|n| n.def == "output") { - let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize; - let label = format!( - "{} {} | {}", - icon::SIGN_OUT, - materialcraft_engine::nodes::atomic::USAGES.get(usage).copied().unwrap_or("Any"), - materialcraft_engine::eval::identifier(n) - ); - if ui.add(egui::Button::selectable(app.session.view2d.node == Some(n.id), label)).clicked() { - app.run("view.2d", json!({"node": n.id.0})); - } - } - }); -} - -/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such as a mesh map baked in TextureCraft -fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { - let inputs = materialcraft_engine::material_cmds::image_inputs(g); - if inputs.is_empty() { - return; - } - let resources: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect(); - section(ui, "graph-input-images", tr("Input previews"), |ui| { - for i in &inputs { - let id = &i.identifier; - let bound = g.input_images.get(id); - ui.horizontal(|ui| { - ui.label(id); - egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| { - if ui.selectable_label(bound.is_none(), tr("None")).clicked() { - app.run("graph.input.unbind", json!({"identifier": id})); - } - for r in &resources { - if ui.selectable_label(bound == Some(r), r).clicked() { - app.run("graph.input.bind", json!({"identifier": id, "resource": r})); - } - } - }); - #[cfg(not(target_arch = "wasm32"))] - if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() - && let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - { - app.run("graph.input.bind", json!({"identifier": id, "path": p.display().to_string()})); - } - }); - } - }); -} - -/// Presets: apply one, save the current inputs under a name, delete one -fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { - let name_id = ui.make_persistent_id("preset-name"); - let mut name: String = ui.data(|d| d.get_temp(name_id)).unwrap_or_default(); - ui.horizontal(|ui| { - let names: Vec<String> = g.presets.iter().map(|p| p.name.clone()).collect(); - let r = egui::ComboBox::from_id_salt("presets").width(110.0).selected_text(tr("Presets")).show_ui(ui, |ui| { - for n in &names { - if ui.button(n).clicked() { - app.run("graph.preset.apply", json!({"name": n})); - } - } - if names.is_empty() { - ui.label(tr("No presets yet")); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Presets"); - let t = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tr("Preset name")).desired_width(90.0)); - crate::widgets::name(&t, egui::Role::TextInput, "Preset name"); - if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save preset"), false, 20.0).clicked() && !name.trim().is_empty() { - app.run("graph.preset.save", json!({"name": name})); - } - if crate::widgets::icon_button(ui, icon::X, tr("Delete preset"), false, 20.0).clicked() && !name.trim().is_empty() { - app.run("graph.preset.delete", json!({"name": name})); - } - }); - ui.data_mut(|d| d.insert_temp(name_id, name)); -} - -/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. Returns the new curve when it changed -pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> { - let tk = Tokens::get(ui.ctx()); - let w = ui.available_width().min(240.0); - let (rect, resp) = ui.allocate_exact_size(vec2(w, w * 0.75), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Curve editor"); - let p = ui.painter_at(rect); - p.rect_filled(rect, 4.0, tk.field); - for i in 1..4 { - let t = i as f32 / 4.0; - p.line_segment([pos2(rect.left() + rect.width() * t, rect.top()), pos2(rect.left() + rect.width() * t, rect.bottom())], Stroke::new(1.0, tk.separator)); - p.line_segment([pos2(rect.left(), rect.top() + rect.height() * t), pos2(rect.right(), rect.top() + rect.height() * t)], Stroke::new(1.0, tk.separator)); - } - let to_s = |x: f32, y: f32| pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height()); - let from_s = |s: Pos2| (((s.x - rect.left()) / rect.width()).clamp(0.0, 1.0), ((rect.bottom() - s.y) / rect.height()).clamp(0.0, 1.0)); - let pts: Vec<Pos2> = (0..=64).map(|i| i as f32 / 64.0).map(|x| to_s(x, c.eval(x).clamp(0.0, 1.0))).collect(); - p.add(egui::Shape::line(pts, Stroke::new(2.0, tk.accent))); - let drag_id = ui.make_persistent_id(id).with("drag"); - let mut dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id)); - let pointer = resp.interact_pointer_pos().or(resp.hover_pos()); - let nearest = pointer.and_then(|q| { - c.points - .iter() - .enumerate() - .map(|(i, pt)| (i, to_s(pt.x, pt.y).distance(q))) - .filter(|(_, d)| *d < 10.0) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(i, _)| i) - }); - for (i, pt) in c.points.iter().enumerate() { - let hot = Some(i) == nearest || Some(i) == dragging; - p.circle(to_s(pt.x, pt.y), if hot { 5.0 } else { 4.0 }, tk.panel, Stroke::new(1.5, if hot { tk.text_strong } else { tk.text })); - } - let mut out: Option<Curve> = None; - if resp.drag_started() { - dragging = nearest; - } - if resp.dragged() - && let (Some(i), Some(q)) = (dragging, pointer) - { - let (x, y) = from_s(q); - let mut nc = c.clone(); - let last = nc.points.len().saturating_sub(1); - if let Some(pt) = nc.points.get_mut(i) { - // End points keep their x - if i != 0 && i != last { - pt.x = x; - } - pt.y = y; - } - nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); - out = Some(nc); - } - if resp.drag_stopped() { - dragging = None; - } - ui.data_mut(|d| d.insert_temp(drag_id, dragging)); - if resp.double_clicked() - && let Some(q) = pointer - { - let (x, _) = from_s(q); - let mut nc = c.clone(); - nc.points.push(materialcraft_engine::core::CurvePoint::new(x, c.eval(x))); - nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); - out = Some(nc); - } - if resp.secondary_clicked() - && let Some(i) = nearest - && i != 0 - && i + 1 != c.points.len() - { - let mut nc = c.clone(); - nc.points.remove(i); - out = Some(nc); - } - out -} - -/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a key's color, right-click a key to remove it -pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option<Gradient> { - let tk = Tokens::get(ui.ctx()); - let w = ui.available_width().min(260.0); - let (rect, resp) = ui.allocate_exact_size(vec2(w, 30.0), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Gradient editor"); - let p = ui.painter_at(rect.expand(6.0)); - let bar = Rect::from_min_size(rect.min, vec2(w, 18.0)); - let n = 64; - for i in 0..n { - let t0 = i as f32 / n as f32; - let c = g.eval(t0 + 0.5 / n as f32); - let q = |v: f32| (materialcraft_engine::image::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0) as u8; - let r = Rect::from_min_max(pos2(bar.left() + bar.width() * t0, bar.top()), pos2(bar.left() + bar.width() * (t0 + 1.0 / n as f32) + 0.5, bar.bottom())); - p.rect_filled(r, 0.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); - } - p.rect_stroke(bar, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let sel_id = ui.make_persistent_id(id).with("sel"); - let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0); - let key_x = |pos: f32| bar.left() + pos * bar.width(); - let pointer = resp.interact_pointer_pos().or(resp.hover_pos()); - let nearest = pointer.and_then(|q| { - g.keys.iter().enumerate().map(|(i, k)| (i, (key_x(k.pos) - q.x).abs())).filter(|(_, d)| *d < 7.0).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) - }); - for (i, k) in g.keys.iter().enumerate() { - let x = key_x(k.pos); - let tri = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 10.0), pos2(x + 5.0, bar.bottom() + 10.0)]; - p.add(egui::Shape::convex_polygon(tri, if i == sel { tk.accent } else { tk.text }, Stroke::NONE)); - } - let mut out: Option<Gradient> = None; - if resp.drag_started() - && let Some(i) = nearest - { - sel = i; - } - if resp.dragged() - && let Some(q) = pointer - && nearest.is_some() - { - let mut ng = g.clone(); - if let Some(k) = ng.keys.get_mut(sel) { - k.pos = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); - } - let moved = ng.keys.get(sel).copied(); - ng.sort(); - if let Some(m) = moved { - sel = ng.keys.iter().position(|k| k.pos == m.pos && k.color == m.color).unwrap_or(sel); - } - out = Some(ng); - } - if resp.clicked() - && let Some(q) = pointer - { - match nearest { - Some(i) => sel = i, - None => { - let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); - let mut ng = g.clone(); - ng.keys.push(materialcraft_engine::core::GradientKey::new(t, g.eval(t))); - ng.sort(); - sel = ng.keys.iter().position(|k| k.pos == t).unwrap_or(0); - out = Some(ng); - } - } - } - if resp.secondary_clicked() - && let Some(i) = nearest - && g.keys.len() > 1 - { - let mut ng = g.clone(); - ng.keys.remove(i); - sel = 0; - out = Some(ng); - } - ui.data_mut(|d| d.insert_temp(sel_id, sel)); - if let Some(k) = g.keys.get(sel) { - ui.horizontal(|ui| { - ui.label(RichText::new(format!("{} {:.2}", tr("Key at"), k.pos)).size(11.0).color(tk.text_dim)); - let mut rgb = [k.color[0], k.color[1], k.color[2]]; - if crate::widgets::color_swatch(ui, &format!("{id}-key"), &mut rgb, 60.0) { - let mut ng = out.clone().unwrap_or_else(|| g.clone()); - if let Some(kk) = ng.keys.get_mut(sel) { - kk.color = [rgb[0], rgb[1], rgb[2], kk.color[3]]; - } - out = Some(ng); - } - }); - } - out -} diff --git a/crates/ui-egui/src/property/curve.rs b/crates/ui-egui/src/property/curve.rs new file mode 100644 index 00000000..888c2f17 --- /dev/null +++ b/crates/ui-egui/src/property/curve.rs @@ -0,0 +1,93 @@ +use crate::theme::Tokens; +use egui::{Pos2, Sense, Stroke, Ui, pos2, vec2}; +use materialcraft_engine::core::Curve; + +/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. Returns the new curve when it changed +pub fn curve_editor(ui: &mut Ui, id: &str, curve: &Curve) -> Option<Curve> { + let tokens = Tokens::get(ui.ctx()); + let width = ui.available_width().min(240.0); + let (rect, response) = ui.allocate_exact_size(vec2(width, width * 0.75), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Curve editor"); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 4.0, tokens.field); + for i in 1..4 { + let t = i as f32 / 4.0; + painter.line_segment( + [pos2(rect.left() + rect.width() * t, rect.top()), pos2(rect.left() + rect.width() * t, rect.bottom())], + Stroke::new(1.0, tokens.separator), + ); + painter.line_segment( + [pos2(rect.left(), rect.top() + rect.height() * t), pos2(rect.right(), rect.top() + rect.height() * t)], + Stroke::new(1.0, tokens.separator), + ); + } + let to_screen = |x: f32, y: f32| pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height()); + let from_screen = |s: Pos2| (((s.x - rect.left()) / rect.width()).clamp(0.0, 1.0), ((rect.bottom() - s.y) / rect.height()).clamp(0.0, 1.0)); + let curve_points: Vec<Pos2> = (0..=64).map(|i| i as f32 / 64.0).map(|x| to_screen(x, curve.eval(x).clamp(0.0, 1.0))).collect(); + painter.add(egui::Shape::line(curve_points, Stroke::new(2.0, tokens.accent))); + let drag_id = ui.make_persistent_id(id).with("drag"); + let mut dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id)); + let pointer = response.interact_pointer_pos().or(response.hover_pos()); + let nearest = pointer.and_then(|pointer_position| { + curve + .points + .iter() + .enumerate() + .map(|(i, point)| (i, to_screen(point.x, point.y).distance(pointer_position))) + .filter(|(_, d)| *d < 10.0) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + }); + for (i, point) in curve.points.iter().enumerate() { + let hot = Some(i) == nearest || Some(i) == dragging; + painter.circle( + to_screen(point.x, point.y), + if hot { 5.0 } else { 4.0 }, + tokens.panel, + Stroke::new(1.5, if hot { tokens.text_strong } else { tokens.text }), + ); + } + let mut edited_curve: Option<Curve> = None; + if response.drag_started() { + dragging = nearest; + } + if response.dragged() + && let (Some(i), Some(pointer_position)) = (dragging, pointer) + { + let (x, y) = from_screen(pointer_position); + let mut updated_curve = curve.clone(); + let last = updated_curve.points.len().saturating_sub(1); + if let Some(point) = updated_curve.points.get_mut(i) { + // End points keep their x + if i != 0 && i != last { + point.x = x; + } + point.y = y; + } + updated_curve.points.sort_by(|a, b| a.x.total_cmp(&b.x)); + edited_curve = Some(updated_curve); + } + if response.drag_stopped() { + dragging = None; + } + ui.data_mut(|d| d.insert_temp(drag_id, dragging)); + if response.double_clicked() + && let Some(pointer_position) = pointer + { + let (x, _) = from_screen(pointer_position); + let mut updated_curve = curve.clone(); + updated_curve.points.push(materialcraft_engine::core::CurvePoint::new(x, curve.eval(x))); + updated_curve.points.sort_by(|a, b| a.x.total_cmp(&b.x)); + edited_curve = Some(updated_curve); + } + if response.secondary_clicked() + && let Some(i) = nearest + && i != 0 + && i + 1 != curve.points.len() + { + let mut updated_curve = curve.clone(); + updated_curve.points.remove(i); + edited_curve = Some(updated_curve); + } + edited_curve +} diff --git a/crates/ui-egui/src/property/gradient.rs b/crates/ui-egui/src/property/gradient.rs new file mode 100644 index 00000000..dd61eceb --- /dev/null +++ b/crates/ui-egui/src/property/gradient.rs @@ -0,0 +1,101 @@ +use crate::{i18n::tr, theme::Tokens}; +use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; +use materialcraft_engine::core::Gradient; + +/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a key's color, right-click a key to remove it +pub fn gradient_editor(ui: &mut Ui, id: &str, gradient: &Gradient) -> Option<Gradient> { + let tokens = Tokens::get(ui.ctx()); + let width = ui.available_width().min(260.0); + let (rect, response) = ui.allocate_exact_size(vec2(width, 30.0), Sense::click_and_drag()); + crate::widgets::name(&response, egui::Role::Canvas, "Gradient editor"); + let painter = ui.painter_at(rect.expand(6.0)); + let bar = Rect::from_min_size(rect.min, vec2(width, 18.0)); + let n = 64; + for i in 0..n { + let t0 = i as f32 / n as f32; + let c = gradient.eval(t0 + 0.5 / n as f32); + let q = |v: f32| (materialcraft_engine::image::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0) as u8; + let r = Rect::from_min_max(pos2(bar.left() + bar.width() * t0, bar.top()), pos2(bar.left() + bar.width() * (t0 + 1.0 / n as f32) + 0.5, bar.bottom())); + painter.rect_filled(r, 0.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); + } + painter.rect_stroke(bar, 2.0, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let selection_id = ui.make_persistent_id(id).with("sel"); + let mut selected: usize = ui.data(|d| d.get_temp(selection_id)).unwrap_or(0); + let key_x = |pos: f32| bar.left() + pos * bar.width(); + let pointer = response.interact_pointer_pos().or(response.hover_pos()); + let nearest = pointer.and_then(|q| { + gradient + .keys + .iter() + .enumerate() + .map(|(i, k)| (i, (key_x(k.pos) - q.x).abs())) + .filter(|(_, d)| *d < 7.0) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + }); + for (i, k) in gradient.keys.iter().enumerate() { + let x = key_x(k.pos); + let triangle = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 10.0), pos2(x + 5.0, bar.bottom() + 10.0)]; + painter.add(egui::Shape::convex_polygon(triangle, if i == selected { tokens.accent } else { tokens.text }, Stroke::NONE)); + } + let mut edited_gradient: Option<Gradient> = None; + if response.drag_started() + && let Some(i) = nearest + { + selected = i; + } + if response.dragged() + && let Some(q) = pointer + && nearest.is_some() + { + let mut updated_gradient = gradient.clone(); + if let Some(k) = updated_gradient.keys.get_mut(selected) { + k.pos = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); + } + let moved = updated_gradient.keys.get(selected).copied(); + updated_gradient.sort(); + if let Some(m) = moved { + selected = updated_gradient.keys.iter().position(|k| k.pos == m.pos && k.color == m.color).unwrap_or(selected); + } + edited_gradient = Some(updated_gradient); + } + if response.clicked() + && let Some(q) = pointer + { + match nearest { + Some(i) => selected = i, + None => { + let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); + let mut updated_gradient = gradient.clone(); + updated_gradient.keys.push(materialcraft_engine::core::GradientKey::new(t, gradient.eval(t))); + updated_gradient.sort(); + selected = updated_gradient.keys.iter().position(|k| k.pos == t).unwrap_or(0); + edited_gradient = Some(updated_gradient); + } + } + } + if response.secondary_clicked() + && let Some(i) = nearest + && gradient.keys.len() > 1 + { + let mut updated_gradient = gradient.clone(); + updated_gradient.keys.remove(i); + selected = 0; + edited_gradient = Some(updated_gradient); + } + ui.data_mut(|d| d.insert_temp(selection_id, selected)); + if let Some(k) = gradient.keys.get(selected) { + ui.horizontal(|ui| { + ui.label(RichText::new(format!("{} {:.2}", tr("Key at"), k.pos)).size(11.0).color(tokens.text_dim)); + let mut rgb = [k.color[0], k.color[1], k.color[2]]; + if crate::widgets::color_swatch(ui, &format!("{id}-key"), &mut rgb, 60.0) { + let mut updated_gradient = edited_gradient.clone().unwrap_or_else(|| gradient.clone()); + if let Some(selected_key) = updated_gradient.keys.get_mut(selected) { + selected_key.color = [rgb[0], rgb[1], rgb[2], selected_key.color[3]]; + } + edited_gradient = Some(updated_gradient); + } + }); + } + edited_gradient +} diff --git a/crates/ui-egui/src/property/graph.rs b/crates/ui-egui/src/property/graph.rs new file mode 100644 index 00000000..166b627b --- /dev/null +++ b/crates/ui-egui/src/property/graph.rs @@ -0,0 +1,184 @@ +use super::{input::input_editor, section}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{Graph, OutputFormat, Resource, Value}; +use serde_json::{Value as JsonValue, json}; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let Ok(graph) = app.session.graph() else { + ui.label(tr("No graph is open")); + return; + }; + + let mut commands = Vec::new(); + let mut emit = |id: &'static str, parameters| commands.push((id, parameters)); + section(ui, "graph-base", tr("Base parameters"), |ui| { + ui.horizontal(|ui| { + ui.label(tr("Name")); + let mut name = graph.name.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, "Graph name"); + if response.lost_focus() && name != graph.name { + emit("graph.rename", json!({"name": name})); + } + }); + if graph.function.is_some() { + return; + } + + for (axis, label) in [(0usize, "Width"), (1, "Height")] { + let mut value = graph.size[axis] as f32; + if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << graph.size[axis]), &mut value, 4.0..=13.0, 0).changed() { + let mut edited = graph.size; + edited[axis] = value.round() as u32; + emit("graph.size", json!({"log2": edited})); + } + } + crate::widgets::combo(ui, tr("Output format"), tr(graph.format.label()), |ui| { + for (format, key) in [(OutputFormat::U8, "u8"), (OutputFormat::U16, "u16"), (OutputFormat::F16, "f16"), (OutputFormat::F32, "f32")] { + if ui.selectable_label(graph.format == format, tr(format.label())).clicked() { + emit("graph.format", json!({"format": key})); + } + } + }); + let mut seed = graph.seed as f32; + if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { + emit("graph.seed", json!({"seed": seed.round() as i64})); + } + }); + section(ui, "graph-attr", tr("Attributes"), |ui| { + for (key, label, current) in [ + ("category", "Category", &graph.attributes.category), + ("description", "Description", &graph.attributes.description), + ("author", "Author", &graph.attributes.author), + ("tags", "Tags", &graph.attributes.tags), + ] { + ui.horizontal(|ui| { + ui.label(tr(label)); + let mut edited = current.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut edited).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, label); + if response.lost_focus() && edited != *current { + emit("graph.attributes", json!({key: edited})); + } + }); + } + }); + section(ui, "graph-inputs", tr("Input parameters"), |ui| { + if graph.exposed.is_empty() { + ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tokens.text_dim)); + } else { + presets_bar(ui, graph, &mut emit); + } + let mut groups: Vec<&str> = Vec::new(); + for exposed in &graph.exposed { + if !groups.contains(&exposed.group.as_str()) { + groups.push(&exposed.group); + } + } + let mut last_group: Option<&str> = None; + let mut order: Vec<&materialcraft_engine::core::ExposedParameter> = Vec::new(); + for group in &groups { + order.extend(graph.exposed.iter().filter(|exposed| exposed.group == *group)); + } + for exposed in order { + if last_group != Some(exposed.group.as_str()) && !exposed.group.is_empty() { + ui.label(RichText::new(exposed.group.to_uppercase()).size(10.5).strong().color(tokens.text_dim)); + } + last_group = Some(exposed.group.as_str()); + let current = graph.input_value(&exposed.id).cloned().unwrap_or_else(|| exposed.default.clone()); + ui.horizontal(|ui| { + if crate::widgets::icon_button(ui, icon::X, tr("Delete input"), false, 18.0).clicked() { + emit("graph.exposed.delete", json!({"id": exposed.id})); + } + ui.vertical(|ui| { + if let Some(value) = input_editor(ui, exposed, ¤t) { + emit("graph.exposed.set", json!({"id": exposed.id, "value": value})); + } + }); + }); + } + }); + input_previews(ui, graph, &app.session.pkg.resources, &mut emit); + section(ui, "graph-outputs", tr("Outputs"), |ui| { + for node in graph.nodes.iter().filter(|node| node.def == "output") { + let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize; + let label = format!( + "{} {} | {}", + icon::SIGN_OUT, + materialcraft_engine::core::ComponentUsage::from_index(usage as u32).label, + materialcraft_engine::eval::identifier(node) + ); + if ui.add(egui::Button::selectable(app.session.view2d.node == Some(node.id), label)).clicked() { + emit("view.2d", json!({"node": node.id.0})); + } + } + }); + + for (id, parameters) in commands { + app.run(id, parameters); + } +} + +/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such as a mesh map baked in TextureCraft +fn input_previews(ui: &mut Ui, graph: &Graph, resources: &[Resource], emit: &mut impl FnMut(&'static str, JsonValue)) { + let inputs = materialcraft_engine::material_cmds::image_inputs(graph); + if inputs.is_empty() { + return; + } + section(ui, "graph-input-images", tr("Input previews"), |ui| { + for input in &inputs { + let id = &input.identifier; + let bound = graph.input_images.get(id); + ui.horizontal(|ui| { + ui.label(id); + egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| { + if ui.selectable_label(bound.is_none(), tr("None")).clicked() { + emit("graph.input.unbind", json!({"identifier": id})); + } + for resource in resources { + if ui.selectable_label(bound == Some(&resource.name), &resource.name).clicked() { + emit("graph.input.bind", json!({"identifier": id, "resource": resource.name})); + } + } + }); + #[cfg(not(target_arch = "wasm32"))] + if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() + && let Some(path) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() + { + emit("graph.input.bind", json!({"identifier": id, "path": path.display().to_string()})); + } + }); + } + }); +} + +/// Presets: apply one, save the current inputs under a name, delete one +fn presets_bar(ui: &mut Ui, graph: &Graph, emit: &mut impl FnMut(&'static str, JsonValue)) { + let name_id = ui.make_persistent_id("preset-name"); + let mut name: String = ui.data(|data| data.get_temp(name_id)).unwrap_or_default(); + ui.horizontal(|ui| { + let response = egui::ComboBox::from_id_salt("presets").width(110.0).selected_text(tr("Presets")).show_ui(ui, |ui| { + for preset in &graph.presets { + if ui.button(&preset.name).clicked() { + emit("graph.preset.apply", json!({"name": preset.name})); + } + } + if graph.presets.is_empty() { + ui.label(tr("No presets yet")); + } + }); + crate::widgets::name(&response.response, egui::Role::ComboBox, "Presets"); + let text_response = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tr("Preset name")).desired_width(90.0)); + crate::widgets::name(&text_response, egui::Role::TextInput, "Preset name"); + if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save preset"), false, 20.0).clicked() && !name.trim().is_empty() { + emit("graph.preset.save", json!({"name": name})); + } + if crate::widgets::icon_button(ui, icon::X, tr("Delete preset"), false, 20.0).clicked() && !name.trim().is_empty() { + emit("graph.preset.delete", json!({"name": name})); + } + }); + ui.data_mut(|data| data.insert_temp(name_id, name)); +} diff --git a/crates/ui-egui/src/property/input.rs b/crates/ui-egui/src/property/input.rs new file mode 100644 index 00000000..e6d49f4f --- /dev/null +++ b/crates/ui-egui/src/property/input.rs @@ -0,0 +1,45 @@ +use egui::Ui; +use materialcraft_engine::core::Value; +use serde_json::{Value as JsonValue, json}; + +/// The editor for one exposed input's value; returns the new value as JSON when it changed +pub(super) fn input_editor(ui: &mut Ui, exposed: &materialcraft_engine::core::ExposedParameter, current: &Value) -> Option<JsonValue> { + match *current { + Value::Float(mut f) => { + let initial = f; + crate::widgets::slider(ui, &exposed.label, &mut f, exposed.min.min(initial)..=exposed.max.max(initial), 3).changed().then(|| json!(f)) + } + Value::Int(i) => { + let mut f = i as f32; + let initial = f; + crate::widgets::slider(ui, &exposed.label, &mut f, exposed.min.min(initial)..=exposed.max.max(initial), 0).changed().then(|| json!(f.round())) + } + Value::Bool(mut b) => ui.checkbox(&mut b, &exposed.label).changed().then(|| json!(b)), + Value::Enum(i) => { + let mut out = None; + crate::widgets::combo(ui, &exposed.label, exposed.options.get(i as usize).cloned().unwrap_or_default(), |ui| { + for (k, o) in exposed.options.iter().enumerate() { + if ui.selectable_label(k as u32 == i, o).clicked() { + out = Some(json!(k)); + } + } + }); + out + } + Value::Color(c) => { + let mut rgb = [c[0], c[1], c[2]]; + let mut out = None; + ui.horizontal(|ui| { + ui.label(&exposed.label); + if crate::widgets::color_swatch(ui, &format!("exp-{}", exposed.id), &mut rgb, 80.0) { + out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]])); + } + }); + out + } + ref other => { + ui.label(format!("{}: {}", exposed.label, other.type_name())); + None + } + } +} diff --git a/crates/ui-egui/src/property/mod.rs b/crates/ui-egui/src/property/mod.rs new file mode 100644 index 00000000..89e6720f --- /dev/null +++ b/crates/ui-egui/src/property/mod.rs @@ -0,0 +1,69 @@ +mod curve; +mod gradient; +mod graph; +mod input; +mod node; +mod parameter; +mod section; + +pub use curve::curve_editor; +pub use gradient::gradient_editor; +pub(crate) use section::section; + +use crate::{MaterialCraftApp, graph::editor_target::EditorTarget, i18n::tr}; +use egui::Ui; + +/// The panel title: "<node> - Properties" or "<graph> - Properties" +pub fn title(app: &MaterialCraftApp) -> String { + match EditorTarget::resolve(app) { + EditorTarget::Pattern => return crate::pattern::properties::title(app), + EditorTarget::Function if !EditorTarget::annotation_active(app) => { + return crate::function::properties::title(app).unwrap_or_else(|| format!("{} - {}", tr("Function Graph"), tr("Properties"))); + } + _ => {} + } + + if let Some(selection) = app.session.annotation_selection { + let name = match selection { + materialcraft_engine::AnnotationSelection::Frame(_) => tr("Frame"), + materialcraft_engine::AnnotationSelection::Comment(_) => tr("Comment"), + }; + return format!("{name} - {}", tr("Properties")); + } + + let sel = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) + .and_then(|id| app.session.graph().ok()?.node(id).ok().map(crate::graph::node_label)); + let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default(); + format!("{name} - {}", tr("Properties")) +} + +pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.set_width(ui.available_width()); + match EditorTarget::resolve(app) { + EditorTarget::Pattern => { + crate::pattern::properties::show(app, ui); + return; + } + EditorTarget::Function if !EditorTarget::annotation_active(app) => { + if !crate::function::properties::show(app, ui) { + ui.label(tr("Select a node")); + } + return; + } + _ => {} + } + + if let Some(selection) = app.session.annotation_selection { + ui.push_id((app.session.graph, format!("{selection:?}")), |ui| crate::annotation::show(app, ui, selection)); + return; + } + + let node = crate::graph::node_selection::inspected(&app.session.selection, app.graph.inspected_node) + .and_then(|id| app.session.graph().ok()?.node(id).ok().cloned()); + ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { + Some(n) => node::show(app, ui, &n), + None => graph::show(app, ui), + }); + }); +} diff --git a/crates/ui-egui/src/property/node.rs b/crates/ui-egui/src/property/node.rs new file mode 100644 index 00000000..d66ab949 --- /dev/null +++ b/crates/ui-egui/src/property/node.rs @@ -0,0 +1,157 @@ +use super::{ + input::input_editor, + parameter::{function_row, param_row}, + section, +}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{Rect, RichText, Ui, vec2}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{OutputFormat, SizeMode}; +use serde_json::json; + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let tokens = Tokens::get(ui.ctx()); + let definition = materialcraft_engine::nodes::find(&node.def); + // Header: label (renamable) and description + ui.horizontal(|ui| { + ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph::header_color(&node.def)); + ui.add_space(8.0); + let mut label = if node.label.is_empty() { crate::graph::node_label(node) } else { node.label.clone() }; + let response = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)); + crate::widgets::name(&response, egui::Role::TextInput, "Node label"); + if response.changed() { + app.run("graph.node.rename", json!({"id": node.id.0, "label": label})); + } + }); + if let Some(definition) = definition + && !definition.description.is_empty() + { + ui.label(RichText::new(definition.description).size(11.0).color(tokens.text_dim)); + } + if let Some(response) = app.session.cooked.nodes.get(&node.id) + && let Some(entry) = &response.error + { + ui.label(RichText::new(format!("{} {entry}", icon::WARNING)).color(tokens.danger)); + } + ui.add_space(4.0); + section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, node)); + crate::value_input_editor::show(app, ui, node); + if node.def == "input_value" { + crate::value_input_editor::default_value(app, ui, node); + } + if node.def == "graph_instance" { + section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, node)); + return; + } + let Some(definition) = definition else { return }; + + if definition.params.is_empty() { + return; + } + section(ui, "specific", tr("Specific parameters"), |ui| { + if node.def == "levels" { + crate::levels_editor::show(app, ui, node); + ui.add_space(6.0); + } + let exposed: Vec<(String, String)> = + app.session.graph().map(|g| g.exposed.iter().map(|entry| (entry.id.clone(), entry.label.clone())).collect()).unwrap_or_default(); + for parameter in &definition.params { + if node.def == "input_value" && parameter.id == "default" { + continue; + } + let current = node.params.get(parameter.id).cloned().unwrap_or_else(|| parameter.default.clone()); + if node.functions.contains_key(parameter.id) { + function_row(app, ui, node.id, parameter.id, parameter.label); + continue; + } + let bound = node.bindings.get(parameter.id).cloned(); + param_row(app, ui, node.id, parameter, current, bound, &exposed); + } + }); +} + +fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let base = &node.base; + let id = node.id.0; + let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")]; + let current = modes.iter().find(|mode| mode.0 == base.size_mode).map_or("", |mode| mode.1); + crate::widgets::combo(ui, tr("Output size"), tr(current), |ui| { + for (mode, label) in modes { + if ui.selectable_label(base.size_mode == mode, tr(label)).clicked() { + let key = match mode { + SizeMode::RelativeToInput => "relativeToInput", + SizeMode::RelativeToParent => "relativeToParent", + SizeMode::Absolute => "absolute", + }; + + let size = if mode == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; + app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); + } + } + }); + let (minimum, maximum) = if base.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) }; + for (axis, label) in [(0usize, "Width"), (1, "Height")] { + let mut value = base.size[axis] as f32; + let caption = if base.size_mode == SizeMode::Absolute { + format!("{label} {} px", 1u32 << base.size[axis].clamp(4, 13)) + } else { + format!("{label} x {}", 2f32.powi(base.size[axis])) + }; + + if crate::widgets::slider(ui, &caption, &mut value, minimum..=maximum, 0).changed() { + let mut size = base.size; + size[axis] = value.round() as i32; + app.run("graph.node.base", json!({"id": id, "size": size})); + } + } + crate::widgets::combo(ui, tr("Output format"), tr(base.format.label()), |ui| { + for format in OutputFormat::ALL { + if ui.selectable_label(base.format == format, tr(format.label())).clicked() { + let key = match format { + OutputFormat::Inherit => "inherit", + OutputFormat::U8 => "u8", + OutputFormat::U16 => "u16", + OutputFormat::F16 => "f16", + OutputFormat::F32 => "f32", + }; + + app.run("graph.node.base", json!({"id": id, "format": key})); + } + } + }); + let mut seed = base.seed as f32; + if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { + app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64})); + } + if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { + let seed = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000; + app.run("graph.node.base", json!({"id": id, "seed": seed})); + } + let mut tiling = base.tiling[0] && base.tiling[1]; + if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() { + app.run("graph.node.base", json!({"id": id, "tiling": tiling})); + } +} + +fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let tokens = Tokens::get(ui.ctx()); + let Some((graph_index, subgraph)) = materialcraft_engine::eval::instance_graph(&app.session.pkg, node) else { + ui.label(RichText::new(tr("The instanced graph is missing")).color(tokens.danger)); + return; + }; + + let exposed = subgraph.exposed.clone(); + if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() { + crate::graph::subgraph_navigation::open_instance(app, graph_index); + return; + } + if exposed.is_empty() { + ui.label(RichText::new(tr("This graph exposes no inputs")).color(tokens.text_dim)); + } + for entry in exposed { + let current = node.params.get(&entry.id).cloned().unwrap_or_else(|| entry.default.clone()); + if let Some(value) = input_editor(ui, &entry, ¤t) { + app.run("graph.node.param", json!({"id": node.id.0, "param": entry.id, "value": value})); + } + } +} diff --git a/crates/ui-egui/src/property/parameter.rs b/crates/ui-egui/src/property/parameter.rs new file mode 100644 index 00000000..f0ce6089 --- /dev/null +++ b/crates/ui-egui/src/property/parameter.rs @@ -0,0 +1,214 @@ +use super::{curve_editor, gradient_editor}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::core::{NodeId, Value}; +use materialcraft_engine::nodes::ParameterDefinition; +use serde_json::{Value as JsonValue, json}; + +fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: JsonValue) { + app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value})); +} + +fn typed(v: &Value) -> JsonValue { + serde_json::to_value(v).unwrap_or(JsonValue::Null) +} + +/// One parameter: its editor, plus the expose/bind menu +pub(super) fn param_row( + app: &mut MaterialCraftApp, + ui: &mut Ui, + node: NodeId, + parameter: &ParameterDefinition, + current: Value, + bound: Option<String>, + exposed: &[(String, String)], +) { + let tokens = Tokens::get(ui.ctx()); + if let Some(input) = &bound { + ui.horizontal(|ui| { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tokens.accent)); + if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() { + app.run("graph.node.bind", json!({"id": node.0, "param": parameter.id, "input": JsonValue::Null})); + } + }); + return; + } + let show_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| { + resp.context_menu(|ui| { + if ui.button(tr("Reset to default")).clicked() { + app.run("graph.node.reset", json!({"id": node.0, "param": parameter.id})); + ui.close(); + } + let dynamic = !matches!(parameter.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_)); + if dynamic && ui.button(tr("Set function...")).clicked() { + if app.run("graph.node.function", json!({"id": node.0, "param": parameter.id})).is_some() { + crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Dynamic(parameter.id.to_string())); + } + ui.close(); + } + if ui.button(tr("Expose as graph input")).clicked() { + app.run("graph.exposed.add", json!({"id": parameter.id, "label": parameter.label, "bind": {"node": node.0, "param": parameter.id}})); + ui.close(); + } + if !exposed.is_empty() { + ui.menu_button(tr("Bind to input"), |ui| { + for (id, label) in exposed { + if ui.button(label).clicked() { + app.run("graph.node.bind", json!({"id": node.0, "param": parameter.id, "input": id})); + ui.close(); + } + } + }); + } + }); + }; + + match current { + Value::Float(mut v) => { + if parameter.angle { + let mut degrees = v * 360.0; + let response = crate::widgets::slider(ui, tr(parameter.label), &mut degrees, -360.0..=360.0, 1); + if response.changed() { + v = degrees / 360.0; + set(app, node, parameter.id, json!(v)); + } + show_menu(app, &response); + } else { + let (minimum, maximum) = (parameter.min.min(v), parameter.max.max(v)); + let response = crate::widgets::slider(ui, tr(parameter.label), &mut v, minimum..=maximum, if maximum - minimum > 20.0 { 1 } else { 3 }); + if response.changed() { + set(app, node, parameter.id, json!(v)); + } + show_menu(app, &response); + } + } + Value::Int(i) => { + let mut v = i as f32; + let range = parameter.min.min(v)..=parameter.max.max(v); + let response = crate::widgets::slider(ui, tr(parameter.label), &mut v, range, 0); + if response.changed() && v.round() as i32 != i { + set(app, node, parameter.id, json!(v.round() as i32)); + } + show_menu(app, &response); + } + Value::Float2(v) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + let mut nv = v; + for (k, axis) in ["X", "Y"].iter().enumerate() { + let range = parameter.min.min(nv[k])..=parameter.max.max(nv[k]); + let response = crate::widgets::slider(ui, axis, &mut nv[k], range, 3); + if response.changed() { + set(app, node, parameter.id, json!(nv)); + } + show_menu(app, &response); + } + } + Value::Int2(v) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + for k in 0..2 { + let mut f = v[k] as f32; + if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, parameter.min..=parameter.max, 0).changed() { + let mut nv = v; + nv[k] = f.round() as i32; + set(app, node, parameter.id, json!(nv)); + } + } + } + Value::Bool(b) => { + let mut v = b; + let response = ui.checkbox(&mut v, tr(parameter.label)); + if response.changed() { + set(app, node, parameter.id, json!(v)); + } + show_menu(app, &response); + } + Value::Float3(_) | Value::Float4(_) | Value::Int3(_) | Value::Int4(_) => { + ui.label(tr(parameter.label)); + let mut value = current.clone(); + if crate::value_editor::show(ui, &mut value) { + set(app, node, parameter.id, serde_json::to_value(value).unwrap_or_default()); + } + } + Value::Color(c) => { + ui.horizontal(|ui| { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut rgb = [c[0], c[1], c[2]]; + if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, parameter.id), &mut rgb, 90.0) { + set(app, node, parameter.id, json!([rgb[0], rgb[1], rgb[2], c[3]])); + } + }); + }); + } + Value::Enum(i) => { + let current = parameter.options.get(i as usize).copied().unwrap_or("?"); + crate::widgets::combo(ui, tr(parameter.label), tr(current), |ui| { + for (k, o) in parameter.options.iter().enumerate() { + if ui.selectable_label(k as u32 == i, tr(o)).clicked() { + set(app, node, parameter.id, json!(k)); + } + } + }); + } + Value::Text(t) if parameter.resource => { + let names: Vec<String> = app.session.pkg.resources.iter().map(|response| response.name.clone()).collect(); + crate::widgets::combo(ui, tr(parameter.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| { + for n in &names { + if ui.selectable_label(*n == t, n).clicked() { + set(app, node, parameter.id, json!(n)); + } + } + }); + if ui.button(format!("{} {}", icon::IMAGE, tr("Import bitmap..."))).clicked() { + crate::menus::invoke(app, ui.ctx(), "file.importBitmap"); + } + } + Value::Text(t) => { + ui.horizontal(|ui| { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + let mut s = t.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, parameter.label); + if response.changed() { + set(app, node, parameter.id, json!(s)); + } + }); + } + Value::Curve(c) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, parameter.id), &c) { + set(app, node, parameter.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>())); + } + } + Value::Gradient(g) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, parameter.id), &g) { + set(app, node, parameter.id, typed(&Value::Gradient(ng))); + } + } + Value::PatternGraph(graph) => { + ui.label(format!("{}: {} nodes", parameter.label, graph.nodes.len())); + } + Value::Function(f) => { + ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); + crate::windows::function_summary(app, ui, node, parameter.id, &f); + } + } +} + +/// A parameter driven by a function: its label, Edit and Remove +pub(super) fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(tr(label)).color(tokens.text)); + ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tokens.accent)); + if ui.small_button(tr("Edit")).clicked() { + crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Dynamic(param.to_string())); + } + if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { + app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); + } + }); +} diff --git a/crates/ui-egui/src/property/section.rs b/crates/ui-egui/src/property/section.rs new file mode 100644 index 00000000..c6bc3ba9 --- /dev/null +++ b/crates/ui-egui/src/property/section.rs @@ -0,0 +1,29 @@ +use crate::theme::Tokens; +use egui::{Sense, Ui, vec2}; +use egui_phosphor::regular as icon; + +pub(crate) fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { + let tokens = Tokens::get(ui.ctx()); + let id = ui.make_persistent_id(id); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + crate::widgets::name(&response, egui::Role::Button, title); + ui.painter().rect_filled(rect, 3.0, tokens.row); + let chevron = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT }; + ui.painter().text(rect.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chevron, egui::FontId::proportional(10.0), tokens.text_dim); + ui.painter().text( + rect.left_center() + vec2(20.0, 0.0), + egui::Align2::LEFT_CENTER, + title.to_uppercase(), + egui::FontId::proportional(10.5), + tokens.text_strong, + ); + if response.clicked() { + state.toggle(ui); + } + state.show_body_unindented(ui, |ui| { + ui.add_space(3.0); + body(ui); + ui.add_space(6.0); + }); +} diff --git a/crates/ui-egui/src/view3d.rs b/crates/ui-egui/src/view3d.rs index 3b517248..adce9d1f 100644 --- a/crates/ui-egui/src/view3d.rs +++ b/crates/ui-egui/src/view3d.rs @@ -1,4 +1,4 @@ -//! The 3D view: the open graph's material on a built-in scene, rendered by +//! The 3D view: assigned material channels on a built-in scene, rendered by //! `materialcraft-render` (one ray per pixel at half resolution while the camera moves, 2×2 //! supersampled when it rests). Left-drag orbits, Alt+drag or middle-drag pans, the wheel zooms, //! Shift+drag turns the light and a double-click resets the camera. @@ -93,6 +93,25 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(4, 1)).show(ui, |ui| { egui::MenuBar::new().ui(ui, |ui| { + ui.menu_button(tr("Material"), |ui| { + let sources = app.session.material_preview.sources(&app.session.pkg); + for channel in materialcraft_engine::core::MaterialChannel::ALL { + let source = sources.get(&channel); + let label = source + .and_then(|source| { + let graph = app.session.pkg.graphs.get(source.graph)?; + let node = graph.node(source.node).ok()?; + Some(format!("{} / {}", graph.name, crate::graph::node_label(node))) + }) + .unwrap_or_else(|| tr("Unassigned").to_string()); + ui.label(format!("{}: {label}", tr(channel.label()))); + } + ui.separator(); + if ui.button(tr("Clear material assignments")).clicked() { + app.run("view.3d.clear", json!({})); + ui.close(); + } + }); ui.menu_button(tr("Scene"), |ui| { for (id, label) in SCENES { if ui.selectable_label(app.session.view3d.scene == *id, tr(label)).clicked() { @@ -172,7 +191,12 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let avail = ui.available_size(); let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::click_and_drag()); crate::widgets::name(&resp, egui::Role::Image, "3D view"); - // Camera gestures. + let graph_hover = resp.dnd_hover_payload::<crate::graph_drag_payload::GraphDragPayload>().is_some(); + if let Some(graph) = crate::widgets::dnd_release::<crate::graph_drag_payload::GraphDragPayload>(&resp) { + app.run("view.3d.outputs", json!({"graph": graph.name})); + } + + // Camera gestures let mut moving = false; if resp.dragged() { let d = resp.drag_delta(); @@ -217,7 +241,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { p.text( rect.center_top() + vec2(0.0, 18.0), egui::Align2::CENTER_TOP, - tr("Add Output nodes with usages (base color, normal, ...) to see the material"), + tr("Assign an image with View in 3D view, or connect Output nodes with material usages"), egui::FontId::proportional(11.0), tk.viewport_text, ); @@ -229,7 +253,18 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { egui::FontId::proportional(10.5), tk.viewport_text, ); - // Bottom bar. + if graph_hover { + p.rect_stroke(rect.shrink(2.0), 4.0, egui::Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + p.text( + rect.center_top() + vec2(0.0, 38.0), + egui::Align2::CENTER_TOP, + tr("Drop to apply graph outputs"), + egui::FontId::proportional(13.0), + tk.viewport_text, + ); + } + + // Bottom bar let bar = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 22.0)); ui.scope_builder(egui::UiBuilder::new().max_rect(bar), |ui| { ui.painter().rect_filled(bar, 0.0, tk.panel); @@ -281,11 +316,7 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 { for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale] { f.to_bits().hash(&mut hs); } - if let Ok(g) = app.session.graph() { - for (id, usage, _, _) in materialcraft_engine::eval::outputs(g, &app.session.cooked) { - (usage, app.session.cooked.nodes.get(&id).map(|r| r.key)).hash(&mut hs); - } - } + app.session.material_key().hash(&mut hs); hs.finish() } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index b5c356f9..8e2c489e 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -484,7 +484,7 @@ pub fn history(app: &mut MaterialCraftApp, ui: &mut Ui) { pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, f: &FunctionGraph) { let tk = Tokens::get(ui.ctx()); if ui.add(crate::widgets::primary_button(ui, &format!("{} {}", icon::FLOW_ARROW, tr("Edit function graph...")))).clicked() { - app.function_editor = Some(crate::function::FunctionEditor::new(node, crate::function::FunctionTarget::Parameter(param.to_string()))); + crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Parameter(param.to_string())); } ui.label(RichText::new(format!("{} {}", f.nodes.len(), tr("function nodes"))).size(10.5).color(tk.text_dim)); let id = egui::Id::unique(("fn-edit", node.0, param)); diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index e9108890..b1327e9f 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -58,26 +58,28 @@ fn explorer_export_opens_the_clicked_graph() { #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn empty_startup_can_create_a_template() { let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); - let mut h = harness(app, 1600.0, 960.0); - settle(&mut h, 40); - assert_eq!(h.state().session.pkg.graphs.len(), 1); - assert!(h.state().session.graph().unwrap().nodes.is_empty()); - assert!(h.state().graph.rects.is_empty()); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 40); + assert_eq!(harness.state().session.pkg.graphs.len(), 1); + assert!(harness.state().session.graph().unwrap().nodes.is_empty()); + assert!(harness.state().graph.rects.is_empty()); if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) { std::fs::create_dir_all(&dir).unwrap(); - save(&mut h, &dir, "empty-startup"); + save(&mut harness, &dir, "empty-startup"); } - h.get_by_label("New graph...").click(); - settle(&mut h, 4); - h.get_by_label("Atomic sample").click(); - settle(&mut h, 4); - h.get_by_label("Create").click(); - settle(&mut h, 40); - assert_eq!(h.state().session.pkg.graphs.len(), 2); - assert!(!h.state().session.graph().unwrap().nodes.is_empty()); - assert!(!h.state().graph.rects.is_empty()); + harness.get_by_label("New graph...").click(); + settle(&mut harness, 4); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Template")).click(); + settle(&mut harness, 2); + harness.get_by_label("Atomic sample").click(); + settle(&mut harness, 4); + harness.get_by_label("Create").click(); + settle(&mut harness, 40); + assert_eq!(harness.state().session.pkg.graphs.len(), 2); + assert!(!harness.state().session.graph().unwrap().nodes.is_empty()); + assert!(!harness.state().graph.rects.is_empty()); if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) { - save(&mut h, &dir, "chosen-template"); + save(&mut harness, &dir, "chosen-template"); } } @@ -144,6 +146,7 @@ fn snapshots() { h.state_mut().run("graph.select", json!({"ids": [id]})); h.state_mut().run("view.2d", json!({"node": id})); h.state_mut().function_editor = Some(materialcraft_ui_egui::function::FunctionEditor::new( + h.state().session.graph, materialcraft_engine::core::NodeId(id), materialcraft_ui_egui::function::FunctionTarget::Parameter("function".into()), )); @@ -205,7 +208,7 @@ fn graph_context_menu_has_flat_node_list() { let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); let mut harness = harness(app, 1600.0, 960.0); settle(&mut harness, 8); - harness.get(By::new().role(egui::accesskit::Role::Button).label("Input Value")).click_secondary(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Brightness")).click_secondary(); settle(&mut harness, 3); let directory = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from); if let Some(directory) = &directory { @@ -218,8 +221,8 @@ fn graph_context_menu_has_flat_node_list() { "Add Frame", "Add Navigation pin", "Add Dot node", - "View outputs in 3D view", - "Reset and view outputs in 3D view", + "View in 3D view", + "Reset and view in 3D view", "View output in 2D view", "Compute nodes thumbnails", "Clear nodes thumbnails", @@ -312,8 +315,7 @@ fn graph_context_menu_has_flat_node_list() { if let Some(directory) = &directory { save(&mut harness, directory, "pattern-graph-editor"); } - let parent = harness.state().session.graph().unwrap().name.clone(); - harness.get(By::new().role(egui::accesskit::Role::Button).label(&parent)).click(); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Return to parent graph")).click(); settle(&mut harness, 3); assert!(harness.state().pattern_editor.is_none()); @@ -553,7 +555,7 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { 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 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(output)]); @@ -577,3 +579,317 @@ fn named_outputs_open_properties_and_preview_only_on_double_click() { assert_eq!(current, material); save(&mut harness, &directory, "named-output-preview"); } + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn shared_toolbar_targets_each_graph_and_preserves_undo() { + use materialcraft_engine::core::{FunctionGraph, NodeId, PatternGraph, PatternNodeKind, Value}; + + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let mut common_controls = None; + for kind in ["material", "function", "pattern"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let mut owner = 0; + match kind { + "function" => { + app.run("file.new", json!({"kind": "function"})).unwrap(); + let mut graph = FunctionGraph::default(); + for position in [[0.0, 0.0], [256.0, 160.0]] { + graph.add_constant(Value::Float(1.0)); + graph.nodes.last_mut().unwrap().pos = position; + } + graph.output = Some(2); + app.run("graph.function.set", json!({"function": graph})).unwrap(); + } + "pattern" => { + owner = app.run("graph.node.add", json!({"def": "fx_map", "at": [700, 800]})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::default(); + for position in [[0.0, 0.0], [256.0, 160.0]] { + graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes.last_mut().unwrap().position = position; + } + app.run("graph.pattern.set", json!({"id": owner, "pattern": graph})).unwrap(); + app.pattern_editor = Some(materialcraft_ui_egui::pattern::PatternEditor::new(app.session.graph, NodeId(owner))); + } + _ => { + for position in [[0, 0], [256, 160]] { + app.run("graph.node.add", json!({"def": "uniform", "at": position})).unwrap(); + } + } + } + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let query = |label| By::new().role(egui::accesskit::Role::Button).label(label); + let controls = ["Frame all (F)", "Align left", "Distribute horizontally", "Snap to grid"].map(|label| harness.get(query(label)).rect()); + if let Some(expected) = common_controls { + assert_eq!(controls, expected, "{kind} toolbar drift"); + } + common_controls = Some(controls); + let context = harness.ctx.clone(); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.selectAll"); + settle(&mut harness, 2); + let original = harness.state().session.pkg.clone(); + harness.get(query("Align left")).click(); + settle(&mut harness, 3); + let graph = harness.state().session.graph().unwrap(); + let positions: Vec<_> = match kind { + "function" => graph.function.as_ref().unwrap().nodes.iter().map(|node| node.pos).collect(), + "pattern" => { + let Value::PatternGraph(pattern) = &graph.node(NodeId(owner)).unwrap().params["pattern"] else { panic!("missing pattern") }; + assert_eq!(graph.node(NodeId(owner)).unwrap().pos, [704.0, 800.0]); + pattern.nodes.iter().map(|node| node.position).collect() + } + _ => graph.nodes.iter().map(|node| node.pos).collect(), + }; + assert_eq!(positions, vec![[0.0, 0.0], [0.0, 160.0]], "{kind} alignment"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(harness.state().session.pkg, original); + let snap = harness.state().ui.prefs.snap_to_grid; + harness.get(query("Snap to grid")).click(); + settle(&mut harness, 2); + assert_eq!(harness.state().ui.prefs.snap_to_grid, !snap); + assert_eq!(harness.state().session.pkg, original); + harness.get(query("Frame all (F)")).click(); + settle(&mut harness, 2); + save(&mut harness, &directory, &format!("shared-toolbar-{kind}")); + if kind == "pattern" { + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.delete"); + settle(&mut harness, 2); + assert!(harness.query_all(By::new().label("Set a node as the root")).next().is_some()); + harness.state_mut().session.undo().unwrap(); + harness.get(query("Return to parent graph")).click(); + settle(&mut harness, 2); + assert!(harness.state().pattern_editor.is_none()); + assert_eq!(harness.state().session.pkg, original); + } else if kind == "function" { + harness.get(query("Add frame around the selection")).click(); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().frames.len(), 1); + assert_eq!(harness.state().session.graph().unwrap().function, original.graphs[harness.state().session.graph].function); + save(&mut harness, &directory, "shared-toolbar-function-frame"); + } + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn embedded_function_toolbar_and_panels_share_the_active_target() { + use materialcraft_engine::{ + FunctionGraphTarget, + core::{FunctionGraph, NodeId, Value}, + }; + for definition in ["pixel_processor", "value_processor"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let owner = NodeId(app.run("graph.node.add", json!({"def": definition, "at": [700, 800]})).unwrap()["id"].as_u64().unwrap()); + let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() }; + let mut graph = FunctionGraph::default(); + for position in [[0.0, 0.0], [256.0, 160.0]] { + graph.add_constant(Value::Float(0.5)); + graph.nodes.last_mut().unwrap().pos = position; + } + app.run("graph.function.set", json!({"target": target, "function": graph})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let context = harness.ctx.clone(); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "graph.node.edit"); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.selectAll"); + settle(&mut harness, 2); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Window)).next().is_none()); + assert_eq!(harness.query_all(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).count(), 1); + let query = |label| By::new().role(egui::accesskit::Role::Button).label(label); + for label in ["Frame all (F)", "Align left", "Distribute horizontally", "Snap to grid", "Show node thumbnails"] { + assert_eq!(harness.query_all(query(label)).count(), 1, "shared control {label}"); + } + let original = harness.state().session.pkg.clone(); + harness.get(query("Align left")).click(); + settle(&mut harness, 2); + let function = target.current(&harness.state().session).unwrap(); + assert_eq!(function.nodes.iter().map(|node| node.pos).collect::<Vec<_>>(), vec![[0.0, 0.0], [0.0, 160.0]]); + assert_eq!(harness.state().session.graph().unwrap().node(owner).unwrap().pos, [704.0, 800.0]); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "edit.undo"); + settle(&mut harness, 2); + assert_eq!(harness.state().session.pkg, original); + let snap = harness.state().ui.prefs.snap_to_grid; + harness.get(query("Snap to grid")).click(); + settle(&mut harness, 2); + assert_eq!(harness.state().ui.prefs.snap_to_grid, !snap); + assert!(harness.query_all(By::new().label("Get Float")).next().is_some()); + assert!(materialcraft_ui_egui::properties::title(harness.state()).starts_with("Float")); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, &format!("{definition}-inline-function")); + harness.state_mut().ui.library_search = "Sample".into(); + settle(&mut harness, 2); + for label in ["Sample grayscale", "Sample color"] { + assert_eq!(harness.query_all(By::new().label(label)).next().is_some(), definition == "pixel_processor"); + } + harness.get(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).click_secondary(); + settle(&mut harness, 2); + harness.get_by_label("Add node").click(); + settle(&mut harness, 2); + for label in ["Sample grayscale", "Sample color"] { + assert_eq!(harness.query_all(query(label)).next().is_some(), definition == "pixel_processor"); + } + save(&mut harness, &directory, &format!("{definition}-node-menu")); + harness.key_press(egui::Key::Escape); + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + harness.get(query("Return to parent graph")).click(); + settle(&mut harness, 3); + assert!(harness.state().function_editor.is_none()); + assert_eq!(harness.state().session.selection, vec![owner]); + assert_eq!(harness.state().session.pkg, original); + } +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn material_assignment_previews_outputs_and_survives_function_editing() { + use materialcraft_engine::core::NodeId; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.session.preview_size = Some(64); + app.ui.prefs.preview_size = 64; + let source = + app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0], "params": {"color_mode": true, "color": [0.8, 0.04, 0.02, 1.0]}})).unwrap()["id"] + .as_u64() + .unwrap(); + let output = app + .run("graph.node.add", json!({"def": "output", "at": [224, 0], "connectFrom": {"node": source}, "params": {"identifier": "preview_image", "usage": 9}})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 45); + assert!(harness.state().session.material_maps().is_empty()); + let before = harness.state().view3d.shown.clone().unwrap(); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, "material-unassigned"); + + let selection = harness.state().session.selection.clone(); + harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Preview Image")).click_secondary(); + settle(&mut harness, 3); + harness.get_by_label("View in 3D view").click(); + settle(&mut harness, 3); + save(&mut harness, &directory, "material-channel-menu"); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Base color")).click(); + settle(&mut harness, 45); + assert_eq!(harness.state().session.selection, selection, "channel menu clicks must not reach the graph beneath them"); + assert_eq!(harness.state().session.material_maps()[0].0, "baseColor"); + let red_frame = harness.state().view3d.shown.clone().unwrap(); + assert_ne!(before.2, red_frame.2, "assignment must invalidate the rendered frame"); + let red_pixels = red_frame.2.chunks_exact(4).filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count(); + assert!(red_pixels > 100, "the rendered mesh must show the assigned red image"); + save(&mut harness, &directory, "material-assigned-red"); + + harness.state_mut().run("graph.node.param", json!({"id": source, "param": "color", "value": [0.02, 0.04, 0.8, 1.0]})).unwrap(); + settle(&mut harness, 45); + let blue_frame = harness.state().view3d.shown.clone().unwrap(); + let blue_pixels = blue_frame.2.chunks_exact(4).filter(|pixel| u16::from(pixel[2]) > u16::from(pixel[0]) + 30).count(); + assert!(blue_pixels > 100, "edits must refresh the assigned material"); + assert_ne!(red_frame.2, blue_frame.2); + save(&mut harness, &directory, "material-assigned-blue"); + + harness.state_mut().run("file.new", json!({"kind": "function", "name": "Function preview"})).unwrap(); + settle(&mut harness, 45); + let maps = harness.state().session.material_maps(); + assert_eq!(maps[0].1.get(0, 0, false), [0.02, 0.04, 0.8, 1.0]); + assert_eq!(harness.state().session.material_preview.channels[&materialcraft_engine::core::MaterialChannel::BaseColor].node, NodeId(output)); + save(&mut harness, &directory, "material-retained-in-function"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { + use materialcraft_engine::core::{ComponentUsage, MaterialChannel, NodeId}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.session.pkg.graphs[0].name = "Atomic_sample".into(); + app.ui.prefs.preview_size = 64; + let mut inputs = Vec::new(); + for (definition, identifier, label) in [ + ("input_color", "color_input", "Color Input"), + ("input_grayscale", "gray_input", "Gray Input"), + ("input_value", "brightness_value", "Brightness Value"), + ] { + let id = app.run("graph.node.add", json!({"def": definition, "at": [0, inputs.len() * 192], "params": {"identifier": identifier}})).unwrap()["id"] + .as_u64() + .unwrap(); + inputs.push((NodeId(id), label)); + } + let source = app.run("graph.node.add", json!({"def": "uniform", "at": [224, 0], "params": {"color_mode": true, "color": [0.8, 0.04, 0.02, 1.0]}})).unwrap() + ["id"] + .as_u64() + .unwrap(); + let output = app.run("graph.node.add", json!({"def": "output", "at": [448, 0], "connectFrom": {"node": source}, "params": {"identifier": "base_color", "usage": ComponentUsage::index("diffuse")}})).unwrap()["id"].as_u64().unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 8); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let graph_row = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Atomic_sample")).rect(); + for (id, label) in inputs { + let row = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label(label)); + assert!(row.rect().left() > graph_row.left()); + row.click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.selection, vec![id]); + assert_eq!(harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Node label")).value().as_deref(), Some(label)); + assert!(harness.query_all(By::new().label("Identifier")).next().is_some()); + let before = harness.state().session.graph().unwrap().node(id).unwrap().clone(); + let default = &materialcraft_engine::nodes::find(&before.def).unwrap().param("usage").unwrap().default; + assert_eq!(before.params.get("usage").unwrap_or(default), &materialcraft_engine::core::Value::Enum(ComponentUsage::ANY_INDEX)); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Component Usage")).click(); + settle(&mut harness, 2); + harness.get_by_label("Base color").scroll_to_me(); + settle(&mut harness, 2); + harness.get_by_label("Base color").click(); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().node(id).unwrap().params.get("usage"), Some(&materialcraft_engine::core::Value::Enum(0))); + save(&mut harness, &directory, &format!("component-usage-{}", before.def)); + harness.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(harness.state().session.graph().unwrap().node(id).unwrap(), &before); + } + harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Base Color")).click(); + settle(&mut harness, 3); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Component Usage")).click(); + settle(&mut harness, 3); + harness.get_by_label("Glossiness").scroll_to_me(); + settle(&mut harness, 3); + harness.get_by_label("Glossiness").click(); + settle(&mut harness, 3); + let node = harness.state().session.graph().unwrap().node(NodeId(output)).unwrap(); + assert_eq!(materialcraft_engine::eval::output_usage(node), "glossiness"); + harness.state_mut().run("graph.node.param", json!({"id": output, "param": "usage", "value": ComponentUsage::index("diffuse")})).unwrap(); + + settle(&mut harness, 3); + save(&mut harness, &directory, "explorer-inputs-and-usages"); + harness.state_mut().run("file.new", json!({"kind": "function", "name": "Function editing"})).unwrap(); + harness.state_mut().run("view.3d.clear", json!({})).unwrap(); + settle(&mut harness, 8); + let graph = harness.state().session.graph; + let camera = harness.state().session.view3d.clone(); + let package = harness.state().session.pkg.clone(); + let start = harness.get(By::new().role(egui::accesskit::Role::TreeItem).label("Atomic_sample")).rect().center(); + let end = harness.get(By::new().role(egui::accesskit::Role::Image).label("3D view")).rect().center(); + harness.event(egui::Event::PointerMoved(start)); + harness.step(); + harness.event(egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.step(); + for position in [start + vec2(12.0, 0.0), end] { + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + } + save(&mut harness, &directory, "graph-drop-target"); + harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + settle(&mut harness, 45); + assert_eq!(harness.state().session.graph, graph, "dropping a graph must not open it"); + assert_eq!(harness.state().session.view3d, camera, "dropping must not orbit the camera"); + assert_eq!(harness.state().session.pkg, package); + let binding = &harness.state().session.material_preview.channels[&MaterialChannel::BaseColor]; + assert_eq!((binding.graph, binding.node), (0, NodeId(output))); + let frame = &harness.state().view3d.shown.as_ref().unwrap().2; + assert!(frame.chunks_exact(4).filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count() > 100); + save(&mut harness, &directory, "graph-dropped-on-material"); +} diff --git a/docs/architecture.md b/docs/architecture.md index b6b05ed4..a27f13ae 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials and TextureCraft) · **Target:** the professional node-based material workflow +> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-05 · **Change:** evaluator and editor organization · **Target:** the professional node-based material workflow MaterialCraft is a Cargo workspace of small crates in strict layers (`cargo xtask layers` enforces them). Everything below the UI is plain Rust with no UI toolkit and builds for @@ -32,7 +32,7 @@ apps materialcraft (desktop), materialcraft-cli, materialcraft-web ## Cooking -A node's cook is a pure function `fn(&Ctx) -> Result<Vec<Image>, String>`: `Ctx` carries the output +A node's cook is a pure function `fn(&CookContext) -> Result<Vec<Image>, String>`: `CookContext` carries the output size, the seed, tiling, the inputs (by port order, `None` when unconnected), the resolved parameters, a resource decoder and the graph's exposed values. `eval::cook` walks the graph in dependency order. For each node it hashes the definition id, resolved parameters, size, seed, tiling, the keys of its @@ -40,6 +40,15 @@ input images, resource bytes and (for instances) the sub-graph: equal keys hit t re-cooks only the nodes downstream of it, and undo finds earlier results again. A failing node shows a magenta image and its error; nodes after it still cook. +Each cook builds a borrowed `core::GraphIndex` for node and connection lookups. `PreparedGraph` +resolves the needed nodes' ports once; `graph_execution` schedules them and `node_execution` handles +a single node. Parameter resolution, graph instances, value execution, output collection and cache +keys have separate modules. The index lives only for the cook, so it needs no invalidation protocol. + +Function execution shares one interpreter. Pixel Processor borrows the caller's variables and keeps +only assignments in its per-pixel state; ordinary function evaluation retains the full environment +for callers such as FX-Map that read the resulting variables. + Sizes: generators take the graph ("parent") size; filters take their main input's size; both can be offset by powers of two or set absolutely. While editing, outputs are capped at the preview size (512 px by default), with pixel-based parameters scaled by `w / 256` so previews and full-size @@ -66,12 +75,76 @@ against the curve, so wires can be selected, deleted, swapped or split with a re gestures into commands only when they complete. See [wires-and-alpha.md](wires-and-alpha.md). The 3D view renders with `materialcraft-render` on the CPU: half resolution while the camera moves, 2×2 supersampled when it rests. +The 3D material has its own `MaterialPreview` assignment state. Automatic graph output usages and +explicit `MaterialSource` overrides resolve to channels from `core::MaterialChannel`, shared with the +renderer and menus. A source records its graph, node and named port; selection and 2D preview do not +change it. `PreviewCook` publishes the editor cook and any other assigned graphs together through +the existing worker/cache, so opening a Function Graph preserves the material. Render invalidation +includes both source assignments and cooked content. Snapshot undo and graph deletion retain or +adjust source ownership; package replacement clears old assignments. + +`core::ComponentUsage` defines output metadata once for node properties, SBS and exports. Its +indices stay stable as choices are added; renderable channels remain a separate capability. +Explorer and canvas node labels share display formatting without rewriting identifiers. Explorer +lists every graph input/output, and graph drops dispatch the existing material assignment command. + `crates/ui-egui/tests/snapshot.rs` renders the real UI offscreen with egui_kittest + wgpu for visual checks and README screenshots. +The regular and function canvases separate drawing, geometry, navigation and input handling. +Shared modules own node cards, selection and annotation gestures. The regular canvas borrows the +document while drawing, then dispatches edits. Graph Properties follows the same pattern; its +`property/` modules separate panel routing, node and graph settings, parameter controls, curves +and gradients. Function and pattern Properties dispatch value edits without cloning graphs in the UI. + The properties panel builds every parameter editor from the node catalog; the Levels node adds a histogram editor with range handles on top of its sliders ([levels-editor.md](levels-editor.md)). +### Shared graph editing + +The graph panel renders one toolbar before dispatching to the material, Function Graph or FX-Map +canvas. Framing, alignment, distribution and snapping occupy the same positions. Image inserts, +parent texture size, annotations and parent-graph navigation appear only where the graph supports +them. Alignment uses the same engine command for all three models, with explicit embedded node IDs +and an explicit Function target or FX-Map owner ID, so overlapping IDs cannot move the parent material nodes. +Pixel Processor, Value Processor and parameter functions use that same main panel and function node +catalog, with one target-aware availability rule shared by node creation, Library and Add node. +Value Processor omits the two sampler entries; saved functions retain their existing operations. +A breadcrumb and parent action return from nested functions, FX-Maps and local graph instances +while retaining the parent view and material preview. + +`ui-egui/graph/graph_camera.rs` owns framing, pointer-centered scroll/pinch zoom and navigation +shortcuts. `node_selection.rs` owns click and box selection; `port_hit.rs` owns nearest-port picking; +`wire_geometry.rs` owns curve construction. Node movement uses the engine's `graph_grid::translate` +for both previews and commits. + +`engine/graph_edit/` owns Function/FX-Map selection commands, clipboard remapping, deletion and +connected-node traversal. Its small model adapters supply node fields, link direction, ID allocation +and result/root handling. Material clipboard commands retain their named-port connections and +cross-graph clipboard rules. Rendering and connection validation remain specific to each model; +all document changes still pass through engine commands and snapshot undo. `selection_commands.rs` +routes the existing selection and clipboard command IDs to these adapters, including headless calls. +Read-only selection actions borrow the graph. Document, selection and clipboard updates are published +only after validation succeeds; clipboard provenance prevents external links crossing graph targets. +`graph_validation.rs` supplies the same checks to creation, legacy setters and targeted edits. + +`graph/editor_target.rs` resolves command ownership for the material canvas, standalone Function +Graphs, FX-Map canvases and embedded Function Graphs. Menus, keyboard shortcuts and +`ui.menu.invoke`, Library and Properties use that resolver; `ui.inspect` reports the same editor and +its canvas coordinates. Embedded editors record their owning graph and close when undo or another +command makes that owner unavailable. +Common context-menu entries live in `graph/edit_menu.rs`. Pointer gestures finish only when their +initiating button is released; Escape or focus loss cancels pending canvas movement. + +Function and FX-Map rendering borrow the document, prepare screen geometry, and dispatch edits +after painting. Function wires reuse one node-layout index instead of scanning the graph for each +endpoint. The engine's `graph.function.edit` and `graph.pattern.edit` commands own creation, +movement, connections, values and result/root changes. Function targets identify standalone, +parameter, dynamic-parameter or nested FX-Map functions explicitly. Value updates may request +`merge: true`; `edit.finish` closes that undo group. The UI closes groups at gesture boundaries, +while discrete edits always receive their own undo entry. + + ## Files SBS is the project format. The codec writes native filters, ports, parameters, function graphs, @@ -79,6 +152,10 @@ pattern graphs and resources directly, without a private payload. Unsupported im warnings; unknown nodes remain placeholders. Library reference loading is not part of the current primitive workflow. `.mcraft` is no longer supported. +The SBS `read` and `write` modules expose codec entry points. `SbsReader` and `SbsWriter` own +serialization state; focused helpers handle values, functions, patterns and canvas annotations. +Native value type codes come from `core::ValueType` rather than a second scalar type table. + See [atomic-workflow.md](atomic-workflow.md) for the tested scope and remaining limitations. ## Other apps diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1c09d6c3..10d12ae0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -68,7 +68,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | Command | Params | |---|---| | `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) | -| `graph.node.edit` | `{}` resolves the selected FX-Map to `{node, parameter}`; use `ui.menu.invoke` to enter its subgraph in the graph panel | +| `graph.node.edit` | `{}` resolves the selected FX-Map, processor or local graph instance to `{kind, node, parameter?, graph?}`; use `ui.menu.invoke` to enter it in the graph panel | | `graph.pattern.set` | `{id, pattern}` replaces an FX-Map subgraph with cycle validation and undo | | `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` | | `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` | @@ -84,11 +84,70 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | +## 3D material assignment + +`view.3d.outputs {graph?, reset?}` applies a material graph's image outputs by their usage. +`graph` accepts an index or name and defaults to the open graph. Ordinary application preserves +unmatched channel assignments; `reset: true` clears them while preserving the scene, camera and lighting. +Outputs with unsupported usages or scalar/vector results cannot supply material textures. + +`view.3d.assign {graph?, node?, port?, channel, reset?}` assigns an individual image to `baseColor`, +`normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive` or `opacity`. +The node defaults to the selection only in the open graph. The port accepts an identifier or index; +terminal Output nodes use `output` or index 0. Assignments refer to their source graph and named port, +update when that source changes, and remain active while editing a Function Graph. +`view.3d.clear {}` removes assignments without resetting the scene. + +Opening a material graph automatically previews its output usages. Selecting or previewing a node +in 2D does not reassign the 3D material. Dragging a graph from Explorer onto the 3D view applies its outputs without opening the graph. +Canvas and Explorer context menus use the same assignment +commands; the 3D View's Material menu lists its channel sources. A Height-only output affects height +sampling, not Base Color; assign that image to `baseColor` to inspect its grayscale pattern on the mesh. + +`session.inspect.material3d` reports assignments and resolved channels, including source graph/node/port, +image dimensions and mean values. Assignment commands leave the package and document undo history +unchanged. Document undo restores the associated source references; replacing a package clears them. + ## Function graphs `file.new {"kind": "function", "name": "Calculation"}` creates a standalone Function Graph. Omit `kind`, or use `"material"`, for a Graph. `graph.function.set {"function": {...}}` replaces the active standalone function through one validated, undoable command. +Both `graph.function.set` and `graph.function.edit` accept an optional `target`: `{"kind":"graph"}` +(the default), `{"kind":"parameter","node":12,"parameter":"function"}`, +`{"kind":"dynamic","node":12,"parameter":"opacity"}`, or +`{"kind":"pattern","owner":12,"node":3,"parameter":"patternrotation"}`. + +`graph.function.edit` accepts `edit: {action: add|move|connect|value|output, ...}`. +For example, `{"edit":{"action":"add","operation":"mul","at":[256,0],"snap":true}}` +creates and returns a node ID using the same defaults as library and context-menu insertion. +`graph.pattern.edit` accepts the FX-Map owner `id` and +`edit: {action: add|move|connect|disconnect|root|value, ...}`. +Use `command.list` for command descriptions and the serialized `FunctionEdit`/`PatternEdit` types +in `crates/engine/src/` for the action fields. Value edits are individual undo steps by default; +`merge: true` groups repeated updates to the same target and value until `edit.finish` or another +edit ends the group. Idle UI frames preserve explicitly requested automation groups. + +`ui.menu.invoke` sends selection actions to the focused editor, including embedded Function +windows. `ui.inspect.subgraph.target` identifies that Function target; its canvas rectangles and +ports correspond to the same editor. Raw `command.run` calls retain their explicit command targets. + + +Selection and clipboard commands (`graph.select`, `edit.selectAll`, `edit.copy`, `edit.cut`, +`edit.paste`, `edit.duplicate`, `edit.delete`, their without-link/relink variants and upstream/downstream +selection) also work without a UI. They infer the active standalone Function Graph. To address an +embedded graph, pass `function: <FunctionGraphTarget>` or `pattern: <owner node id>` and explicit +`ids` for selection-dependent operations. `edit.selectAll` returns those IDs. An optional numeric +`graph` guards against the owning graph no longer being active. `graph.align` accepts the same +Function and FX-Map targets with explicit IDs. + +Results include `ids` and `selected`; copy/cut also return `copied` and a typed `clip` accepted by +paste. The session retains the most recent embedded clipboard. Cross-target paste keeps internal +links and drops external links. Standalone commands update the session selection; embedded commands +return their selection without changing the parent selection. Invalid operations preserve the +document, clipboard, selection and undo history. Creation and all function/pattern setters share +cycle, capacity, ID and position validation. + A function has `nodes` and an optional `output` node id. Each node has `id`, native `op`, `inputs` (source ids or null for unwired ports), optional `value`, `type_code` and `pos`. @@ -121,10 +180,13 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k "source": "source.sbs" } ``` -- Usages: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive`, - `opacity`, `specular` (the first output of each). Color usages (`baseColor`, `emissive`, - `specular`) are 8-bit sRGB PNGs, the rest 16-bit linear. Normals are tangent space, OpenGL (Y+); - height is 0..1 with 0.5 at the surface. +- Usages come from the shared `ComponentUsage` catalog (the first output of each, excluding + `any`). The catalog includes PBR, diffuse/specular, coat, sheen, scattering and user channels. + Color maps are 8-bit sRGB PNGs; data maps are 16-bit linear. Each map records its color space. + Additional usage identifiers do not change the manifest version; consumers may ignore usages + they do not support. Normals are tangent space, OpenGL (Y+); height is 0..1 with 0.5 at the surface. + The 3D preview supports base color (including `diffuse`), normal, roughness, metallic, height, + ambient occlusion, emissive and opacity; other usages remain available for SBS and exports. - Parameters are the exposed inputs other apps can set (float, float2-4, int, int2, bool, color, enum), values in the typed form `{"t", "v"}`; colors are linear RGBA. - Inputs are the graph's input nodes. Mesh maps feed them by identifier: `ambientOcclusion`, From 74ff4a9dc37d15473808814a90961544b859a9b4 Mon Sep 17 00:00:00 2001 From: chasse20 <chasse20@gmail.com> Date: Fri, 6 Nov 2026 01:22:07 -0500 Subject: [PATCH 83/91] Fix debug UI tests and remove redundant coverage --- crates/engine/src/session.test.rs | 35 +-------------- crates/eval/src/tests.rs | 14 ++---- crates/ui-egui/src/graph/canvas_tests.rs | 34 +------------- crates/ui-egui/src/graph/frames.rs | 4 +- crates/ui-egui/src/graph/review_tests.rs | 7 ++- crates/ui-egui/src/material_craft_app.test.rs | 26 +++-------- crates/ui-egui/src/unsaved.test.rs | 44 +------------------ crates/ui-egui/tests/{common => }/search.rs | 21 +++++++-- .../{search_query.rs => search/query.rs} | 24 +++------- .../tests/{search_rows.rs => search/rows.rs} | 24 ++++------ 10 files changed, 56 insertions(+), 177 deletions(-) rename crates/ui-egui/tests/{common => }/search.rs (66%) rename crates/ui-egui/tests/{search_query.rs => search/query.rs} (64%) rename crates/ui-egui/tests/{search_rows.rs => search/rows.rs} (59%) diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs index 35bf56b4..d254c555 100644 --- a/crates/engine/src/session.test.rs +++ b/crates/engine/src/session.test.rs @@ -1,17 +1,3 @@ -#[cfg(test)] -mod session_tests { - use crate::Session; - use materialcraft_core::Package; - - #[test] - fn sync_cook_bumps_the_cook_epoch() { - let mut s = Session::new(Package::new("t")); - let before = s.cook_epoch; - s.cook(); - assert_ne!(s.cook_epoch, before); - } -} - use materialcraft_core::{Package, Resource}; use materialcraft_formats::{Depth, encode}; use materialcraft_image::{Image, Kind, resource_key}; @@ -39,11 +25,7 @@ fn the_resource_decoder_reads_data_maps_as_stored() { #[cfg(test)] mod merge_tests { - use crate::{EngineError, Session}; - - fn session() -> Session { - crate::sample_session() - } + use crate::Session; fn set(s: &mut Session, key: &str) { s.edit_merged(key, "Set parameter", |s| { @@ -55,7 +37,7 @@ mod merge_tests { #[test] fn same_key_merges_until_finish_edit() { - let mut s = session(); + let mut s = crate::new_session(); let base = s.history().len(); set(&mut s, "k"); set(&mut s, "k"); @@ -64,19 +46,6 @@ mod merge_tests { set(&mut s, "k"); assert_eq!(s.history().len(), base + 2, "a second drag after finish_edit is a new entry"); } - - #[test] - fn failed_merged_edit_restores_the_session() { - let mut s = session(); - set(&mut s, "k"); - let name = s.pkg.name.clone(); - let r: Result<(), EngineError> = s.edit_merged("k", "Set parameter", |s| { - s.pkg.name = "half-applied".into(); - Err(EngineError::Other("boom".into())) - }); - assert!(r.is_err()); - assert_eq!(s.pkg.name, name); - } } #[test] diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 7e2d8d8e..bacffb89 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -275,14 +275,6 @@ fn partial_cooks_keep_shared_dependencies_and_first_duplicate_node() { use crate::cache_key::image_key; use std::sync::Arc; #[test] -fn input_image_cache_key_covers_every_pixel() { - let a = Image::filled(128, 128, Kind::Gray, [0.0; 4]); - let mut b = a.clone(); - Arc::make_mut(&mut b.data)[1] = 1.0; - let cache = Mutex::new(Cache::default()); - assert_ne!(image_key(&a, &cache), image_key(&b, &cache)); -} -#[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]); @@ -293,9 +285,11 @@ fn cached_input_fingerprint_tracks_copy_on_write_and_shape() { assert_ne!(changed, first); image.w = 64; image.h = 256; - assert_ne!(image_key(&image, &cache), changed); + let reshaped = image_key(&image, &cache); + assert_ne!(reshaped, changed); + cache.lock().unwrap().clear(); - assert_eq!(image_key(&image, &cache), image_key(&image, &cache)); + assert_eq!(image_key(&image, &cache), reshaped); } #[test] fn preview_cap_does_not_compound_downscaling() { diff --git a/crates/ui-egui/src/graph/canvas_tests.rs b/crates/ui-egui/src/graph/canvas_tests.rs index 5462b88f..ddb3c748 100644 --- a/crates/ui-egui/src/graph/canvas_tests.rs +++ b/crates/ui-egui/src/graph/canvas_tests.rs @@ -1,11 +1,9 @@ +use super::GraphCamera; use super::canvas::*; -use super::node_card::port as port_pos; -use super::search::matches; use super::wire_geometry::{WIRE_HIT, bezier_at, bezier_distance, bezier_points, wire_at}; -use super::{GraphCamera, node_card, node_rect}; use crate::MaterialCraftApp; use egui::{Ui, Vec2, pos2, vec2}; -use materialcraft_engine::core::{Node, NodeId}; +use materialcraft_engine::core::NodeId; use serde_json::json; use super::frames::Frames; @@ -88,15 +86,6 @@ fn clicking_the_shown_node_keeps_its_port() { assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); } -#[test] -fn tab_opens_search_in_the_full_workspace() { - let mut f = Frames::new(materialcraft_engine::sample_session()); - let pointer = f.app.graph.view.center(); - let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); - assert!(f.app.graph.search.is_some()); -} - #[test] fn clicked_wires_swap_with_x_and_delete_together() { let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); @@ -184,14 +173,6 @@ fn node_search_shortcuts_respect_hover_and_keyboard_focus() { } } -#[test] -fn search_finds_by_label_and_category() { - assert!(matches("uniform").iter().any(|d| d.id == "uniform")); - assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); - assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); - assert!(matches("zzzz").is_empty()); -} - #[test] fn wires_are_hit_near_their_curve_only() { let a = (NodeId(1), "input".to_string()); @@ -208,14 +189,3 @@ fn wires_are_hit_near_their_curve_only() { assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); } - -#[test] -fn port_positions_stay_on_the_card() { - let n = Node::new(NodeId(1), "blend", [0.0, 0.0]); - let r = node_rect(&n, 3, 1, true); - for i in 0..3 { - let p = port_pos(r, i, 3, false, false); - assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); - assert!(p.y > r.top() + node_card::HEADER_HEIGHT && p.y < r.bottom() - node_card::FOOTER_HEIGHT); - } -} diff --git a/crates/ui-egui/src/graph/frames.rs b/crates/ui-egui/src/graph/frames.rs index 7b842b77..b9bf8ebc 100644 --- a/crates/ui-egui/src/graph/frames.rs +++ b/crates/ui-egui/src/graph/frames.rs @@ -28,10 +28,12 @@ impl Frames { let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))); let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() }; let app = &mut self.app; - let output = self.ctx.run_ui(input, |ui| { + let mut output = self.ctx.run_ui(input, |ui| { app.step(&ui.ctx().clone()); app.draw(ui); }); + // These interaction tests inspect shapes without uploading textures + output.textures_delta.clear(); self.canvas_text = output .shapes .iter() diff --git a/crates/ui-egui/src/graph/review_tests.rs b/crates/ui-egui/src/graph/review_tests.rs index 98de7f91..a327668a 100644 --- a/crates/ui-egui/src/graph/review_tests.rs +++ b/crates/ui-egui/src/graph/review_tests.rs @@ -241,7 +241,9 @@ fn canvas_frame_cost() { crate::theme::install(&context); let mut frame = || { let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; - std::hint::black_box(context.run_ui(input, |ui| super::show(&mut app, ui))); + let mut output = context.run_ui(input, |ui| super::show(&mut app, ui)); + output.textures_delta.clear(); + std::hint::black_box(output); }; for _ in 0..3 { frame(); @@ -312,11 +314,12 @@ fn properties_and_library_follow_the_active_embedded_function() { let label = materialcraft_engine::nodes::function::definition("const_float1").unwrap().label; assert!(crate::properties::title(&frames.app).starts_with(label)); frames.app.ui.library_search.clear(); - let output = frames + let mut output = frames .ctx .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 800.0))), ..Default::default() }, |ui| { crate::library::show(&mut frames.app, ui) }); + output.textures_delta.clear(); assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.job.text.contains("Search functions")))); menus::invoke(&mut frames.app, &frames.ctx, "ui.graph.parent"); assert_eq!(EditorTarget::resolve(&frames.app), EditorTarget::Material); diff --git a/crates/ui-egui/src/material_craft_app.test.rs b/crates/ui-egui/src/material_craft_app.test.rs index 2c32f827..70d337d0 100644 --- a/crates/ui-egui/src/material_craft_app.test.rs +++ b/crates/ui-egui/src/material_craft_app.test.rs @@ -1,7 +1,6 @@ #[cfg(test)] mod lib_tests { use crate::MaterialCraftApp; - use crate::cook::execute_guarded; use crate::state::UiState; use materialcraft_engine::sample_session; use serde_json::json; @@ -13,19 +12,11 @@ mod lib_tests { assert!(app.toasts.iter().any(|t| t.error)); assert!(app.run("graph.node.add", json!({"def": "levels"})).is_some()); } - - #[test] - fn guarded_execute_returns_command_errors_as_strings() { - let mut s = sample_session(); - let e = execute_guarded(&mut s, "no.such.command", &json!({})).unwrap_err(); - assert!(!e.is_empty()); - assert!(execute_guarded(&mut s, "graph.node.add", &json!({"def": "levels"})).is_ok()); - } } #[cfg(test)] mod unsaved_state_tests { - use crate::unsaved::{Choice, Guarded, guard}; + use crate::unsaved::{Choice, Guarded, Step, answer, guard}; use crate::{MaterialCraftApp, state::UiState}; fn app(modified: bool) -> MaterialCraftApp { @@ -41,9 +32,13 @@ mod unsaved_state_tests { guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); assert!(a.ui.windows.unsaved.is_some()); assert_eq!(a.session.pkg.name, before, "nothing was replaced yet"); - // The held action is visible as serde state (control channel `ui.inspect`). + // The control channel can inspect the held action let v = serde_json::to_value(&a.ui).unwrap(); assert_eq!(v["windows"]["unsaved"]["kind"], "menu"); + + assert_eq!(answer(&mut a.ui.windows.unsaved, Choice::Cancel), Step::Stop); + assert!(a.session.modified); + assert_eq!(a.session.pkg.name, before); } #[test] @@ -54,15 +49,6 @@ mod unsaved_state_tests { assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("New_graph"), "the empty package replaced it"); } - #[test] - fn discard_runs_the_held_action_and_cancel_keeps_the_work() { - let mut a = app(true); - guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); - let step = crate::unsaved::answer(&mut a.ui.windows.unsaved, Choice::Cancel); - assert_eq!(step, crate::unsaved::Step::Stop); - assert!(a.session.modified); - } - #[test] fn a_pending_dialog_is_not_restored_from_saved_state() { let mut a = app(true); diff --git a/crates/ui-egui/src/unsaved.test.rs b/crates/ui-egui/src/unsaved.test.rs index 3bdb17b9..859bcd01 100644 --- a/crates/ui-egui/src/unsaved.test.rs +++ b/crates/ui-egui/src/unsaved.test.rs @@ -1,39 +1,11 @@ #[cfg(test)] mod unsaved_tests { - use crate::unsaved::{Choice, Guarded, Step, after_save, answer, needs_confirmation, request}; + use crate::unsaved::{Choice, Guarded, Step, answer}; fn open() -> Guarded { Guarded::OpenPath { path: "a.sbs".into() } } - #[test] - fn a_clean_session_never_asks() { - let mut s = materialcraft_engine::sample_session(); - s.modified = false; - assert!(!needs_confirmation(&s)); - let mut pending = None; - assert_eq!(request(&mut pending, false, open()), Some(open())); - assert_eq!(pending, None); - } - - #[test] - fn a_modified_session_asks_and_holds_the_action() { - let mut s = materialcraft_engine::sample_session(); - s.modified = true; - assert!(needs_confirmation(&s)); - let mut pending = None; - assert_eq!(request(&mut pending, true, open()), None); - assert_eq!(pending, Some(open())); - } - - #[test] - fn the_first_pending_action_is_kept() { - let mut pending = None; - request(&mut pending, true, open()); - assert_eq!(request(&mut pending, true, Guarded::Quit), None); - assert_eq!(pending, Some(open())); - } - #[test] fn cancel_drops_discard_runs_save_saves_first() { let mut pending = Some(open()); @@ -50,20 +22,6 @@ mod unsaved_tests { assert_eq!(answer(&mut None, Choice::Discard), Step::Stop, "nothing pending, nothing to run"); } - - #[test] - fn closing_the_window_is_held_only_for_unsaved_work() { - use crate::unsaved::holds_close; - assert!(holds_close(true, false)); - assert!(!holds_close(false, false)); - assert!(!holds_close(true, true), "after Discard the close goes through"); - } - - #[test] - fn the_action_runs_after_save_only_when_the_save_worked() { - assert_eq!(after_save(false, open()), Some(open())); - assert_eq!(after_save(true, open()), None, "still modified: the save was cancelled or failed"); - } } #[test] diff --git a/crates/ui-egui/tests/common/search.rs b/crates/ui-egui/tests/search.rs similarity index 66% rename from crates/ui-egui/tests/common/search.rs rename to crates/ui-egui/tests/search.rs index 63735d78..a4fd4cd2 100644 --- a/crates/ui-egui/tests/common/search.rs +++ b/crates/ui-egui/tests/search.rs @@ -1,11 +1,13 @@ +//! Search interactions also capture screenshots when MC_SNAPSHOT_DIR is set + use egui::{Event, Pos2, Rect, epaint::Shape, vec2}; use egui_kittest::Harness; use materialcraft_ui_egui::{MaterialCraftApp, UiState}; -pub fn harness(render: bool) -> Harness<'static, MaterialCraftApp> { +fn harness() -> Harness<'static, MaterialCraftApp> { let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); - let builder = if render { builder.wgpu() } else { builder }; + let builder = if std::env::var_os("MC_SNAPSHOT_DIR").is_some() { builder.wgpu() } else { builder }; let mut h = builder.build_ui_state( |ui, app: &mut MaterialCraftApp| { app.step(&ui.ctx().clone()); @@ -25,7 +27,7 @@ pub fn harness(render: bool) -> Harness<'static, MaterialCraftApp> { h } -pub fn label_position(h: &Harness<'static, MaterialCraftApp>, label: &str) -> Option<Pos2> { +fn label_position(h: &Harness<'static, MaterialCraftApp>, label: &str) -> Option<Pos2> { let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); fn find(shape: &Shape, clip: Rect, popup: Rect, label: &str) -> Option<Pos2> { match shape { @@ -38,3 +40,16 @@ pub fn label_position(h: &Harness<'static, MaterialCraftApp>, label: &str) -> Op } h.output().shapes.iter().find_map(|s| find(&s.shape, s.clip_rect, popup, label)) } + +fn save_snapshot(harness: &mut Harness<'static, MaterialCraftApp>, name: &str) { + if let Some(directory) = std::env::var_os("MC_SNAPSHOT_DIR") { + let directory = std::path::PathBuf::from(directory); + std::fs::create_dir_all(&directory).unwrap(); + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } +} + +#[path = "search/query.rs"] +mod query; +#[path = "search/rows.rs"] +mod rows; diff --git a/crates/ui-egui/tests/search_query.rs b/crates/ui-egui/tests/search/query.rs similarity index 64% rename from crates/ui-egui/tests/search_query.rs rename to crates/ui-egui/tests/search/query.rs index 5c6d819d..f2ba600e 100644 --- a/crates/ui-egui/tests/search_query.rs +++ b/crates/ui-egui/tests/search/query.rs @@ -1,6 +1,4 @@ //! Resetting the search selection must also reveal it in a previously scrolled list. -#[path = "common/search.rs"] -mod search; use egui::{Event, Key, Modifiers}; use egui_kittest::{Harness, kittest::Queryable}; use materialcraft_ui_egui::MaterialCraftApp; @@ -17,7 +15,7 @@ fn filter_after_scrolling(h: &mut Harness<'static, MaterialCraftApp>) { h.event(Event::Text("blur".into())); h.step(); h.run_steps(25); - assert!(search::label_position(h, "Blur").is_some(), "selected first filtered result is offscreen"); + assert!(super::label_position(h, "Blur").is_some(), "selected first filtered result is offscreen"); } fn assert_inserted(h: &mut Harness<'static, MaterialCraftApp>, def: &str) { h.key_press(Key::Enter); @@ -28,13 +26,14 @@ fn assert_inserted(h: &mut Harness<'static, MaterialCraftApp>, def: &str) { } #[test] fn filtering_after_scrolling_reveals_and_inserts_first_match() { - let mut h = search::harness(false); + let mut h = super::harness(); filter_after_scrolling(&mut h); + super::save_snapshot(&mut h, "filtered-first-result"); assert_inserted(&mut h, "blur"); } #[test] fn clearing_a_scrolled_query_reveals_and_inserts_first_match() { - let mut h = search::harness(false); + let mut h = super::harness(); h.event(Event::Text("blur".into())); h.step(); scroll(&mut h, 15); @@ -43,12 +42,12 @@ fn clearing_a_scrolled_query_reveals_and_inserts_first_match() { h.key_press(Key::Backspace); h.step(); h.run_steps(25); - assert!(search::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after clearing"); + assert!(super::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after clearing"); assert_inserted(&mut h, "bitmap"); } #[test] fn reopening_a_scrolled_search_reveals_first_match() { - let mut h = search::harness(false); + let mut h = super::harness(); scroll(&mut h, 45); h.key_press(Key::Escape); h.step(); @@ -57,15 +56,6 @@ fn reopening_a_scrolled_search_reveals_first_match() { h.step(); h.run_steps(25); assert!(h.get_by_label("Search nodes").rect().width() > 0.0); - assert!(search::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after reopening"); + assert!(super::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after reopening"); assert_inserted(&mut h, "bitmap"); } -#[test] -#[ignore = "requires an offscreen GPU"] -fn filtered_first_result_screenshot() { - let mut h = search::harness(true); - filter_after_scrolling(&mut h); - let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("filtered-first-result.png")).unwrap(); -} diff --git a/crates/ui-egui/tests/search_rows.rs b/crates/ui-egui/tests/search/rows.rs similarity index 59% rename from crates/ui-egui/tests/search_rows.rs rename to crates/ui-egui/tests/search/rows.rs index 5f25bbb4..d7992bda 100644 --- a/crates/ui-egui/tests/search_rows.rs +++ b/crates/ui-egui/tests/search/rows.rs @@ -1,12 +1,10 @@ //! Clicking anywhere across a search result's row should insert that result. -#[path = "common/search.rs"] -mod search; use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; use egui_kittest::Harness; use materialcraft_ui_egui::MaterialCraftApp; fn right_side(h: &Harness<'static, MaterialCraftApp>) -> Pos2 { - let y = search::label_position(h, "Bitmap").unwrap().y; + let y = super::label_position(h, "Bitmap").unwrap().y; let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); pos2(popup.right() - 24.0, y) } @@ -22,22 +20,16 @@ fn click(h: &mut Harness<'static, MaterialCraftApp>, pos: Pos2) { #[test] fn clicking_label_or_right_side_inserts_the_same_result() { for right in [false, true] { - let mut h = search::harness(false); - let pos = if right { right_side(&h) } else { search::label_position(&h, "Bitmap").unwrap() + vec2(8.0, 0.0) }; + let mut h = super::harness(); + let pos = if right { right_side(&h) } else { super::label_position(&h, "Bitmap").unwrap() + vec2(8.0, 0.0) }; + if right { + h.event(Event::PointerMoved(pos)); + h.run_steps(3); + super::save_snapshot(&mut h, "full-width-search-result"); + } click(&mut h, pos); let graph = h.state().session.graph().unwrap(); assert_eq!(graph.nodes.len(), 1, "row click did not insert a node (right_side={right})"); assert_eq!(graph.nodes[0].def, "bitmap"); } } -#[test] -#[ignore = "requires an offscreen GPU"] -fn full_width_result_screenshot() { - let mut h = search::harness(true); - let pos = right_side(&h); - h.event(Event::PointerMoved(pos)); - h.run_steps(3); - let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("full-width-search-result.png")).unwrap(); -} From 0ce7a6aafbfaffa6be7634155109eaba1f4d8bac Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:10:21 +0200 Subject: [PATCH 84/91] Hash bound input-image resources into graph instance cache keys (#110) * Hash bound input-image resources into graph instance cache keys A graph instance can show a stale preview image after its bound bitmap resource is replaced, because the instance cache key never changes. Hashing those resources makes the instance re-cook when the bitmap changes. Include the content hashes of resources referenced by graph.input_images (and their linear flags) in graph_tree_hash, and add a regression test that cooks an instance, replaces the bound resource bytes, and asserts the new image is cooked instead of the cached one. Test: bound_input_image_resource_change_recooks_instance failed before the change and passes after. * Address review for pull request 110 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- crates/eval/src/cache_key.rs | 5 +++ crates/eval/src/graph_execution.rs | 4 +- crates/eval/src/tests.rs | 65 ++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index 40e47723..62b01ab8 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -52,6 +52,11 @@ pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { index.hash(&mut h); serde_json::to_string(graph).unwrap_or_default().hash(&mut h); + for (id, res) in &graph.input_images { + pkg.resource(res).map(|r| r.bytes.content_hash()).hash(&mut h); + id.hash(&mut h); + graph.input_images_linear.contains(id).hash(&mut h); + } for n in &graph.nodes { if let Some(Value::Text(name)) = n.params.get("resource") { pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index f02a1703..a9c48c19 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -12,9 +12,9 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu let mut cooked = Cooked::default(); let Some(graph) = package.graphs.get(graph_index) else { return cooked }; - // The top-level graph's input nodes show their preview images; the caller's images win + // Input nodes show their bound preview images; the caller's images win let bound; - let options = if options.depth == 0 && !graph.input_images.is_empty() { + let options = if !graph.input_images.is_empty() { let mut inputs: BTreeMap<String, Image> = graph .input_images .iter() diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index bacffb89..1ed1298f 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -364,3 +364,68 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() { p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1)); assert_eq!(first(&p), (0.5, 0.5)); } + +#[test] +fn bound_input_image_resource_change_recooks_instance() { + use materialcraft_core::{Resource, ResourceBytes}; + use std::sync::atomic::AtomicU8; + let mut sub = Graph::new("sub"); + sub.size = [4, 4]; + let i = sub.add_node("input_grayscale", [0.0, 0.0]); + sub.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("in".into())); + let o = sub.add_node("output", [100.0, 0.0]); + sub.connect(i, "output", o, "input").unwrap(); + sub.input_images.insert("in".into(), "curv".into()); + let (top, inst) = instancing("top", "sub"); + let mut p = Package::new("p"); + p.graphs = vec![top, sub]; + p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100]))); + // Stands in for decoding: the first byte picks the shade. + let shade = AtomicU8::new(1); + let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 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 unchanged = cook(&p, 0, &opts, &cache); + assert!(unchanged.nodes[&inst].cached, "an unchanged instance should be served from the cache"); + p.resources[0].bytes = ResourceBytes::new(vec![2; 100]); + shade.store(2, Ordering::Relaxed); + let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&inst].cached, "changing the bound input image resource must recook the instance"); +} + +#[test] +fn bound_input_image_linear_flag_change_recooks_instance() { + use materialcraft_core::{Resource, ResourceBytes}; + let mut sub = Graph::new("sub"); + sub.size = [4, 4]; + let i = sub.add_node("input_grayscale", [0.0, 0.0]); + sub.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("in".into())); + let o = sub.add_node("output", [100.0, 0.0]); + sub.connect(i, "output", o, "input").unwrap(); + sub.input_images.insert("in".into(), "curv".into()); + let (top, inst) = instancing("top", "sub"); + let mut p = Package::new("p"); + 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); + (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]; + 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]; + assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); +} From c479765c013a526726f512e85abe3bd586ea72ff Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:10:27 +0200 Subject: [PATCH 85/91] Reject non-finite glTF normals before normalizing them (#114) A glTF file with NaN or infinite normals currently loads as a mesh with zero normals instead of being rejected like non-finite positions, UVs and OBJ normals. Check raw glTF normals for finiteness before transforming them and return an error for non-finite values, matching the existing finish() checks. Test: gltf_non_finite_normals_are_rejected failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/formats/src/mesh.rs | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 88b1c005..9d712879 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -132,7 +132,15 @@ fn gltf(bytes: &[u8]) -> Result<Mesh> { let pos: Vec<Vec3> = pos.map(|p| m.transform_point3(Vec3::from(p))).collect(); let n = pos.len(); match reader.read_normals() { - Some(ns) => normals.extend(ns.map(|q| m.transform_vector3(Vec3::from(q)).normalize_or_zero())), + Some(ns) => { + for q in ns { + let v = m.transform_vector3(Vec3::from(q)); + if !v.is_finite() { + return Err(bad("the mesh has non-finite (NaN or infinite) normals")); + } + normals.push(v.normalize_or_zero()); + } + } None => all_normals = false, } match reader.read_tex_coords(0) { @@ -241,6 +249,33 @@ mod tests { assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n").is_err()); } + #[test] + fn gltf_non_finite_normals_are_rejected() { + use base64::Engine as _; + let gltf_with_normals = |normals: [[f32; 3]; 4]| { + let idx: [u16; 6] = [0, 1, 2, 0, 2, 3]; + let mut buf: Vec<u8> = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); + buf.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes())); + buf.extend(idx.iter().flat_map(|i| i.to_le_bytes())); + let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + format!( + r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], +"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0,"NORMAL":1}},"indices":2}}]}}], +"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{{"bufferView":1,"componentType":5126,"count":4,"type":"VEC3"}},{{"bufferView":2,"componentType":5123,"count":6,"type":"SCALAR"}}], +"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{{"buffer":0,"byteOffset":48,"byteLength":48}},{{"buffer":0,"byteOffset":96,"byteLength":12}}], +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, + buf.len() + ) + .into_bytes() + }; + let mut nan_normals = [[0.0f32, 0.0, 1.0]; 4]; + nan_normals[2][0] = f32::NAN; + assert!(load_mesh("x.gltf", &gltf_with_normals(nan_normals)).is_err()); + let mut inf_normals = [[0.0f32, 0.0, 1.0]; 4]; + inf_normals[1][2] = f32::INFINITY; + assert!(load_mesh("x.gltf", &gltf_with_normals(inf_normals)).is_err()); + } + #[test] fn a_bad_index_drops_its_whole_triangle_and_later_ones_keep_their_vertices() { // Triangles: (0,1,2), (0,1,9) out of range, (0,2,3). From d05d2bf0a96edf5da67ee4c34312266ca1a4931a Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:10:32 +0200 Subject: [PATCH 86/91] Clamp enum and degenerate-range parameters to hard limits (#115) A hostile file or binding could supply an out-of-range enum or degenerate-range numeric value that reaches a cook unclamped, breaking the hard-limits guarantee for node parameters. Make clamp_params bound enum values even with no options and bound numeric values even when min is not below max, using the same hard-span limits as other parameters. Test: clamp_params_bounds_enum_without_options failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- crates/nodes/src/parameter.rs | 21 ++++++++++++--------- crates/nodes/src/parameter.test.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/crates/nodes/src/parameter.rs b/crates/nodes/src/parameter.rs index 46b5112c..4925f868 100644 --- a/crates/nodes/src/parameter.rs +++ b/crates/nodes/src/parameter.rs @@ -14,9 +14,12 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) for p in &def.params { let Some(v) = params.get_mut(p.id) else { continue }; if let Value::Enum(i) = v { - if !p.options.is_empty() { - *i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX)); - } + // (an enum without options has nothing to choose from: its default stands) + *i = match (p.options.len().checked_sub(1), &p.default) { + (Some(last), _) => (*i).min(u32::try_from(last).unwrap_or(u32::MAX)), + (None, Value::Enum(d)) => *d, + (None, _) => 0, + }; continue; } if let Value::Color(c) = v { @@ -25,11 +28,11 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) } continue; } - if p.min >= p.max { - continue; - } + // No range declared (an Input Value's default takes any number): only a value that isn't + // a number goes + let ranged = p.min < p.max; let span = p.max - p.min; - let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span); + let (lo, hi) = if ranged { (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) }; // The default's component `i`, or 0 when the default is a different variant let fallback = |i: usize| match &p.default { Value::Float(d) => [*d].get(i).copied(), @@ -46,8 +49,8 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Int(x) => clamp_int(x), - Value::Int2(a) => a.iter_mut().for_each(clamp_int), + Value::Int(x) if ranged => clamp_int(x), + Value::Int2(a) if ranged => a.iter_mut().for_each(clamp_int), _ => {} } } diff --git a/crates/nodes/src/parameter.test.rs b/crates/nodes/src/parameter.test.rs index 226e9e5e..5ecacfd1 100644 --- a/crates/nodes/src/parameter.test.rs +++ b/crates/nodes/src/parameter.test.rs @@ -33,6 +33,32 @@ fn clamp_params_covers_values_set_after_resolution() { assert_eq!(p["opacity"], Value::Float(17.0)); } +#[test] +fn clamp_params_bounds_an_enum_without_options() { + let mut def = find("blend").unwrap().clone(); + let enums = def.params.iter_mut().find(|p| matches!(p.default, Value::Enum(_))).expect("an enum parameter"); + enums.options = &[]; + enums.default = Value::Enum(1); + let id = enums.id; + let mut p = BTreeMap::from([(id.to_string(), Value::Enum(999))]); + clamp_params(&def, &mut p); + assert_eq!(p[id], Value::Enum(1)); +} + +/// A parameter with no declared range keeps any number, and only a value that isn't a number goes. +#[test] +fn clamp_params_keeps_numbers_without_a_declared_range() { + let def = find("input_value").unwrap(); + let default = def.params.iter().find(|p| p.id == "default").unwrap(); + assert!(default.min >= default.max, "input_value's default declares no range"); + let mut p = over("default", Value::Float(3.5)); + clamp_params(def, &mut p); + assert_eq!(p["default"], Value::Float(3.5)); + let mut p = over("default", Value::Float(f32::NAN)); + clamp_params(def, &mut p); + assert_eq!(p["default"], default.default); +} + #[test] fn defaults_lie_inside_their_hard_limits() { for def in catalog() { From a0180da9b6807d64a6f689ae800fd56e3bb46f86 Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:10:38 +0200 Subject: [PATCH 87/91] Reply to non-UTF8 lines on the control channel (#118) Clients cannot tell a refused non-UTF8 request from a dropped connection, unlike malformed JSON which gets an explicit error reply. Make the TCP control servers reply with an error for non-UTF8 lines, closing before auth and continuing after auth like bad JSON. Test: non_utf8_line_before_auth_gets_refusal_reply failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- apps/materialcraft/src/control_server.rs | 22 +++++++++++++++++++++- crates/automation/src/rpc.rs | 18 +++++++++++++----- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index 5e892761..7e1c94f2 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -111,7 +111,15 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"})); return; } - Ok(LineRead::Eof) | Err(_) => return, + Ok(LineRead::Eof) => return, + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": "request is not UTF-8"})); + if !sent || deadline.is_some() { + return; + } + continue; + } + Err(_) => return, } if line.trim().is_empty() { continue; @@ -230,6 +238,18 @@ mod tests { assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); } + #[test] + fn non_utf8_line_before_auth_gets_refusal_reply() { + let addr = server(); + let (mut w, mut r) = connect(addr); + w.write_all(b"\xff\n").unwrap(); + w.flush().unwrap(); + let mut reply = String::new(); + let n = r.read_line(&mut reply).unwrap(); + assert!(n > 0, "a non-UTF8 first line gets a refusal reply, not a silent close"); + assert_eq!(serde_json::from_str::<Value>(&reply).unwrap()["ok"], false); + } + #[test] fn connections_are_limited_and_idle_ones_time_out() { let addr = server(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index dae2611d..427d7a79 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -158,11 +158,19 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st let mut authed = false; let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?); loop { - match read_bounded_line(&mut r, &mut line)? { - LineRead::Eof => return Ok(()), - LineRead::TooLong => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})), - LineRead::Line if line.trim().is_empty() => continue, - LineRead::Line => {} + match read_bounded_line(&mut r, &mut line) { + Ok(LineRead::Eof) => return Ok(()), + Ok(LineRead::TooLong) => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})), + Ok(LineRead::Line) if line.trim().is_empty() => continue, + Ok(LineRead::Line) => {} + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request is not UTF-8"}))?; + if !authed { + return Ok(()); + } + continue; + } + Err(e) => return Err(e), } if authed { write_reply(&mut w, &respond(h, &line))?; From 0e160cd53aceba270bc905f761c5aa64411142ba Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:10:44 +0200 Subject: [PATCH 88/91] Fix 4K preview texture refresh in 2D view (#122) Users switching to 4K previews saw stale low-resolution textures in the 2D view. Include image dimensions in the texture cache key so a size change reloads the texture at the new resolution. Test: four_k_preview_refreshes_texture_after_size_change failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/view2d.rs | 2 ++ crates/ui-egui/tests/resolution.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 56fc6ce6..70bb3aca 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -95,6 +95,8 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let texture_limit = ctx.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 ^ (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; diff --git a/crates/ui-egui/tests/resolution.rs b/crates/ui-egui/tests/resolution.rs index ae5d15a7..64231d57 100644 --- a/crates/ui-egui/tests/resolution.rs +++ b/crates/ui-egui/tests/resolution.rs @@ -48,6 +48,36 @@ fn selecting_4k_cooks_and_displays_4k_material_maps() { assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); } +#[test] +fn four_k_preview_refreshes_texture_after_size_change() { + let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::theme::install).with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.apply_prefs(); + view2d::show(app, ui); + }, + 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. + let node = h.state().session.view2d.node.unwrap(); + h.state_mut().session.preview_size = Some(4096); + h.state_mut().session.cook(); + h.state_mut().session.cooked.nodes.get_mut(&node).unwrap().key = 0; + 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!(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!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256))); +} + #[test] fn command_resolution_survives_preferences_and_invalid_requests() { let mut app = app(); From d560df3392d858c02530289e7e52d2007b599aa1 Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:20:32 +0200 Subject: [PATCH 89/91] Restore modified flag when undoing to saved state (#112) * Restore modified flag when undoing to saved state Undoing every edit should return the session to its saved, unmodified state so the unsaved-work prompt is not shown spuriously. Make undo and redo preserve the restored snapshot's modified flag while still marking the graph dirty for cooking, and add a regression test that edits from a clean session and undoes to assert modified is false. Test: undo_to_unmodified_state_clears_modified_flag failed before the change and passes after. * Tests: add a node that exists on main Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/session.rs | 4 ++-- crates/engine/tests/session.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 0f40bb24..5ff2f673 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -357,7 +357,7 @@ impl Session { self.redo.push(cur); self.restore(s); self.merge_key = None; - self.changed(); + self.dirty = true; Some(label) } @@ -369,7 +369,7 @@ impl Session { self.undo.push(cur); self.restore(s); self.merge_key = None; - self.changed(); + self.dirty = true; Some(label) } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 3f2a6de1..8ee5d14c 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -467,3 +467,15 @@ fn selected_wires_swap_their_sources_and_delete_together() { run(&mut s, "edit.undo", json!({})); assert_eq!(s.graph().unwrap().connections.len(), 4); } + +#[test] +fn undo_to_unmodified_state_clears_modified_flag() { + let mut s = sample_session(); + assert!(!s.modified); + run(&mut s, "graph.node.add", json!({"def": "uniform", "at": [0, 0]})); + assert!(s.modified); + run(&mut s, "edit.undo", json!({})); + assert!(!s.modified, "undoing to the unmodified state should clear the modified flag"); + run(&mut s, "edit.redo", json!({})); + assert!(s.modified, "redoing to the modified state should set the modified flag"); +} From 3d399dd1a5f22e12100dfa5bd68fc4a7d3ec9adf Mon Sep 17 00:00:00 2001 From: eliets2 <elietecovery@gmail.com> Date: Fri, 6 Nov 2026 11:23:13 +0200 Subject: [PATCH 90/91] Keep typed graph name and attribute text across frames (#124) * Keep typed graph name and attribute text across frames Typing a graph name or attribute currently loses the text between frames, so the edit never reaches the engine command on focus loss. Persisting the draft across frames, as the slider and preset name already do, makes the edit commit correctly. Store the in-progress graph name and attribute text in temporary UI data while editing, like presets_bar does, and commit the stored text on lost_focus. Add a harness test that types a new graph name across several frames, moves focus away, and asserts the renamed graph. Test: graph_name_typed_across_frames_commits_on_focus_loss failed before the change and passes after. * Graph properties: a draft field's id salt is a string Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- crates/ui-egui/src/property/graph.rs | 28 +++++++++++++++++++-------- crates/ui-egui/tests/numeric_input.rs | 26 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/property/graph.rs b/crates/ui-egui/src/property/graph.rs index 166b627b..8613cdb5 100644 --- a/crates/ui-egui/src/property/graph.rs +++ b/crates/ui-egui/src/property/graph.rs @@ -5,8 +5,26 @@ use egui_phosphor::regular as icon; use materialcraft_engine::core::{Graph, OutputFormat, Resource, Value}; use serde_json::{Value as JsonValue, json}; +/// A one-line field for a value the engine holds: what is typed stays between frames, and the text +/// comes back when the field loses focus with something new in it. A change to the value from +/// elsewhere (undo) drops the draft. +fn draft_field(ui: &mut Ui, salt: String, current: &str, label: &str) -> Option<String> { + let id = ui.make_persistent_id(salt); + let draft: Option<(String, String)> = ui.data(|data| data.get_temp(id)); + let mut text = draft.filter(|(seen, _)| seen == current).map_or_else(|| current.to_string(), |(_, text)| text); + let response = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, label); + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(id, (current.to_string(), text.clone()))); + } else { + ui.data_mut(|data| data.remove_temp::<(String, String)>(id)); + } + (response.lost_focus() && text != current).then_some(text) +} + pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); + let graph_index = app.session.graph; let Ok(graph) = app.session.graph() else { ui.label(tr("No graph is open")); return; @@ -17,10 +35,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { section(ui, "graph-base", tr("Base parameters"), |ui| { ui.horizontal(|ui| { ui.label(tr("Name")); - let mut name = graph.name.clone(); - let response = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); - crate::widgets::name(&response, egui::Role::TextInput, "Graph name"); - if response.lost_focus() && name != graph.name { + if let Some(name) = draft_field(ui, format!("graph-name-{graph_index}"), &graph.name, "Graph name") { emit("graph.rename", json!({"name": name})); } }); @@ -57,10 +72,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ] { ui.horizontal(|ui| { ui.label(tr(label)); - let mut edited = current.clone(); - let response = ui.add(egui::TextEdit::singleline(&mut edited).desired_width(ui.available_width())); - crate::widgets::name(&response, egui::Role::TextInput, label); - if response.lost_focus() && edited != *current { + if let Some(edited) = draft_field(ui, format!("graph-attribute-{graph_index}-{key}"), current, label) { emit("graph.attributes", json!({key: edited})); } }); diff --git a/crates/ui-egui/tests/numeric_input.rs b/crates/ui-egui/tests/numeric_input.rs index 5679841d..df84d97e 100644 --- a/crates/ui-egui/tests/numeric_input.rs +++ b/crates/ui-egui/tests/numeric_input.rs @@ -47,6 +47,32 @@ fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32 } } #[test] +fn graph_name_typed_across_frames_commits_on_focus_loss() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.run("file.new", json!({"template":"empty"})).unwrap(); + app.session.reset_history(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + h.state_mut().run("graph.select", json!({"ids": []})).unwrap(); + h.run_steps(3); + h.get_by_label("Graph name").click(); + h.step(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); + type_text(&mut h, "My_graph"); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(4); + assert_eq!(h.state().session.graph().unwrap().name, "My_graph", "graph name typed across frames was reset before focus was lost"); +} +#[test] fn offset_x_commits_on_enter_and_focus_loss_with_undo() { for enter in [true, false] { let (mut h, id) = harness(false); From 1d6dfe22408bb25ee959b9a3d68e52b8c400b6c0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:01 +0100 Subject: [PATCH 91/91] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 ++++++++++++++ AGENTS.md | 64 +++++++++++++++++++++++++++---- CLAUDE.md | 6 +-- 3 files changed, 86 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 00000000..de64ad3e --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 812eeef3..2d250fed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ +<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb --> +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. +<!-- craft-house-rules:end --> +<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 --> +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. +<!-- craft-house-rules:end --> + # AGENTS.md: guide for AI agents and contributors MaterialCraft is an open-source, native **node-based procedural material designer**: a clean-room @@ -13,10 +66,7 @@ TextureCraft) in user-facing text: UI, window titles, About, installers, release Machine names stay lowercase: crates (`materialcraft-*`), binaries, file names, ids (`ai.storyteller.materialcraft`). The project format is SBS (`.sbs`). Legacy package compatibility is not required. -Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next -to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its -standards, and contribute reusable learnings back there. Shared code goes only in craft-libs -(`standards/shared-libraries.md`); otherwise copy, don't depend. TextureCraft is the sibling this +Shared code goes only in craft-libs; otherwise copy, don't depend. TextureCraft is the sibling this repository's infrastructure (xtask, automation, packaging, docking, theme) was copied from. The goal is full parity with the professional node-based material workflow (the same panels, @@ -106,7 +156,7 @@ implementation, in code, docs and commits. People trust MaterialCraft with hours of work. A malformed package, a hostile command or MCP parameter, an odd keystroke or a full disk must produce an error the user or agent can act on, -never a panic. The shared standard is `../craftrules/standards/never-crash.md`. +never a panic. - Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries @@ -183,6 +233,6 @@ after every arc of work that builds and passes. - `ROADMAP.md`: milestones, parity estimate and remaining effort. - `docs/target-app-parity.md` and `docs/gaps.md`: the assessment and the work list. -- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing. -- `plan/` (local, gitignored): execution plan and notes. +- `docs/releasing.md`: release builds and signing. +- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent. - `log/` (local, gitignored): the dev log. diff --git a/CLAUDE.md b/CLAUDE.md index 911603ec..43c994c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1 @@ -# MaterialCraft: instructions for Claude - -Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository -(workspace map, golden rules including the asset and attribution rules, the definition of done). -Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps. +@AGENTS.md