diff --git a/Cargo.lock b/Cargo.lock index 69db9d50..c3134a01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2331,7 +2331,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "materialcraft" -version = "0.1.2" +version = "0.1.3" dependencies = [ "eframe", "egui", @@ -2340,13 +2340,14 @@ dependencies = [ "materialcraft-automation", "materialcraft-engine", "materialcraft-ui-egui", + "rfd", "serde_json", "winresource", ] [[package]] name = "materialcraft-automation" -version = "0.1.2" +version = "0.1.3" dependencies = [ "base64 0.22.1", "cap-std", @@ -2367,7 +2368,7 @@ dependencies = [ [[package]] name = "materialcraft-cli" -version = "0.1.2" +version = "0.1.3" dependencies = [ "materialcraft-automation", "materialcraft-engine", @@ -2378,7 +2379,7 @@ dependencies = [ [[package]] name = "materialcraft-core" -version = "0.1.2" +version = "0.1.3" dependencies = [ "serde", "serde_json", @@ -2387,7 +2388,7 @@ dependencies = [ [[package]] name = "materialcraft-engine" -version = "0.1.2" +version = "0.1.3" dependencies = [ "materialcraft-core", "materialcraft-eval", @@ -2402,7 +2403,7 @@ dependencies = [ [[package]] name = "materialcraft-eval" -version = "0.1.2" +version = "0.1.3" dependencies = [ "materialcraft-core", "materialcraft-image", @@ -2412,7 +2413,7 @@ dependencies = [ [[package]] name = "materialcraft-formats" -version = "0.1.2" +version = "0.1.3" dependencies = [ "base64 0.22.1", "flate2", @@ -2433,7 +2434,7 @@ dependencies = [ [[package]] name = "materialcraft-geom" -version = "0.1.2" +version = "0.1.3" dependencies = [ "glam 0.30.10", "mikktspace", @@ -2444,7 +2445,7 @@ dependencies = [ [[package]] name = "materialcraft-image" -version = "0.1.2" +version = "0.1.3" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2452,7 +2453,7 @@ dependencies = [ [[package]] name = "materialcraft-nodes" -version = "0.1.2" +version = "0.1.3" dependencies = [ "materialcraft-core", "materialcraft-image", @@ -2461,7 +2462,7 @@ dependencies = [ [[package]] name = "materialcraft-render" -version = "0.1.2" +version = "0.1.3" dependencies = [ "materialcraft-core", "materialcraft-geom", @@ -2471,7 +2472,7 @@ dependencies = [ [[package]] name = "materialcraft-ui-egui" -version = "0.1.2" +version = "0.1.3" dependencies = [ "base64 0.22.1", "craft-ui", @@ -2496,7 +2497,7 @@ dependencies = [ [[package]] name = "materialcraft-web" -version = "0.1.2" +version = "0.1.3" dependencies = [ "eframe", "js-sys", @@ -5393,7 +5394,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.1.2" +version = "0.1.3" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 7761605e..03d0173d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ default-members = [ ] [workspace.package] -version = "0.1.2" +version = "0.1.3" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 04d93e12..fa7a15ef 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -34,11 +34,12 @@ USAGE: [--yaw ] [--pitch ] [--graph ] [--set =]... [--full] [--tiling ] [--hq [--displacement ]] Render the material on a 3D scene (rounded_cube, cube, sphere, cylinder, plane, torus, - material_ball), or one node's output (--view 2d), to PNG. No GPU needed. --hq is a beauty - render: real displacement from the height output, ambient occlusion and a key light. + material_ball), or one node's output (--view 2d), to PNG. No GPU needed. The height output + raises the surface; --hq is a beauty render with a finer mesh, 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. @@ -57,10 +58,14 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("cook", &["--graph", "--set"], &["--full"]), ("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"], &[]), + ("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)>, @@ -88,7 +93,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() { @@ -304,3 +310,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/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 7b5a2caa..83f388f9 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -19,6 +19,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/control_server.rs b/apps/materialcraft/src/control_server.rs index c424f846..5e892761 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -16,6 +16,14 @@ use materialcraft_automation::security::{ use materialcraft_ui_egui::ControlRequest; use serde_json::{Value, json}; +#[cfg(test)] +#[path = "control_server.test.rs"] +mod exact_token_tests; + +fn auth_ok(token: &str, method: &str, params: &Value) -> bool { + method == "auth" && params.get("token").and_then(Value::as_str).is_some_and(|t| token_matches(token, t)) +} + /// How long an authenticated connection may stay idle. const IDLE_TIMEOUT: Duration = Duration::from_secs(600); @@ -123,8 +131,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); let params = msg.get("params").cloned().unwrap_or(json!({})); if deadline.is_some() { - let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default(); - if method != "auth" || !token_matches(token, supplied) { + if !auth_ok(token, &method, ¶ms) { // One attempt per connection, as on `materialcraft-cli serve`. reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); return; diff --git a/apps/materialcraft/src/control_server.test.rs b/apps/materialcraft/src/control_server.test.rs new file mode 100644 index 00000000..50b02a30 --- /dev/null +++ b/apps/materialcraft/src/control_server.test.rs @@ -0,0 +1,16 @@ +#[cfg(test)] +mod auth_tests { + use crate::control_server::auth_ok; + use serde_json::json; + + #[test] + fn only_the_exact_token_on_an_auth_request_passes() { + let token = "0123456789abcdef0123456789abcdef"; + assert!(auth_ok(token, "auth", &json!({"token": token}))); + assert!(!auth_ok(token, "auth", &json!({"token": "0123456789abcdef0123456789abcdee"}))); + assert!(!auth_ok(token, "auth", &json!({"token": "short"}))); + assert!(!auth_ok(token, "auth", &json!({}))); + assert!(!auth_ok(token, "auth", &json!({"token": 5}))); + assert!(!auth_ok(token, "command.run", &json!({"token": token}))); + } +} diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index e71470e6..f5e691fa 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -5,6 +5,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; @@ -108,6 +109,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..17596045 --- /dev/null +++ b/apps/materialcraft/src/start_failure.rs @@ -0,0 +1,52 @@ +//! 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. 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 { + 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. +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 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 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}"); + } +} diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 99f24a03..20ef2589 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -3,8 +3,9 @@ use std::path::Path; use materialcraft_engine::core::NodeId; -use materialcraft_engine::{Session, commands, file_cmds, inspect}; -use materialcraft_render::{Lighting, Maps, Scene, Settings}; +use materialcraft_engine::formats::material::MATERIAL_EXT; +use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds}; +use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES}; use serde_json::{Value, json}; use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png}; @@ -83,7 +84,7 @@ impl Headless { if !self.trusted() { authorize_command(id, ¶ms)?; } - Ok(materialcraft_engine::execute(&mut self.session, id, ¶ms)?) + Ok(materialcraft_engine::commands::execute_request(&mut self.session, id, ¶ms)?) } /// Run `[{id, params?}]` in order, stopping at the first error (reported with its index) @@ -155,7 +156,25 @@ impl Headless { Ok(json!({"files": written})) } - /// Render the 3D view or a node's 2D output as PNG + /// Export a portable material below the granted write root + 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 assigned material or a node 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 }; let saved = self.session.preview_size; @@ -208,6 +227,8 @@ impl Headless { self.light = Some(Lighting::new(&v.environment)); } let tiling = o.tiling.unwrap_or(v.tiling).clamp(0.1, 64.0); + let depth = if o.hq { o.displacement.unwrap_or(v.height_scale) } else { v.height_scale }; + let relief = Relief { depth: depth.clamp(0.0, 0.5), level: v.height_level }; let mut settings = Settings { yaw: o.yaw.unwrap_or(v.yaw), pitch: o.pitch.unwrap_or(v.pitch), @@ -216,7 +237,7 @@ impl Headless { tiling, exposure: v.exposure, env_rotation: v.env_rotation, - height_scale: v.height_scale, + normal_y_flip: v.normal_y_flip, show_env: false, supersample: 2, transparency: v.transparency, @@ -227,14 +248,7 @@ impl Headless { let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max)); let maps = Maps::from_usages(self.session.material_maps()); let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) }; - let displaced = match (o.hq, &maps.height) { - (true, Some(height)) => { - settings.height_scale = 0.0; - Some(Scene::displaced(&scene.mesh, height, tiling, o.displacement.unwrap_or(0.04).clamp(0.0, 0.5) * scene.radius, HQ_TRIANGLES)) - } - _ => None, - }; - + let displaced = scene.with_relief(&maps, relief, tiling, if o.hq { HQ_TRIANGLES } else { VIEW_TRIANGLES }); if o.hq { settings.supersample = 3; settings.ao_rays = 8; @@ -251,3 +265,7 @@ pub fn batch_reply(results: Vec, failed: Option<(usize, &str, String)>) - "failed": failed.map(|(index, id, error)| json!({ "index": index, "id": id, "error": error })), }) } + +#[cfg(test)] +#[path = "headless.test.rs"] +mod tests; diff --git a/crates/automation/src/headless.test.rs b/crates/automation/src/headless.test.rs new file mode 100644 index 00000000..4d9ee590 --- /dev/null +++ b/crates/automation/src/headless.test.rs @@ -0,0 +1,16 @@ +#[cfg(test)] +mod end_merge_tests { + use crate::headless::{Filesystem, Headless}; + use serde_json::json; + + #[test] + fn two_param_requests_are_two_undo_steps() { + let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal); + h.command_run("file.new", json!({"template": "empty"})).unwrap(); + let id = h.command_run("graph.node.add", json!({"def": "levels"})).unwrap()["id"].as_u64().unwrap(); + let sets = |h: &Headless| h.session.history().iter().filter(|l| *l == "Set parameter").count(); + h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": [0.3, 0.3, 0.3, 0.3]})).unwrap(); + h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": [0.4, 0.4, 0.4, 0.4]})).unwrap(); + assert_eq!(sets(&h), 2, "separate requests must not merge"); + } +} diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index ca3e96b3..dae2611d 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -23,6 +23,7 @@ pub const METHODS: &[&str] = &[ "package.save", "bitmap.import", "outputs.export", + "material.export", "render", ]; @@ -75,6 +76,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), @@ -261,6 +263,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 == "height")); + 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/material_craft_mcp.rs b/crates/automation/src/server/material_craft_mcp.rs index 383a7657..71cb233b 100644 --- a/crates/automation/src/server/material_craft_mcp.rs +++ b/crates/automation/src/server/material_craft_mcp.rs @@ -101,7 +101,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, @@ -223,6 +223,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 { @@ -264,7 +271,7 @@ impl MaterialCraftMcp { (usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \ (templates: empty, pbr, atomics) 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. Undo: command_run edit.undo." )] impl ServerHandler for MaterialCraftMcp {} @@ -286,6 +293,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/server/parameter/material_export_params.rs b/crates/automation/src/server/parameter/material_export_params.rs new file mode 100644 index 00000000..88f7ddbb --- /dev/null +++ b/crates/automation/src/server/parameter/material_export_params.rs @@ -0,0 +1,19 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[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, +} diff --git a/crates/automation/src/server/parameter/mod.rs b/crates/automation/src/server/parameter/mod.rs index 12aca9b2..f9d71284 100644 --- a/crates/automation/src/server/parameter/mod.rs +++ b/crates/automation/src/server/parameter/mod.rs @@ -31,3 +31,6 @@ pub use render_params::RenderParams; pub use run_params::RunParams; pub use save_params::SaveParams; pub use screenshot_params::ScreenshotParams; + +mod material_export_params; +pub use material_export_params::MaterialExportParams; diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index bd3917e1..89d6f226 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -64,7 +64,13 @@ impl AuthorizedWorkspace { Ok(()) } - /// Create a directory (and its parents) below the write root + /// Validate the write capability and relative path before cooking + 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)?; let root = self.write.as_ref().ok_or_else(|| denied("write"))?; diff --git a/crates/automation/tests/normal_maps.rs b/crates/automation/tests/normal_maps.rs new file mode 100644 index 00000000..aadac01f --- /dev/null +++ b/crates/automation/tests/normal_maps.rs @@ -0,0 +1,46 @@ +use materialcraft_automation::headless::{Filesystem, Headless, RenderOptions}; +use materialcraft_engine::{ + execute, + image::{Image, Kind}, + new_session, + nodes::atomic::height_to_normal, +}; +use materialcraft_render::{Lighting, Maps, Scene, Settings, render}; +use serde_json::json; + +#[test] +fn generated_normal_conventions_produce_the_same_surface_when_matched() { + let height = Image::gray(32, 32, |x, y| ((x as f32 * 0.15).sin() + (y as f32 * 0.25).sin()) * 0.25 + 0.5); + let gl = height_to_normal(&height, 8.0, false, false, false); + let dx = height_to_normal(&height, 8.0, true, false, false); + let normal_node = materialcraft_engine::nodes::find("normal").unwrap(); + assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(true)); + let maps = |normal| Maps { normal: Some(normal), base_color: Some(Image::filled(4, 4, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() }; + let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio")); + let settings = Settings::default(); + assert!(!settings.normal_y_flip); + let expected = render(&scene, &maps(gl), &light, &settings, 64, 48); + let flipped = maps(dx); + let matched = render(&scene, &flipped, &light, &Settings { normal_y_flip: true, ..settings }, 64, 48); + assert!(expected.iter().zip(&matched).all(|(a, b)| a.abs_diff(*b) <= 1)); + let wrong = render(&scene, &flipped, &light, &settings, 64, 48); + assert!(expected.iter().zip(&wrong).filter(|(a, b)| a.abs_diff(**b) > 2).count() > 20); +} + +#[test] +fn headless_render_honors_the_normal_y_command() { + let mut s = new_session(); + s.preview_size = Some(64); + let node = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap(); + execute(&mut s, "graph.node.add", &json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap(); + let mut h = Headless::new(s, Filesystem::Denied); + let options = RenderOptions { width: Some(64), height: Some(48), ..RenderOptions::default() }; + let gl = h.render_png(&options).unwrap().png; + execute(&mut h.session, "view.3d", &json!({"normalYFlip": true})).unwrap(); + let wrong = h.render_png(&options).unwrap().png; + assert_ne!(gl, wrong); + execute(&mut h.session, "graph.node.param", &json!({"id": node, "param": "color", "value": [0.5, 0.25, 1.0, 1.0]})).unwrap(); + assert_eq!(gl, h.render_png(&options).unwrap().png); + execute(&mut h.session, "view.3d.reset", &json!({})).unwrap(); + assert_eq!(wrong, h.render_png(&options).unwrap().png); +} diff --git a/crates/automation/tests/view_settings.rs b/crates/automation/tests/view_settings.rs new file mode 100644 index 00000000..404e7665 --- /dev/null +++ b/crates/automation/tests/view_settings.rs @@ -0,0 +1,16 @@ +use materialcraft_automation::headless::{Filesystem, Headless, RenderOptions}; +use materialcraft_engine::new_session; +use serde_json::json; + +#[test] +fn rejected_view_command_preserves_the_rendered_scene() { + let mut h = Headless::new(new_session(), Filesystem::Denied); + let options = RenderOptions { width: Some(64), height: Some(48), ..RenderOptions::default() }; + h.command_run("view.3d", json!({"scene": "sphere", "environment": "sunset"})).unwrap(); + let before = h.render_png(&options).unwrap().png; + assert!(h.command_run("view.3d", json!({"scene": "cube", "environment": "invalid"})).is_err()); + assert!(before == h.render_png(&options).unwrap().png, "rejected settings changed the rendered scene"); + // Confirm that valid settings still change the rendered output rather than returning a stale image. + h.command_run("view.3d", json!({"scene": "cube", "environment": "night"})).unwrap(); + assert_ne!(before, h.render_png(&options).unwrap().png); +} diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs index b54d43eb..2c659bc1 100644 --- a/crates/core/src/graph.rs +++ b/crates/core/src/graph.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; @@ -36,6 +36,8 @@ pub struct Graph { pub presets: Vec, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub input_images: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub input_images_linear: BTreeSet, #[serde(default)] pub attributes: Attributes, /// The id the next node, frame, comment or pin gets @@ -63,6 +65,7 @@ impl Graph { inputs: BTreeMap::new(), presets: Vec::new(), input_images: BTreeMap::new(), + input_images_linear: BTreeSet::new(), attributes: Attributes::default(), next_id: 1, } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 8c7089f1..08e9dd0a 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -164,3 +164,16 @@ pub(crate) fn point(p: &J, key: &str) -> Option<[f32; 2]> { let y = a.get(1)?.as_f64()? as f32; (x.is_finite() && y.is_finite()).then_some([x, y]) } + +/// Automation requests are separate undo steps unless the caller explicitly groups a gesture +pub fn execute_request(session: &mut Session, id: &str, params: &J) -> Result { + let merged = params.get("merge").and_then(J::as_bool) == Some(true); + if !merged { + session.finish_edit(); + } + let result = execute(session, id, params); + if !merged { + session.finish_edit(); + } + result +} diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 92cbdddb..e761fe45 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -217,9 +217,11 @@ fn delete_relink(s: &mut Session, p: &J) -> Result { let ids = ids_param(s, "edit.deleteRelink", p)?; s.edit("Delete and relink", |s| { - let g = s.graph_mut()?; for id in &ids { - let src = g.connections.iter().find(|c| c.to == *id).map(|c| (c.from, c.from_port.clone())); + // Port order comes from the node definition, not the order its wires were created. + let input = s.input_ports(*id).into_iter().next(); + let g = s.graph_mut()?; + let src = input.and_then(|port| g.input_of(*id, &port)).map(|c| (c.from, c.from_port.clone())); let outs: Vec<(NodeId, String)> = g.connections.iter().filter(|c| c.from == *id).map(|c| (c.to, c.to_port.clone())).collect(); g.remove_nodes(&[*id]); if let Some((from, port)) = src { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 6d99b63a..6164ea1b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -234,13 +234,18 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O let dec = s.resource_decoder(); let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache); let mut out = Vec::new(); + let mut names = std::collections::HashSet::new(); for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { let Some(img) = img else { continue }; + let file = format!("{}.{}", output_name(pattern, &g.name, &ident, usage), ext.trim_start_matches('.')); + if !names.insert(file.to_lowercase()) { + return Err(bad("file.export", format!("duplicate export filename `{file}`: use unique output identifiers or a different filename pattern"))); + } let node = g.node(id)?; let depth = depth .unwrap_or_else(|| Depth::from_format(if node.base.format == materialcraft_core::OutputFormat::Inherit { g.format } else { node.base.format })); let bytes = encode(img, ext, depth, materialcraft_formats::material::srgb_usage(usage))?; - out.push(Exported { file: format!("{}.{}", output_name(pattern, &g.name, &ident, usage), ext.trim_start_matches('.')), bytes }); + out.push(Exported { file, bytes }); } if out.is_empty() { return Err(bad("file.export", "the graph has no connected output nodes")); @@ -294,7 +299,7 @@ fn export(_: &mut Session, _: &J) -> Result { /// Embed image bytes as a resource; returns the resource name pub fn add_resource(s: &mut Session, file: &str, bytes: Vec, name: Option<&str>) -> Result { - materialcraft_formats::decode(&bytes)?; + materialcraft_formats::decode(&bytes, false)?; s.edit("Import bitmap", |s| Ok(push_resource(&mut s.pkg, file, bytes, name))) } diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 852fff2c..236329fb 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -110,6 +110,9 @@ fn delete(s: &mut Session, p: &J) -> Result { let i = graph_index(s, p)?; s.edit("Delete graph", |s| { s.pkg.graphs.remove(i); + if i < s.graph { + s.graph -= 1; + } s.material_preview.remove_graph(i); s.clear_preview_results(); s.clipboard = None; @@ -362,6 +365,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result { let src = s.graph()?.clone(); let mut sub = materialcraft_core::Graph::new(&name); sub.size = src.size; + sub.seed = src.seed; sub.next_id = src.next_id; sub.nodes = src.nodes.iter().filter(|n| ids.contains(&n.id)).cloned().collect(); sub.connections = src.connections.iter().filter(|c| ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect(); @@ -406,3 +410,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result { Ok(json!({"graph": name, "instance": inst.0})) }) } + +#[cfg(test)] +#[path = "graph_cmds.test.rs"] +mod tests; diff --git a/crates/engine/src/graph_cmds.test.rs b/crates/engine/src/graph_cmds.test.rs new file mode 100644 index 00000000..0d2a1ffd --- /dev/null +++ b/crates/engine/src/graph_cmds.test.rs @@ -0,0 +1,23 @@ +#[cfg(test)] +mod delete_tests { + use crate::{execute, sample_session}; + use serde_json::json; + + /// Deleting a graph that sits before the open one must not switch the user to another graph. + #[test] + fn deleting_an_earlier_graph_keeps_the_open_graph_open() { + let mut s = sample_session(); + let run = |s: &mut crate::Session, id: &str, p: serde_json::Value| execute(s, id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + run(&mut s, "file.new", json!({"template": "empty", "name": "Mine"})); + for _ in 0..3 { + run(&mut s, "graph.duplicate", json!({})); + } + let count = s.pkg.graphs.len(); + assert!(count >= 4, "need four graphs, got {count}"); + run(&mut s, "graph.open", json!({"graph": 2})); + let open_name = s.pkg.graphs[s.graph].name.clone(); + run(&mut s, "graph.delete", json!({"graph": 0})); + assert_eq!(s.pkg.graphs.len(), count - 1); + assert_eq!(s.pkg.graphs[s.graph].name, open_name, "the open graph changed"); + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 5658d5e4..b2c9814b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -21,6 +21,8 @@ pub fn session(s: &Session, graph: Option) -> J { "exposed": g.exposed, "presets": g.presets, "inputs": g.inputs, + "inputImages": g.input_images, + "inputImagesLinear": g.input_images_linear, "nodes": g.nodes.iter().map(|n| { let r = cooked.and_then(|c| c.nodes.get(&n.id)); let (ins, outs) = materialcraft_eval::ports(&s.pkg, g, n); diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index f19d8c15..922eeef2 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -44,7 +44,7 @@ pub(crate) fn specs() -> Vec { "Set input preview image", [], None, - "{identifier, resource? | path?} shows a bitmap resource (or an image file, embedded) on the graph's input node `identifier`, e.g. a mesh map baked in TextureCraft", + "{identifier, resource? | path?, linear?} shows a bitmap resource (or an image file, embedded) on the graph's input node `identifier`, e.g. a mesh map baked in TextureCraft", has_graph, bind ), @@ -146,17 +146,23 @@ fn graph_param(s: &Session, p: &J) -> Result { Ok(gi) } +#[cfg(not(target_arch = "wasm32"))] +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}")))?; - o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes)?); + o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes, false)?); } let bytes = material_bytes(s, gi, &o)?; materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?; @@ -212,14 +218,19 @@ fn bind(s: &mut Session, p: &J) -> Result { (None, Some(path)) => Some(read_image_file(CMD, path)?), (None, None) => return Err(bad(CMD, "give a `resource` or a `path`")), }; - s.edit("Set input preview image", |s| { let res = match file { Some((name, bytes)) => crate::file_cmds::push_resource(&mut s.pkg, &name, bytes, Some(&id)), None => strp(p, "resource").unwrap_or_default().to_string(), }; - - s.graph_mut()?.input_images.insert(id.clone(), res.clone()); + let linear = p.get("linear").and_then(J::as_bool).unwrap_or(false); + let g = s.graph_mut()?; + g.input_images.insert(id.clone(), res.clone()); + if linear { + g.input_images_linear.insert(id.clone()); + } else { + g.input_images_linear.remove(&id); + } Ok(json!({"identifier": id, "resource": res})) }) } @@ -227,7 +238,7 @@ fn bind(s: &mut Session, p: &J) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_image_file(cmd: &str, path: &str) -> Result<(String, Vec)> { let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - materialcraft_formats::decode(&bytes)?; + materialcraft_formats::decode(&bytes, false)?; let name = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("input.png").to_string(); Ok((name, bytes)) } @@ -239,7 +250,10 @@ fn read_image_file(cmd: &str, _: &str) -> Result<(String, Vec)> { fn unbind(s: &mut Session, p: &J) -> Result { let id = strp(p, "identifier").ok_or_else(|| bad("graph.input.unbind", "`identifier` is required"))?.to_string(); - s.edit("Clear input preview image", |s| Ok(J::Bool(s.graph_mut()?.input_images.remove(&id).is_some()))) + s.edit("Clear input preview image", |s| { + s.graph_mut()?.input_images_linear.remove(&id); + Ok(J::Bool(s.graph_mut()?.input_images.remove(&id).is_some())) + }) } #[cfg(test)] @@ -277,13 +291,18 @@ mod tests { let png = encode(&Image::filled(4, 4, materialcraft_image::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap(); let res = crate::file_cmds::add_resource(&mut s, "curv.png", png, None).unwrap(); assert!(crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "nope", "resource": res})).is_err()); - crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res})).unwrap(); + crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res, "linear": true})).unwrap(); assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res)); + let bytes = materialcraft_formats::sbs::write_sbs(&s.pkg).unwrap(); + let reopened = materialcraft_formats::sbs::read_sbs(&bytes, "input.sbs", &|_| None).unwrap().pkg; + assert_eq!(reopened.graphs[s.graph].input_images.get("curvature"), Some(&res)); + assert!(reopened.graphs[s.graph].input_images_linear.contains("curvature")); let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(16), ..Default::default() }).unwrap(); let (m, _) = read_material(&bytes).unwrap(); assert!(m.inputs.iter().any(|i| i.identifier == "curvature" && i.kind == "gray")); assert_eq!(crate::execute(&mut s, "graph.input.unbind", &json!({"identifier": "curvature"})).unwrap(), J::Bool(true)); assert!(s.graph().unwrap().input_images.is_empty()); + assert!(s.graph().unwrap().input_images_linear.is_empty()); } #[test] diff --git a/crates/engine/src/material_preview.rs b/crates/engine/src/material_preview.rs index ba56c6b7..e572cb83 100644 --- a/crates/engine/src/material_preview.rs +++ b/crates/engine/src/material_preview.rs @@ -80,13 +80,19 @@ impl Session { self.material_preview.sources(&self.pkg).into_iter().filter_map(|(channel, source)| Some((channel.id(), self.material_image(&source)?))).collect() } + /// A source's identity, selected port and cooked content + pub fn material_source_key(&self, source: &MaterialSource) -> u64 { + let result = self.preview_cooked(source.graph).and_then(|cooked| cooked.nodes.get(&source.node)); + let mut hash = std::collections::hash_map::DefaultHasher::new(); + (source, source.port_index(&self.pkg), result.map(|result| result.key)).hash(&mut hash); + hash.finish() + } + /// 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); + (channel, self.material_source_key(&source)).hash(&mut hash); } hash.finish() } diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs index 34efaa75..fbc2af9e 100644 --- a/crates/engine/src/node_cmds.rs +++ b/crates/engine/src/node_cmds.rs @@ -215,8 +215,14 @@ fn reset(s: &mut Session, p: &J) -> Result { match ¶m { Some(k) => { n.params.remove(k); + n.bindings.remove(k); + n.functions.remove(k); + } + None => { + n.params.retain(|k, _| k == "graph" || k == "identifier"); + n.bindings.clear(); + n.functions.clear(); } - None => n.params.retain(|k, _| k == "graph" || k == "identifier"), } Ok(J::Null) }) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 3e3d274d..0f40bb24 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -33,8 +33,10 @@ pub struct View3d { pub environment: String, pub env_rotation: f32, pub exposure: f32, - /// Parallax depth of the height output (0 = off). + /// Height relief in mesh radii pub height_scale: f32, + pub height_level: f32, + pub normal_y_flip: bool, pub show_axis: bool, pub show_grid: bool, /// See through the mesh where the material's alpha (opacity output, else base color alpha) @@ -56,7 +58,9 @@ impl Default for View3d { environment: "studio".into(), env_rotation: 0.0, exposure: 0.0, - height_scale: 0.012, + height_scale: 0.04, + height_level: 0.0, + normal_y_flip: false, show_axis: false, show_grid: false, transparency: true, @@ -141,6 +145,8 @@ pub struct Session { pub cooked: Cooked, /// Set when the graph changed and needs cooking. pub dirty: bool, + /// Synchronous cooks invalidate older worker results + pub cook_epoch: u64, /// Cooked node outputs, shared with background cooks. pub cache: Arc>, /// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry. @@ -149,7 +155,8 @@ pub struct Session { redo: Vec, /// Edits with the same key coalesce into one undo step (slider drags). merge_key: Option, - decoded: Arc>>, + group: Option<(Snapshot, bool)>, + decoded: Arc>>, } impl Session { @@ -174,11 +181,13 @@ impl Session { embedded_clipboard: None, cooked: Cooked::default(), dirty: true, + cook_epoch: 0, cache: Arc::new(Mutex::new(Cache::default())), custom_mesh: None, undo: Vec::new(), redo: Vec::new(), merge_key: None, + group: None, decoded: Arc::new(Mutex::new(HashMap::new())), } } @@ -200,6 +209,9 @@ impl Session { annotation_selection: self.annotation_selection, material_preview: self.material_preview.clone(), label: label.into(), + modified: self.modified, + dirty: self.dirty, + cook_epoch: self.cook_epoch, } } @@ -212,10 +224,16 @@ impl Session { /// Like [`Session::edit`], but consecutive edits with the same `key` (dragging one slider) /// make a single undo step. pub fn edit_merged(&mut self, key: &str, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if self.group.is_some() { + return self.edit_inner(label, f); + } if self.merge_key.as_deref() == Some(key) && !self.undo.is_empty() { + // Preserve the gesture snapshot while rolling back failed edits + let snap = self.snapshot(label); let r = f(self); - if r.is_ok() { - self.changed(); + match &r { + Ok(_) => self.changed(), + Err(_) => self.restore(snap), } return r; } @@ -231,23 +249,72 @@ impl Session { self.merge_key = None; } - fn edit_inner(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { - let snap = self.snapshot(label); - match f(self) { - Ok(v) => { - self.undo.push(snap); - if self.undo.len() > MAX_UNDO { - self.undo.remove(0); - } - self.redo.clear(); - self.changed(); - Ok(v) - } - Err(e) => { + pub fn begin_group(&mut self, label: &str) { + if self.group.is_none() { + self.merge_key = None; + self.group = Some((self.snapshot(label), false)); + } + } + + pub fn end_group(&mut self) { + if let Some((snap, edited)) = self.group.take() + && edited + { + self.record_undo(snap); + } + } + + pub fn group(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if self.group.is_some() { + let snap = self.snapshot(label); + let edited = self.group.as_ref().is_some_and(|(_, edited)| *edited); + let result = f(self); + if result.is_err() { self.restore(snap); - Err(e) + if let Some((_, flag)) = self.group.as_mut() { + *flag = edited; + } + } + return result; + } + self.begin_group(label); + let r = f(self); + match r { + Ok(_) => self.end_group(), + Err(_) => { + if let Some((snap, _)) = self.group.take() { + self.restore(snap); + } } } + r + } + + fn edit_inner(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + let snapshot = self.snapshot(label); + match f(self) { + Ok(value) => { + if let Some((_, edited)) = self.group.as_mut() { + *edited = true; + } else { + self.record_undo(snapshot); + } + self.changed(); + Ok(value) + } + Err(error) => { + self.restore(snapshot); + Err(error) + } + } + } + + fn record_undo(&mut self, snapshot: Snapshot) { + self.undo.push(snapshot); + if self.undo.len() > MAX_UNDO { + self.undo.remove(0); + } + self.redo.clear(); } fn restore(&mut self, s: Snapshot) { @@ -256,7 +323,11 @@ impl Session { self.selection = s.selection; self.annotation_selection = s.annotation_selection; self.material_preview = s.material_preview; - self.clear_preview_results(); + self.modified = s.modified; + self.dirty = s.dirty || self.cook_epoch != s.cook_epoch; + if self.cook_epoch != s.cook_epoch { + self.clear_preview_results(); + } } /// Mark the document modified and in need of a cook. @@ -279,6 +350,7 @@ impl Session { } pub fn undo(&mut self) -> Option { + self.end_group(); let s = self.undo.pop()?; let label = s.label.clone(); let cur = self.snapshot(&label); @@ -290,6 +362,7 @@ impl Session { } pub fn redo(&mut self) -> Option { + self.end_group(); let s = self.redo.pop()?; let label = s.label.clone(); let cur = self.snapshot(&label); @@ -305,21 +378,23 @@ impl Session { self.undo.clear(); self.redo.clear(); self.merge_key = None; + self.group = None; } /// 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, 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| { + // Release decoded images of deleted or replaced resources + memo.lock().unwrap_or_else(PoisonError::into_inner).retain(|(k, _), _| res.iter().any(|(_, b)| b.content_hash() == *k)); + move |requested: &str| { + let (name, linear) = materialcraft_image::split_resource_key(requested); let (_, bytes) = res.iter().find(|(n, _)| n == name)?; - let key = bytes.content_hash(); + let key = (bytes.content_hash(), linear); if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { return Some(i.clone()); } - let img = materialcraft_formats::decode(bytes.as_slice()).ok()?; + let img = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?; memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); Some(img) } @@ -338,6 +413,7 @@ impl Session { let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache); self.accept_preview(cooked); self.dirty = false; + self.cook_epoch = self.cook_epoch.wrapping_add(1); &self.cooked } @@ -420,3 +496,7 @@ impl Session { } } } + +#[cfg(test)] +#[path = "session.test.rs"] +mod tests; diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs new file mode 100644 index 00000000..35bf56b4 --- /dev/null +++ b/crates/engine/src/session.test.rs @@ -0,0 +1,230 @@ +#[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}; + +use crate::session::Session; + +fn normal_map_session() -> Session { + let mut pkg = Package::new("T"); + let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap(); + pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: materialcraft_core::ResourceBytes::new(png) }); + Session::new(pkg) +} + +#[test] +fn the_resource_decoder_reads_data_maps_as_stored() { + let s = normal_map_session(); + let dec = s.resource_decoder(); + let color = dec(&resource_key("n", false)).unwrap(); + let data = dec(&resource_key("n", true)).unwrap(); + // 8-bit color is sRGB-decoded (0.5 -> ~0.214); a data map keeps 0.5. + assert!((color.get(0, 0, false)[0] - 0.214).abs() < 0.01); + assert!((data.get(0, 0, false)[0] - 0.5).abs() < 0.01); + assert!((data.get(0, 0, false)[2] - 1.0).abs() < 0.01); +} + +#[cfg(test)] +mod merge_tests { + use crate::{EngineError, Session}; + + fn session() -> Session { + crate::sample_session() + } + + fn set(s: &mut Session, key: &str) { + s.edit_merged(key, "Set parameter", |s| { + s.modified = true; + Ok(()) + }) + .unwrap(); + } + + #[test] + fn same_key_merges_until_finish_edit() { + let mut s = session(); + let base = s.history().len(); + set(&mut s, "k"); + set(&mut s, "k"); + assert_eq!(s.history().len(), base + 1, "one drag is one entry"); + s.finish_edit(); + 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] +fn failed_merged_edits_restore_clean_flags_and_history() { + let mut s = crate::sample_session(); + s.edit_merged("k", "Set", |_| Ok(())).unwrap(); + s.modified = false; + s.dirty = false; + let name = s.pkg.name.clone(); + let history = s.history(); + let result: crate::Result<()> = s.edit_merged("k", "Set", |s| { + s.pkg.name = "partial".into(); + s.changed(); + Err(crate::EngineError::Other("failed".into())) + }); + assert!(result.is_err()); + assert_eq!(s.pkg.name, name); + assert_eq!(s.history(), history); + assert!(!s.modified && !s.dirty); +} + +#[cfg(test)] +mod group_tests { + use crate::{EngineError, Session, execute}; + use serde_json::json; + + fn two_nodes() -> (Session, u64, u64) { + let mut s = crate::sample_session(); + execute(&mut s, "file.new", &json!({"template": "empty"})).unwrap(); + let a = execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap(); + let b = execute(&mut s, "graph.node.add", &json!({"def": "levels"})).unwrap()["id"].as_u64().unwrap(); + (s, a, b) + } + + #[test] + fn a_group_is_one_undo_entry_and_one_undo_reverts_all() { + let (mut s, a, b) = two_nodes(); + let base = s.history().len(); + s.group("Rewire", |s| { + execute(s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"}))?; + execute(s, "graph.disconnect", &json!({"to": b, "toPort": "input"}))?; + execute(s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"}))?; + Ok(()) + }) + .unwrap(); + assert_eq!(s.history().len(), base + 1); + assert_eq!(s.history().last().map(String::as_str), Some("Rewire")); + assert_eq!(s.undo().as_deref(), Some("Rewire")); + assert!(s.graph().unwrap().connections.is_empty(), "the single undo removed every step"); + } + + #[test] + fn a_failing_group_restores_everything_and_records_nothing() { + let (mut s, a, b) = two_nodes(); + let base = s.history().len(); + let r: Result<(), EngineError> = s.group("Rewire", |s| { + execute(s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"}))?; + Err(EngineError::Other("boom".into())) + }); + assert!(r.is_err()); + assert_eq!(s.history().len(), base); + assert!(s.graph().unwrap().connections.is_empty()); + } + + #[test] + fn begin_and_end_group_span_several_calls_and_an_untouched_group_records_nothing() { + let (mut s, a, b) = two_nodes(); + let base = s.history().len(); + s.begin_group("Nothing"); + s.end_group(); + assert_eq!(s.history().len(), base); + s.begin_group("Both"); + execute(&mut s, "graph.connect", &json!({"from": a, "to": b, "toPort": "input"})).unwrap(); + execute(&mut s, "graph.node.param", &json!({"id": b, "param": "in_low", "value": [0.2, 0.2, 0.2, 0.2]})).unwrap(); + s.end_group(); + assert_eq!(s.history().len(), base + 1); + } +} + +#[test] +fn a_group_with_only_failed_edits_preserves_redo_and_clean_flags() { + let mut s = crate::sample_session(); + s.edit("Prior", |s| { + s.pkg.name = "Prior".into(); + Ok(()) + }) + .unwrap(); + s.undo(); + assert!(s.can_redo()); + s.modified = false; + s.dirty = false; + let history = s.history(); + let name = s.pkg.name.clone(); + s.begin_group("Rejected"); + let result: crate::Result<()> = s.edit("Bad", |s| { + s.pkg.name = "Partial".into(); + Err(crate::EngineError::Other("failed".into())) + }); + assert!(result.is_err()); + s.end_group(); + assert_eq!(s.pkg.name, name); + assert_eq!(s.history(), history); + assert!(s.can_redo()); + assert!(!s.modified && !s.dirty); +} + +#[test] +fn a_caught_nested_group_error_rolls_back_only_its_own_edits() { + let mut s = crate::sample_session(); + let original = s.pkg.name.clone(); + let count = s.history().len(); + s.group("Outer", |s| { + s.edit("Outer edit", |s| { + s.pkg.name = "Outer".into(); + Ok(()) + })?; + let result: crate::Result<()> = s.group("Inner", |s| { + s.edit("Inner edit", |s| { + s.pkg.name = "Partial inner".into(); + Ok(()) + })?; + Err(crate::EngineError::Other("failed".into())) + }); + assert!(result.is_err()); + assert_eq!(s.pkg.name, "Outer"); + Ok(()) + }) + .unwrap(); + assert_eq!(s.history().len(), count + 1); + s.undo(); + assert_eq!(s.pkg.name, original); +} + +#[test] +fn a_failed_group_recooks_if_it_cooked_a_temporary_document() { + use crate::{core::NodeId, execute}; + use serde_json::json; + let mut s = crate::new_session(); + s.preview_size = Some(16); + let id = NodeId(execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap()); + execute(&mut s, "graph.node.param", &json!({"id": id.0, "param": "color_mode", "value": true})).unwrap(); + let before = s.cook().image(id, 0).unwrap().data.clone(); + let result: crate::Result<()> = s.group("Temporary", |s| { + execute(s, "graph.node.param", &json!({"id": id.0, "param": "color", "value": [0.1, 0.8, 0.2, 1.0]}))?; + s.cook(); + Err(crate::EngineError::Other("failed".into())) + }); + assert!(result.is_err()); + s.cook_if_dirty(); + assert_eq!(s.cooked.image(id, 0).unwrap().data, before); +} diff --git a/crates/engine/src/snapshot.rs b/crates/engine/src/snapshot.rs index b09078cf..4fe9829d 100644 --- a/crates/engine/src/snapshot.rs +++ b/crates/engine/src/snapshot.rs @@ -9,4 +9,7 @@ pub(crate) struct Snapshot { pub(crate) annotation_selection: Option, pub(crate) material_preview: crate::MaterialPreview, pub(crate) label: String, + pub(crate) modified: bool, + pub(crate) dirty: bool, + pub(crate) cook_epoch: u64, } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 5b3299e3..274a88fb 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec { "3D view settings", [], None, - "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", + "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", always, view3d ), @@ -61,6 +61,11 @@ pub(crate) fn specs() -> Vec { } fn view2d(s: &mut Session, p: &J) -> Result { + // Validate the channel before applying any part of the request. + let channel = strp(p, "channel"); + if channel.is_some_and(|c| !["rgba", "r", "g", "b", "a"].contains(&c)) { + return Err(bad("view.2d", "`channel` is rgba, r, g, b or a")); + } if let Some(n) = u64p(p, "node") { s.graph()?.node(NodeId(n)).map_err(|_| bad("view.2d", format!("no node {n}")))?; s.view2d.node = Some(NodeId(n)); @@ -75,10 +80,7 @@ fn view2d(s: &mut Session, p: &J) -> Result { if let Some(h) = boolp(p, "histogram") { s.view2d.histogram = h; } - if let Some(c) = strp(p, "channel") { - if !["rgba", "r", "g", "b", "a"].contains(&c) { - return Err(bad("view.2d", "`channel` is rgba, r, g, b or a")); - } + if let Some(c) = channel { s.view2d.channel = c.into(); } Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null)) @@ -97,6 +99,13 @@ fn view3d(s: &mut Session, p: &J) -> Result { } } }; + // A rejected environment must not leave a new scene applied. + let environment = strp(p, "environment"); + if let Some(e) = environment + && !ENVIRONMENTS.iter().any(|(id, _)| *id == e) + { + return Err(bad("view.3d", format!("unknown environment `{e}`"))); + } if let Some(sc) = strp(p, "scene") { if sc == "custom" && s.custom_mesh.is_none() { return Err(bad("view.3d", "no mesh is loaded: use view.3d.loadMesh")); @@ -108,10 +117,7 @@ fn view3d(s: &mut Session, p: &J) -> Result { v.scene = sc.into(); } let v = &mut s.view3d; - if let Some(e) = strp(p, "environment") { - if !ENVIRONMENTS.iter().any(|(id, _)| *id == e) { - return Err(bad("view.3d", format!("unknown environment `{e}`"))); - } + if let Some(e) = environment { v.environment = e.into(); } if let Some(t) = f32p(p, "tiling") { @@ -138,6 +144,12 @@ fn view3d(s: &mut Session, p: &J) -> Result { if let Some(t) = f32p(p, "heightScale") { v.height_scale = t.clamp(0.0, 0.5); } + if let Some(t) = f32p(p, "heightLevel") { + v.height_level = t.clamp(0.0, 1.0); + } + if let Some(flip) = boolp(p, "normalYFlip") { + v.normal_y_flip = flip; + } if let Some(b) = boolp(p, "axis") { v.show_axis = b; } diff --git a/crates/engine/tests/delete_relink.rs b/crates/engine/tests/delete_relink.rs new file mode 100644 index 00000000..a15ed206 --- /dev/null +++ b/crates/engine/tests/delete_relink.rs @@ -0,0 +1,77 @@ +use materialcraft_engine::{Session, core::NodeId, execute, new_session}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + execute(s, id, &p).unwrap() +} + +fn node(s: &mut Session, def: &str) -> u64 { + run(s, "graph.node.add", json!({"def": def}))["id"].as_u64().unwrap() +} + +fn connect(s: &mut Session, from: u64, to: u64, port: &str) { + run(s, "graph.connect", json!({"from": from, "to": to, "toPort": port})); +} + +#[test] +fn relink_uses_the_first_declared_input_regardless_of_wire_creation_order() { + for background_first in [true, false] { + let mut s = new_session(); + s.preview_size = Some(32); + let foreground = node(&mut s, "uniform"); + let background = node(&mut s, "uniform"); + run(&mut s, "graph.node.param", json!({"id": foreground, "param": "color", "value": [0.8, 0.4, 0.2, 1.0]})); + run(&mut s, "graph.node.param", json!({"id": background, "param": "color", "value": [0.1, 0.2, 0.3, 1.0]})); + let blend = node(&mut s, "blend"); + let output = node(&mut s, "output"); + let wires = [(foreground, "foreground"), (background, "background")]; + for index in if background_first { [1, 0] } else { [0, 1] } { + connect(&mut s, wires[index].0, blend, wires[index].1); + } + connect(&mut s, blend, output, "input"); + run(&mut s, "graph.select", json!({"ids": [blend]})); + let before = s.pkg.graphs.clone(); + let history = s.history().len(); + run(&mut s, "edit.deleteRelink", json!({})); + assert_eq!(s.graph().unwrap().input_of(NodeId(output), "input").unwrap().from, NodeId(foreground)); + assert_eq!(s.history().len(), history + 1); + assert!(s.selection.is_empty()); + let cooked = s.cook(); + assert_eq!(cooked.image(NodeId(output), 0).unwrap().get(0, 0, false), [0.8, 0.4, 0.2, 1.0]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.pkg.graphs, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.graph().unwrap().input_of(NodeId(output), "input").unwrap().from, NodeId(foreground)); + } +} + +#[test] +fn relink_does_not_substitute_a_secondary_input_when_the_first_is_unconnected() { + let mut s = new_session(); + let background = node(&mut s, "uniform"); + let blend = node(&mut s, "blend"); + let output = node(&mut s, "output"); + connect(&mut s, background, blend, "background"); + connect(&mut s, blend, output, "input"); + run(&mut s, "graph.select", json!({"ids": [blend]})); + run(&mut s, "edit.deleteRelink", json!({})); + assert!(s.graph().unwrap().input_of(NodeId(output), "input").is_none()); +} + +#[test] +fn relink_preserves_multi_node_chain_connections_in_either_selection_order() { + for reverse in [false, true] { + let mut s = new_session(); + let source = node(&mut s, "uniform"); + let a = node(&mut s, "levels"); + let b = node(&mut s, "blur"); + let output = node(&mut s, "output"); + connect(&mut s, source, a, "input"); + connect(&mut s, a, b, "input"); + connect(&mut s, b, output, "input"); + let ids = if reverse { vec![b, a] } else { vec![a, b] }; + run(&mut s, "graph.select", json!({"ids": ids})); + run(&mut s, "edit.deleteRelink", json!({})); + assert_eq!(s.graph().unwrap().input_of(NodeId(output), "input").unwrap().from, NodeId(source)); + } +} diff --git a/crates/engine/tests/export_names.rs b/crates/engine/tests/export_names.rs new file mode 100644 index 00000000..df71446d --- /dev/null +++ b/crates/engine/tests/export_names.rs @@ -0,0 +1,93 @@ +use materialcraft_engine::{Session, core::NodeId, execute, file_cmds::export_outputs, formats, new_session}; +use serde_json::json; + +fn session() -> (Session, Vec) { + let mut s = new_session(); + execute(&mut s, "graph.size", &json!({"width": 16})).unwrap(); + let mut outputs = Vec::new(); + for (name, value) in [("first", 0.2), ("second", 0.8)] { + let source = + execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color": [value, value, value, 1.0]}})).unwrap()["id"].as_u64().unwrap(); + let output = + execute(&mut s, "graph.node.add", &json!({"def": "output", "params": {"identifier": name}, "connectFrom": {"node": source}})).unwrap()["id"] + .as_u64() + .unwrap(); + outputs.push(output); + } + (s, outputs) +} + +#[test] +fn export_rejects_duplicate_final_names_from_patterns_identifiers_and_sanitization() { + for (identifiers, pattern) in [ + (["first", "second"], "same"), + (["first", "second"], "$(usage)"), + (["same", "same"], "$(identifier)"), + (["Map", "map"], "$(identifier)"), + (["map?", "map*"], "$(identifier)"), + (["a/map", "b/map"], "$(identifier)"), + ] { + let (mut s, outputs) = session(); + for (&id, name) in outputs.iter().zip(identifiers) { + execute(&mut s, "graph.node.param", &json!({"id": id, "param": "identifier", "value": name})).unwrap(); + } + let result = export_outputs(&s, 0, "png", pattern, None, None); + assert!(result.is_err(), "colliding names were accepted: {identifiers:?}, {pattern}"); + let error = result.err().unwrap().to_string(); + assert!(error.contains("filename") && error.contains("identifier"), "{error}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct TempDir(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl TempDir { + fn new(name: &str) -> Self { + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("mc-export-{name}-{}-{nonce}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn colliding_export_preserves_existing_files_and_writes_no_partial_outputs() { + let (mut s, outputs) = session(); + let source = s.graph().unwrap().input_of(NodeId(outputs[0]), "input").unwrap().from; + // The third output collides only after the first two have distinct names. + execute(&mut s, "graph.node.add", &json!({"def": "output", "params": {"identifier": "first"}, "connectFrom": {"node": source.0}})).unwrap(); + let dir = TempDir::new("collision"); + let sentinel = b"existing file must survive a rejected export"; + std::fs::write(dir.0.join("first.png"), sentinel).unwrap(); + let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})); + let existing = std::fs::read(dir.0.join("first.png")).unwrap(); + let files = std::fs::read_dir(&dir.0).unwrap().count(); + assert!( + result.is_err() && existing == sentinel && files == 1, + "colliding export modified files: response={result:?}, files={files}, sentinel preserved={}", + existing == sentinel + ); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn unique_export_writes_both_maps_with_their_expected_pixels() { + let (mut s, _) = session(); + let dir = TempDir::new("unique"); + let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 2); + for (name, value) in [("first.png", 0.2), ("second.png", 0.8)] { + let image = formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), false).unwrap(); + assert_eq!((image.w, image.h), (16, 16)); + assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}"); + } +} diff --git a/crates/engine/tests/function_math.rs b/crates/engine/tests/function_math.rs new file mode 100644 index 00000000..bde70b1a --- /dev/null +++ b/crates/engine/tests/function_math.rs @@ -0,0 +1,60 @@ +use materialcraft_engine::core::{FunctionGraph, Value}; +use materialcraft_engine::{Session, execute, formats::sbs, new_session}; +use serde_json::json; + +fn math_function() -> FunctionGraph { + let mut graph = FunctionGraph::default(); + let power = graph.add("get_float1", &[], Some(Value::Text("power".into()))); + let radius = graph.add("pow2", &[power], None); + let two = graph.add_constant(Value::Float(2.0)); + let angle = graph.add("log2", &[two], None); + let position = graph.add("cartesian", &[radius, angle], None); + let tail = graph.add_constant(Value::Float2([0.0, 1.0])); + graph.output = Some(graph.add("vector4", &[position, tail], None)); + graph +} + +fn assert_outputs(session: &mut Session, radius: f32) { + session.cook(); + for node in &session.graph().unwrap().nodes { + let result = &session.cooked.nodes[&node.id]; + assert!(result.error.is_none(), "{:?}", result.error); + let color = if node.def == "value_processor" { + let Some(Value::Float4(value)) = session.cooked.value(node.id, 0) else { panic!("expected typed Float4 output") }; + *value + } else { + session.cooked.image(node.id, 0).unwrap().mean() + }; + assert!((color[0] - radius * 1.0f32.cos()).abs() < 1e-5, "{color:?}"); + assert!((color[1] - radius * 1.0f32.sin()).abs() < 1e-5, "{color:?}"); + assert!(color[2].abs() < 1e-5 && (color[3] - 1.0).abs() < 1e-5); + } +} + +#[test] +fn math_primitives_cook_in_processors_and_parameter_functions_and_round_trip() { + let mut session = new_session(); + session.preview_size = Some(32); + execute(&mut session, "graph.exposed.add", &json!({"id": "power", "default": {"t": "float", "v": -2.0}})).unwrap(); + let function = math_function(); + for definition in ["value_processor", "pixel_processor", "uniform"] { + let id = execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap(); + if definition == "uniform" { + execute(&mut session, "graph.node.function", &json!({"id": id, "param": "color", "function": function})).unwrap(); + } else { + execute(&mut session, "graph.node.param", &json!({"id": id, "param": "function", "value": Value::Function(Box::new(function.clone()))})).unwrap(); + } + } + assert_outputs(&mut session, 0.25); + execute(&mut session, "graph.exposed.set", &json!({"id": "power", "value": -1.0})).unwrap(); + assert_outputs(&mut session, 0.5); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_outputs(&mut session, 0.25); + execute(&mut session, "edit.redo", &json!({})).unwrap(); + assert_outputs(&mut session, 0.5); + let report = sbs::read_sbs(&sbs::write_sbs(&session.pkg).unwrap(), "math.sbs", &|_| None).unwrap(); + assert!(report.warnings.is_empty(), "{:?}", report.warnings); + let mut reopened = Session::new(report.pkg); + reopened.preview_size = Some(32); + assert_outputs(&mut reopened, 0.5); +} diff --git a/crates/engine/tests/normal_maps.rs b/crates/engine/tests/normal_maps.rs new file mode 100644 index 00000000..42ada40c --- /dev/null +++ b/crates/engine/tests/normal_maps.rs @@ -0,0 +1,17 @@ +use materialcraft_engine::{View3d, execute, new_session}; +use serde_json::json; + +#[test] +fn normal_map_convention_is_inspectable_and_resets_to_opengl() { + let mut s = new_session(); + assert!(!s.view3d.normal_y_flip); + assert_eq!(materialcraft_engine::nodes::find("normal").unwrap().param("opengl").unwrap().default.as_bool(), Some(true)); + execute(&mut s, "view.3d", &json!({"normalYFlip": true})).unwrap(); + let inspection = execute(&mut s, "session.inspect", &json!({})).unwrap(); + assert_eq!(inspection["view3d"]["normalYFlip"], true); + let saved = serde_json::to_value(&s.view3d).unwrap(); + assert!(serde_json::from_value::(saved).unwrap().normal_y_flip); + assert!(!serde_json::from_value::(json!({"scene": "sphere"})).unwrap().normal_y_flip); + execute(&mut s, "view.3d.reset", &json!({})).unwrap(); + assert!(!s.view3d.normal_y_flip); +} diff --git a/crates/engine/tests/reset_drivers.rs b/crates/engine/tests/reset_drivers.rs new file mode 100644 index 00000000..8aaa9354 --- /dev/null +++ b/crates/engine/tests/reset_drivers.rs @@ -0,0 +1,88 @@ +use materialcraft_engine::{ + Session, + core::{FunctionGraph, NodeId, Value}, + execute, formats, new_session, +}; +use serde_json::{Value as Json, json}; + +fn run(s: &mut Session, id: &str, params: Json) -> Json { + execute(s, id, ¶ms).unwrap() +} + +fn setup() -> (Session, NodeId) { + let mut s = new_session(); + s.preview_size = Some(32); + let source = run(&mut s, "graph.node.add", json!({"def": "uniform"}))["id"].as_u64().unwrap(); + let levels = NodeId(run(&mut s, "graph.node.add", json!({"def": "levels", "connectFrom": {"node": source}}))["id"].as_u64().unwrap()); + (s, levels) +} + +fn drive(s: &mut Session, id: NodeId, param: &str, value: f32, function: bool) { + if function { + run(s, "graph.node.function", json!({"id": id.0, "param": param, "function": FunctionGraph::constant(Value::Float4([value; 4]))})); + } else { + run(s, "graph.exposed.add", json!({"id": param, "default": Value::Float4([value; 4]), "bind": {"node": id.0, "param": param}})); + } +} + +fn pixel(s: &mut Session, id: NodeId) -> f32 { + let cooked = s.cook(); + assert!(cooked.nodes[&id].error.is_none()); + cooked.image(id, 0).unwrap().get_gray(0, 0, false) +} + +fn check_single_reset(function: bool) { + let (mut s, id) = setup(); + drive(&mut s, id, "in_low", 0.4, function); + drive(&mut s, id, "out_high", 0.8, !function); + let before = s.pkg.graphs.clone(); + let driven = pixel(&mut s, id); + assert!(driven < 0.2); + run(&mut s, "graph.node.reset", json!({"id": id.0, "param": "in_low"})); + assert!((pixel(&mut s, id) - 0.4).abs() < 1e-5, "reset left the in_low driver active (function={function})"); + let n = s.graph().unwrap().node(id).unwrap(); + assert!(!n.bindings.contains_key("in_low") && !n.functions.contains_key("in_low")); + assert!(n.bindings.contains_key("out_high") || n.functions.contains_key("out_high")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.pkg.graphs, before); + assert!((pixel(&mut s, id) - driven).abs() < 1e-5); + run(&mut s, "edit.redo", json!({})); + assert!((pixel(&mut s, id) - 0.4).abs() < 1e-5); +} + +#[test] +fn resetting_one_bound_parameter_preserves_other_drivers() { + check_single_reset(false); +} + +#[test] +fn resetting_one_function_parameter_preserves_other_drivers() { + check_single_reset(true); +} + +#[test] +fn resetting_all_parameters_removes_drivers_and_restores_default_output() { + let (mut s, id) = setup(); + drive(&mut s, id, "in_low", 0.4, false); + drive(&mut s, id, "out_high", 0.8, true); + run(&mut s, "graph.node.param", json!({"id": id.0, "param": "out_low", "value": [0.1, 0.1, 0.1, 0.1]})); + let before = s.pkg.graphs.clone(); + let driven = pixel(&mut s, id); + assert!((driven - 0.5).abs() > 0.1); + let history = s.history().len(); + run(&mut s, "graph.node.reset", json!({"id": id.0})); + assert!((pixel(&mut s, id) - 0.5).abs() < 1e-5, "reset left dynamic parameters active"); + let n = s.graph().unwrap().node(id).unwrap(); + assert!(n.params.is_empty() && n.bindings.is_empty() && n.functions.is_empty()); + assert_eq!(s.history().len(), history + 1); + assert_eq!(s.graph().unwrap().exposed, before[0].exposed); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.pkg.graphs, before); + assert!((pixel(&mut s, id) - driven).abs() < 1e-5); + run(&mut s, "edit.redo", json!({})); + assert!((pixel(&mut s, id) - 0.5).abs() < 1e-5); + let mut reopened = Session::new(formats::sbs::read_sbs(&formats::sbs::write_sbs(&s.pkg).unwrap(), "test.sbs", &|_| None).unwrap().pkg); + reopened.preview_size = Some(32); + let reopened_id = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "levels").unwrap().id; + assert!((pixel(&mut reopened, reopened_id) - 0.5).abs() < 1e-5); +} diff --git a/crates/engine/tests/sbs_functions.rs b/crates/engine/tests/sbs_functions.rs new file mode 100644 index 00000000..7aa0003b --- /dev/null +++ b/crates/engine/tests/sbs_functions.rs @@ -0,0 +1,50 @@ +//! Imported numeric parameter expressions must affect real cooks and follow exposed inputs. +use materialcraft_engine::{execute, formats::sbs, new_session}; +use serde_json::json; + +#[test] +fn imported_expression_cooks_follows_inputs_and_survives_undo_and_save() { + // Original structural XML: in_low = amount - 0.25, with no embedded native package. + let xml = r#" + + + + + + + + + + + + + + + "#; + let imported = sbs::read_sbs(xml.as_bytes(), "math.sbs", &|_| None).unwrap(); + assert!(imported.warnings.is_empty(), "{:?}", imported.warnings); + let mut s = new_session(); + s.preview_size = Some(64); + s.pkg = imported.pkg; + let levels = s.graph().unwrap().nodes[0].id; + let uniform = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": false}})).unwrap()["id"].as_u64().unwrap(); + execute(&mut s, "graph.connect", &json!({"from": uniform, "to": levels.0})).unwrap(); + let mean = |s: &mut materialcraft_engine::Session| { + let levels = s.graph().unwrap().nodes.iter().find(|node| node.def == "levels").unwrap().id; + s.cook(); + assert!(s.cooked.nodes[&levels].error.is_none()); + s.cooked.image(levels, 0).unwrap().mean()[0] + }; + assert!(mean(&mut s).abs() < 1e-5); + execute(&mut s, "graph.exposed.set", &json!({"id": "amount", "value": 0.5})).unwrap(); + assert!((mean(&mut s) - 1.0 / 3.0).abs() < 1e-5); + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert!(mean(&mut s).abs() < 1e-5); + execute(&mut s, "edit.redo", &json!({})).unwrap(); + assert!((mean(&mut s) - 1.0 / 3.0).abs() < 1e-5); + let saved = sbs::write_sbs(&s.pkg).unwrap(); + s.pkg = sbs::read_sbs(&saved, "saved.sbs", &|_| None).unwrap().pkg; + s.cache.lock().unwrap().clear(); + assert!((mean(&mut s) - 1.0 / 3.0).abs() < 1e-5); + assert!(s.graph().unwrap().nodes.iter().find(|node| node.def == "levels").unwrap().functions.contains_key("in_low")); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 3991d1f3..3f2a6de1 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -86,7 +86,7 @@ fn package_save_and_open_round_trip() { let small = dir.join("small"); run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64})); let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path(); - let img = materialcraft_formats::decode(&std::fs::read(file).unwrap()).unwrap(); + let img = materialcraft_formats::decode(&std::fs::read(file).unwrap(), false).unwrap(); assert_eq!((img.w, img.h), (64, 64)); let _ = std::fs::remove_dir_all(&dir); } @@ -99,7 +99,7 @@ fn export_size_keeps_proportions_and_clamps() { let dims = |s: &Session, size: Value| { let (gi, ext, pattern, depth, size) = materialcraft_engine::file_cmds::export_params(s, &json!({"size": size})).unwrap(); let files = materialcraft_engine::file_cmds::export_outputs(s, gi, &ext, &pattern, depth, size).unwrap(); - files.iter().map(|f| materialcraft_formats::decode(&f.bytes).unwrap()).map(|i| (i.w, i.h)).collect::>() + files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.w, i.h)).collect::>() }; for size in [json!(0), json!(null)] { @@ -317,6 +317,24 @@ fn view3d_target_is_validated_clamped_and_reset() { assert_eq!(s.view3d.target, [0.0; 3]); } +/// The height output rises out of the mesh by default; depth and level are clamped and reset with the scene. +#[test] +fn view3d_height_depth_and_level_are_clamped_and_reset() { + let mut s = sample_session(); + assert_eq!(s.view3d.height_level, 0.0, "the relief rises out of the surface by default"); + assert!(s.view3d.height_scale > 0.0); + + let view = run(&mut s, "view.3d", json!({"heightScale": 0.1, "heightLevel": 0.5})); + assert_eq!((view["heightScale"].as_f64(), view["heightLevel"].as_f64()), (Some(0.1f32 as f64), Some(0.5))); + run(&mut s, "view.3d", json!({"heightScale": 9.0, "heightLevel": -3.0})); + assert_eq!((s.view3d.height_scale, s.view3d.height_level), (0.5, 0.0)); + run(&mut s, "view.3d", json!({"heightLevel": 7.0})); + assert_eq!(s.view3d.height_level, 1.0); + + run(&mut s, "view.3d.reset", json!({})); + assert_eq!(s.view3d.height_level, 0.0); +} + #[test] fn camera_prefs_bound_the_pan_and_survive_hostile_values() { use materialcraft_engine::CameraPrefs; diff --git a/crates/engine/tests/subgraph_seed.rs b/crates/engine/tests/subgraph_seed.rs new file mode 100644 index 00000000..070f5fcc --- /dev/null +++ b/crates/engine/tests/subgraph_seed.rs @@ -0,0 +1,45 @@ +use materialcraft_engine::{Session, core::NodeId, execute, formats, new_session}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, params: Value) -> Value { + execute(s, id, ¶ms).unwrap() +} + +#[test] +fn grouping_noise_preserves_pixels_seed_and_undo() { + for seed in [0, 42, 12345] { + let mut s = new_session(); + s.preview_size = None; + run(&mut s, "graph.size", json!({"width": 64, "height": 32})); + run(&mut s, "graph.seed", json!({"seed": seed})); + let noise = run(&mut s, "graph.node.add", json!({"def": "pixel_processor"}))["id"].as_u64().unwrap(); + let mut function = materialcraft_engine::core::FunctionGraph::default(); + let maximum = function.add_constant(materialcraft_engine::core::Value::Float(1.0)); + function.output = Some(function.add("rand", &[maximum], None)); + run(&mut s, "graph.node.param", json!({"id": noise, "param": "function", "value": materialcraft_engine::core::Value::Function(Box::new(function))})); + run(&mut s, "graph.node.base", json!({"id": noise, "seed": 7})); + let output = NodeId(run(&mut s, "graph.node.add", json!({"def": "output", "connectFrom": {"node": noise}}))["id"].as_u64().unwrap()); + run(&mut s, "graph.select", json!({"ids": [noise]})); + let before_graphs = s.pkg.graphs.clone(); + let before = s.cook().image(output, 0).unwrap().clone(); + run(&mut s, "graph.createFromSelection", json!({"name": "Grouped_noise"})); + // Force an actual cook instead of relying on the pre-grouping cache entry. + s.cache.lock().unwrap().clear(); + let after = s.cook().image(output, 0).unwrap().clone(); + assert!(before.data == after.data, "grouping changed the material at graph seed {seed}"); + assert_eq!((after.w, after.h), (64, 32)); + assert_eq!(s.pkg.graphs[1].seed, seed); + let grouped_graphs = s.pkg.graphs.clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.pkg.graphs, before_graphs); + assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.pkg.graphs, grouped_graphs); + assert_eq!(s.cook().image(output, 0).unwrap().data, before.data); + let bytes = formats::sbs::write_sbs(&s.pkg).unwrap(); + let mut reopened = Session::new(formats::sbs::read_sbs(&bytes, "seed.sbs", &|_| None).unwrap().pkg); + reopened.preview_size = None; + let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id; + assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data, before.data); + } +} diff --git a/crates/engine/tests/view_settings.rs b/crates/engine/tests/view_settings.rs new file mode 100644 index 00000000..47d0ea16 --- /dev/null +++ b/crates/engine/tests/view_settings.rs @@ -0,0 +1,53 @@ +use materialcraft_engine::{execute, new_session}; +use serde_json::json; + +#[test] +fn rejected_2d_settings_leave_the_view_unchanged() { + let mut s = new_session(); + let a = execute(&mut s, "graph.node.add", &json!({"def": "channels_shuffle"})).unwrap()["id"].as_u64().unwrap(); + let b = execute(&mut s, "graph.node.add", &json!({"def": "channels_shuffle"})).unwrap()["id"].as_u64().unwrap(); + execute(&mut s, "view.2d", &json!({"node": a, "port": 1, "channel": "g"})).unwrap(); + let before = s.view2d.clone(); + // A bad channel used to leave all the preceding fields changed despite returning an error. + assert!(execute(&mut s, "view.2d", &json!({"node": b, "port": 2, "tiled": true, "histogram": true, "channel": "invalid"})).is_err()); + assert_eq!(s.view2d, before); + assert!(execute(&mut s, "view.2d", &json!({"node": u64::MAX, "channel": "b", "tiled": true})).is_err()); + assert_eq!(s.view2d, before); + assert_eq!(execute(&mut s, "session.inspect", &json!({})).unwrap()["view2d"], serde_json::to_value(&before).unwrap()); +} + +#[test] +fn rejected_3d_settings_leave_the_view_unchanged() { + let mut s = new_session(); + execute(&mut s, "view.3d", &json!({"scene": "sphere", "environment": "sunset", "yaw": 70})).unwrap(); + let before = s.view3d.clone(); + // A valid scene must not be applied when another setting in the request is rejected. + for params in [ + json!({"scene": "cube", "environment": "invalid", "yaw": 10}), + json!({"scene": "invalid", "environment": "studio"}), + json!({"scene": "custom", "environment": "studio"}), + json!({"scene": "cube", "target": [1, 2]}), + ] { + assert!(execute(&mut s, "view.3d", ¶ms).is_err(), "{params}"); + assert_eq!(s.view3d, before, "{params}"); + } + assert_eq!(execute(&mut s, "session.inspect", &json!({})).unwrap()["view3d"], serde_json::to_value(&before).unwrap()); +} + +#[test] +fn valid_view_updates_still_apply_and_return_the_complete_settings() { + let mut s = new_session(); + let node = execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap(); + let result = execute(&mut s, "view.2d", &json!({"node": node, "channel": "r", "tiled": true, "histogram": true})).unwrap(); + assert_eq!(result["node"], node); + assert_eq!(result["channel"], "r"); + assert_eq!(result["tiled"], true); + assert_eq!(result["histogram"], true); + assert_eq!(result, serde_json::to_value(&s.view2d).unwrap()); + let result = execute(&mut s, "view.3d", &json!({"scene": "cube", "environment": "night", "yaw": 370, "target": [1, 2, 3]})).unwrap(); + assert_eq!(result["scene"], "cube"); + assert_eq!(result["environment"], "night"); + assert_eq!(result["yaw"], 10.0); + assert_eq!(result["target"], json!([1.0, 2.0, 3.0])); + assert_eq!(result, serde_json::to_value(&s.view3d).unwrap()); +} diff --git a/crates/eval/src/cache.rs b/crates/eval/src/cache.rs index e221307c..e175cead 100644 --- a/crates/eval/src/cache.rs +++ b/crates/eval/src/cache.rs @@ -8,6 +8,7 @@ pub struct Cache { bytes: usize, cap: usize, tick: u64, + pub(crate) input_hashes: HashMap, } impl Default for Cache { @@ -18,7 +19,7 @@ impl Default for Cache { impl Cache { pub fn new(cap_bytes: usize) -> Cache { - Cache { entries: HashMap::new(), bytes: 0, cap: cap_bytes, tick: 0 } + Cache { entries: HashMap::new(), bytes: 0, cap: cap_bytes, tick: 0, input_hashes: HashMap::new() } } pub fn bytes(&self) -> usize { @@ -35,6 +36,7 @@ impl Cache { pub fn clear(&mut self) { self.entries.clear(); + self.input_hashes.clear(); self.bytes = 0; } diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index 0f522279..40e47723 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -1,12 +1,37 @@ -use crate::{identifier, instance_graph}; +use crate::{Cache, identifier, instance_graph}; use materialcraft_core::{Node, Package, Value}; use materialcraft_image::Image; use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Mutex}; -pub(crate) fn image_key(i: &Image) -> u64 { - let step = (i.data.len() / 4096).max(1); - hash_of(&(i.w, i.h, i.data.iter().step_by(step).map(|v| v.to_bits()).collect::>())) +pub(crate) fn image_key(i: &Image, cache: &Mutex) -> u64 { + let ptr = Arc::as_ptr(&i.data) as usize; + let shape = (i.w, i.h, i.kind.channels()); + if let Some(key) = cache + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .input_hashes + .get(&ptr) + .and_then(|saved| saved.buffer.upgrade().filter(|data| Arc::ptr_eq(data, &i.data) && saved.shape == shape).map(|_| saved.key)) + { + return key; + } + let mut h = DefaultHasher::new(); + (shape, i.data.len()).hash(&mut h); + for value in i.data.iter() { + value.to_bits().hash(&mut h); + } + let key = h.finish(); + let mut cache = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if cache.input_hashes.len() >= 128 { + cache.input_hashes.retain(|_, saved| saved.buffer.strong_count() > 0); + if cache.input_hashes.len() >= 128 { + cache.input_hashes.clear(); + } + } + cache.input_hashes.insert(ptr, crate::input_fingerprint::InputFingerprint { buffer: Arc::downgrade(&i.data), shape, key }); + key } pub(crate) fn hash_of(v: &impl Hash) -> u64 { diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index 64eac009..f02a1703 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -15,8 +15,13 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu // The top-level graph's input nodes show their preview images; the caller's images win let bound; let options = if options.depth == 0 && !graph.input_images.is_empty() { - let mut inputs: BTreeMap = - graph.input_images.iter().filter_map(|(id, resource)| Some((id.clone(), (options.resource)(resource)?))).collect(); + let mut inputs: BTreeMap = graph + .input_images + .iter() + .filter_map(|(id, resource)| { + Some((id.clone(), (options.resource)(&materialcraft_image::resource_key(resource, graph.input_images_linear.contains(id)))?)) + }) + .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 diff --git a/crates/eval/src/input_fingerprint.rs b/crates/eval/src/input_fingerprint.rs new file mode 100644 index 00000000..3b04d6bf --- /dev/null +++ b/crates/eval/src/input_fingerprint.rs @@ -0,0 +1,7 @@ +use std::sync::Weak; + +pub(crate) struct InputFingerprint { + pub buffer: Weak>, + pub shape: (u32, u32, usize), + pub key: u64, +} diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index bee00925..3d8e9028 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -7,6 +7,7 @@ mod cooked; mod graph_execution; mod graph_instance; mod graph_output; +mod input_fingerprint; mod node_execution; mod node_output; mod node_result; diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index ac4b9456..a0ce6646 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -73,7 +73,7 @@ pub(crate) fn cook_node( incoming.push(output); } let vars = &variables; - let first = inputs.iter().flatten().next().map(|i| (i.w, i.h)); + let first = prepared.first_input_size(node.id); 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)]), @@ -110,7 +110,7 @@ pub(crate) fn cook_node( &input_keys, res_hash, sub_hash, - input_img.map(image_key), + input_img.map(|image| image_key(image, cache)), variable_key(node, ¶ms, vars), )); if let Some(v) = lock(cache).get(key) { diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs index 7a25bf4b..d34d0c6e 100644 --- a/crates/eval/src/prepared_graph.rs +++ b/crates/eval/src/prepared_graph.rs @@ -6,6 +6,7 @@ use std::collections::BTreeMap; pub(crate) struct PreparedGraph<'a> { pub index: GraphIndex<'a>, pub order: Vec, + nominal_sizes: BTreeMap, ports: BTreeMap, Vec)>, } @@ -22,7 +23,26 @@ impl<'a> PreparedGraph<'a> { }) .collect(); - Self { index, order, ports } + let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new() }; + for &id in &prepared.order { + let Some(node) = prepared.index.node(id) else { continue }; + + let input = prepared.first_input_size(id); + let nominal = if node.disabled { + input.unwrap_or_else(|| crate::node_size(graph, materialcraft_nodes::find(&node.def), node, None, None)) + } else { + crate::node_size(graph, materialcraft_nodes::find(&node.def), node, input, None) + }; + prepared.nominal_sizes.insert(id, nominal); + } + prepared + } + + pub fn first_input_size(&self, id: NodeId) -> Option<(u32, u32)> { + self.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| { + let connection = self.index.input_of(id, &port.id)?; + self.nominal_sizes.get(&connection.from).copied() + }) } pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) { diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 9c714b42..7e2d8d8e 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -271,3 +271,102 @@ fn partial_cooks_keep_shared_dependencies_and_first_duplicate_node() { assert!(cooked.image(id, 0).is_some()); } } + +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]); + let first = image_key(&image, &cache); + assert_eq!(image_key(&image, &cache), first); + Arc::make_mut(&mut image.data)[1] = 1.0; + let changed = image_key(&image, &cache); + assert_ne!(changed, first); + image.w = 64; + image.h = 256; + assert_ne!(image_key(&image, &cache), changed); + cache.lock().unwrap().clear(); + assert_eq!(image_key(&image, &cache), image_key(&image, &cache)); +} +#[test] +fn preview_cap_does_not_compound_downscaling() { + let (mut p, noise, blur, out) = sample(); + p.graphs[0].size = [10, 10]; + p.graphs[0].node_mut(blur).unwrap().base.size = [-3, -3]; + let cache = Mutex::new(Cache::default()); + let mut opts = Options::new(&no_res); + opts.max_size = Some(512); + let c = cook(&p, 0, &opts, &cache); + assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((512, 512))); + assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 128))); + assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 128))); +} +#[test] +fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() { + let (mut p, noise, blur, out) = sample(); + p.graphs[0].size = [13, 12]; + p.graphs[0].node_mut(blur).unwrap().disabled = true; + p.graphs[0].node_mut(out).unwrap().base.size = [1, 0]; + let cache = Mutex::new(Cache::default()); + let mut opts = Options::new(&no_res); + opts.max_size = Some(128); + let c = cook(&p, 0, &opts, &cache); + assert_eq!(c.image(noise, 0).map(|i| (i.w, i.h)), Some((128, 64))); + assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((128, 64))); + assert_eq!(c.image(out, 0).map(|i| (i.w, i.h)), Some((128, 64))); +} +#[test] +fn changed_unsampled_input_recooks() { + let mut g = Graph::new("g"); + g.size = [7, 7]; + let input = g.add_node("input_grayscale", [0.0, 0.0]); + let mut p = Package::new("p"); + p.graphs.push(g); + let mut opts = Options::new(&no_res); + let image = Image::filled(128, 128, Kind::Gray, [0.0; 4]); + opts.inputs.insert("input".into(), image.clone()); + let cache = Mutex::new(Cache::default()); + let first = cook(&p, 0, &opts, &cache); + assert!(!first.nodes[&input].cached); + let mut changed = image; + Arc::make_mut(&mut changed.data)[1] = 1.0; + opts.inputs.insert("input".into(), changed); + let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&input].cached); + assert_eq!(second.image(input, 0).unwrap().data[1], 1.0); +} +#[test] +fn linear_input_images_and_bitmap_nodes_request_data_reads() { + // The decoder returns 0.5 for a linear request and 0.2 for an sRGB one. + let res = |k: &str| { + let (name, linear) = materialcraft_image::split_resource_key(k); + (name == "m").then(|| Image::filled(4, 4, Kind::Color, [if linear { 0.5 } else { 0.2 }; 4])) + }; + let mut p = Package::new("p"); + let mut g = Graph::new("g"); + g.size = [4, 4]; + let i = g.add_node("input_color", [0.0, 0.0]); + g.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("n".into())); + let b = g.add_node("bitmap", [0.0, 100.0]); + g.node_mut(b).unwrap().params.insert("resource".into(), Value::Text("m".into())); + g.input_images.insert("n".into(), "m".into()); + p.graphs.push(g); + let first = |p: &Package| { + let cache = Mutex::new(Cache::default()); + let c = cook(p, 0, &Options::new(&res), &cache); + (c.image(i, 0).unwrap().data[0], c.image(b, 0).unwrap().data[0]) + }; + assert_eq!(first(&p), (0.2, 0.2), "default is sRGB, as before"); + p.graphs[0].input_images_linear.insert("n".into()); + p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1)); + assert_eq!(first(&p), (0.5, 0.5)); +} diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index 4d9cfe72..17ede5e8 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -4,34 +4,33 @@ use std::io::Cursor; use std::sync::Arc; /// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale files stay grayscale) -pub fn decode(bytes: &[u8]) -> Result { +pub fn decode(bytes: &[u8], linear: bool) -> Result { if std::str::from_utf8(bytes.get(..bytes.len().min(4096)).unwrap_or_default()).is_ok_and(|text| text.contains(" 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()); + let open = || -> Result>> { + let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Image(e.to_string()))?; + if reader.format().is_none() { + 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); + Ok(reader) + }; + let failed = || FormatError::Image("the decoder failed on this file".into()); + let image_error = |e| match e { + image::ImageError::Limits(_) => FormatError::Image(format!("image is larger than {MAX_SIDE} pixels")), + e => FormatError::Image(e.to_string()), + }; + let (w, h) = guard(|| open()?.into_dimensions().map_err(image_error), failed)?; 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"))); } + let img = guard(|| open()?.decode().map_err(image_error), failed)?; let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16); let float = matches!(img.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F); if gray { @@ -40,7 +39,7 @@ pub fn decode(bytes: &[u8]) -> Result { return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); } let mut data = img.into_rgba32f().into_raw(); - if !float { + if !(float || linear) { for px in data.chunks_exact_mut(4) { for c in px.iter_mut().take(3) { *c = srgb_to_linear(*c); diff --git a/crates/formats/src/material/archive.rs b/crates/formats/src/material/archive.rs index 1c8a1deb..9adc29e7 100644 --- a/crates/formats/src/material/archive.rs +++ b/crates/formats/src/material/archive.rs @@ -77,8 +77,15 @@ pub fn read_material(bytes: &[u8]) -> Result<(Manifest, Vec)> { let bad = |m: String| FormatError::BadPackage(format!("portable material: {m}")); let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| bad(e.to_string()))?; let mut read = |name: &str, cap: u64| -> Result> { + let entry = z.by_name(name).map_err(|_| bad(format!("{name} is missing")))?; + if entry.size() > cap { + return Err(bad(format!("{name} exceeds {cap} bytes"))); + } let mut data = Vec::new(); - z.by_name(name).map_err(|_| bad(format!("{name} is missing")))?.take(cap).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?; + entry.take(cap + 1).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?; + if data.len() as u64 > cap { + return Err(bad(format!("{name} exceeds {cap} bytes"))); + } Ok(data) }; diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index cfaca36c..88b1c005 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -17,6 +17,42 @@ fn bad(msg: impl Into) -> FormatError { FormatError::BadPackage(msg.into()) } +/// Append the triangles of `ix` to `out`, offset by `base`. Whole triangles are dropped when any +/// of their indices is `>= n` (or when a trailing partial triangle is left over), so the +/// triangles that follow keep their vertices. +fn push_triangles(out: &mut Vec, ix: impl IntoIterator, n: usize, base: u32) -> Result<()> { + append_triangles(out, ix, n, base, MAX_TRIANGLES) +} + +fn append_triangles(out: &mut Vec, ix: impl IntoIterator, n: usize, base: u32, limit: usize) -> Result<()> { + let mut ix = ix.into_iter(); + while let (Some(a), Some(b), Some(c)) = (ix.next(), ix.next(), ix.next()) { + let t = [a, b, c]; + if t.iter().all(|i| (*i as usize) < n) { + if out.len() / 3 >= limit { + return Err(bad("the mesh is too large")); + } + out.extend(t.iter().map(|i| i.saturating_add(base))); + } + } + Ok(()) +} + +/// Build the mesh, rejecting non-finite positions, normals and UVs before anything computes +/// normals, tangents or bounds from them. +fn finish(positions: Vec, normals: Option>, uvs: Vec, indices: Vec) -> Result { + if positions.iter().any(|p| !p.is_finite()) { + return Err(bad("the mesh has non-finite (NaN or infinite) positions")); + } + if normals.iter().flatten().any(|n| !n.is_finite()) { + return Err(bad("the mesh has non-finite (NaN or infinite) normals")); + } + if uvs.iter().any(|u| !u.is_finite()) { + return Err(bad("the mesh has non-finite (NaN or infinite) UVs")); + } + Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string())) +} + /// Parse a mesh file by extension. pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); @@ -67,14 +103,13 @@ fn obj(bytes: &[u8]) -> Result { // OBJ UVs have their origin at the bottom left. uvs.push(mesh.texcoords.get(i * 2..i * 2 + 2).map_or(Vec2::ZERO, |t| Vec2::new(t[0], 1.0 - t[1]))); } - indices.extend(mesh.indices.iter().filter(|i| (**i as usize) < n).map(|i| i + base)); + push_triangles(&mut indices, mesh.indices.iter().copied(), n, base)?; if indices.len() / 3 > MAX_TRIANGLES { return Err(bad("the mesh is too large")); } } - indices.truncate(indices.len() / 3 * 3); let normals = (normals.len() == positions.len()).then_some(normals); - Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string())) + finish(positions, normals, uvs, indices) } fn gltf(bytes: &[u8]) -> Result { @@ -105,8 +140,8 @@ fn gltf(bytes: &[u8]) -> Result { None => uvs.extend(std::iter::repeat_n(Vec2::ZERO, n)), } match reader.read_indices() { - Some(ix) => indices.extend(ix.into_u32().filter(|i| (*i as usize) < n).map(|i| i + base)), - None => indices.extend((0..n as u32).map(|i| i + base)), + Some(ix) => push_triangles(&mut indices, ix.into_u32(), n, base)?, + None => push_triangles(&mut indices, 0..n as u32, n, base)?, } positions.extend(pos); if indices.len() / 3 > MAX_TRIANGLES { @@ -114,9 +149,8 @@ fn gltf(bytes: &[u8]) -> Result { } } } - indices.truncate(indices.len() / 3 * 3); let normals = (all_normals && normals.len() == positions.len()).then_some(normals); - Mesh::from_parts(positions, normals, uvs, indices, "material").map_err(|e| bad(e.to_string())) + finish(positions, normals, uvs, indices) } /// Box-projected UVs: each vertex takes the plane of its normal's largest axis. @@ -156,6 +190,80 @@ mod tests { assert!(m.uvs.iter().any(|u| *u != m.uvs[0])); } + /// A glTF with 4 vertices (positions given by `pos`, optional UVs) and the given indices. + fn gltf_json(pos: [[f32; 3]; 4], uvs: Option<[[f32; 2]; 4]>, idx: &[u16]) -> Vec { + use base64::Engine as _; + let mut buf: Vec = pos.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); + let uv_off = buf.len(); + if let Some(uvs) = uvs { + buf.extend(uvs.iter().flatten().flat_map(|f| f.to_le_bytes())); + } + let idx_off = buf.len(); + buf.extend(idx.iter().flat_map(|i| i.to_le_bytes())); + let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + let uv_attr = if uvs.is_some() { r#","TEXCOORD_0":1"# } else { "" }; + let uv_view = if uvs.is_some() { format!(r#"{{"buffer":0,"byteOffset":{uv_off},"byteLength":32}},"#) } else { String::new() }; + let uv_acc = if uvs.is_some() { r#"{"bufferView":1,"componentType":5126,"count":4,"type":"VEC2"},"# } else { "" }; + // View/accessor layout: with UVs, views are [pos, uv, idx] and accessors [pos, uv, idx]. + let idx_view = if uvs.is_some() { 2 } else { 1 }; + let idx_acc = if uvs.is_some() { 2 } else { 1 }; + format!( + r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], +"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0{uv_attr}}},"indices":{idx_acc}}}]}}], +"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{uv_acc}{{"bufferView":{idx_view},"componentType":5123,"count":{},"type":"SCALAR"}}], +"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{uv_view}{{"buffer":0,"byteOffset":{idx_off},"byteLength":{}}}], +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, + idx.len(), + idx.len() * 2, + buf.len() + ) + .into_bytes() + } + + const QUAD: [[f32; 3]; 4] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]; + + #[test] + fn triangle_limit_stops_a_stream_before_collecting_the_rest() { + let mut out = Vec::new(); + let mut read = 0; + let indices = std::iter::from_fn(|| { + read += 1; + assert!(read <= 6, "read beyond the first triangle over the limit"); + Some(0) + }); + assert!(append_triangles(&mut out, indices, 1, 0, 1).is_err()); + assert_eq!(out, [0, 0, 0]); + assert_eq!(read, 6); + } + + #[test] + fn obj_non_finite_normals_are_rejected() { + 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 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). + let m = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 1, 9, 0, 2, 3])).unwrap(); + assert_eq!(m.indices, vec![0, 1, 2, 0, 2, 3]); + // An index count that is not a multiple of 3 drops only the partial triangle. + let m = load_mesh("x.gltf", &gltf_json(QUAD, None, &[0, 1, 2, 0, 2, 3, 1, 2])).unwrap(); + assert_eq!(m.indices, vec![0, 1, 2, 0, 2, 3]); + } + + #[test] + fn non_finite_positions_normals_and_uvs_are_rejected_before_processing() { + let mut nan_pos = QUAD; + nan_pos[2][0] = f32::NAN; + let e = load_mesh("x.gltf", &gltf_json(nan_pos, None, &[0, 1, 2, 0, 2, 3])).unwrap_err(); + assert!(e.to_string().contains("non-finite"), "{e}"); + let mut nan_uv = [[0.0f32, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; + nan_uv[1][1] = f32::NAN; + let e = load_mesh("x.gltf", &gltf_json(QUAD, Some(nan_uv), &[0, 1, 2, 0, 2, 3])).unwrap_err(); + assert!(e.to_string().contains("non-finite"), "{e}"); + assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvt nan 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").is_err()); + } + #[test] fn bad_meshes_are_errors() { assert!(load_mesh("x.obj", b"").is_err()); diff --git a/crates/formats/src/sbs/constant.rs b/crates/formats/src/sbs/constant.rs index 6314e7b2..f35e9a96 100644 --- a/crates/formats/src/sbs/constant.rs +++ b/crates/formats/src/sbs/constant.rs @@ -18,3 +18,5 @@ 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]; + +pub(super) const MAX_PACKAGE_BYTES: usize = 1 << 30; diff --git a/crates/formats/src/sbs/embedded.rs b/crates/formats/src/sbs/embedded.rs index 6e284cb8..cd8bdcb3 100644 --- a/crates/formats/src/sbs/embedded.rs +++ b/crates/formats/src/sbs/embedded.rs @@ -6,16 +6,17 @@ 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, String> { +pub(super) fn decode_embedded(strdata: &str, remaining: usize) -> 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 limit = remaining.min(MAX_EMBEDDED_BYTES); + if length > limit { + return Err(format!("{length} bytes is over the {limit}-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); + let mut decoder = flate2::read::ZlibDecoder::new(compressed).take(limit 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())); @@ -30,3 +31,18 @@ pub(super) fn encode_embedded(bytes: &[u8]) -> Result { let raw = encoder.finish().map_err(|e| FormatError::Io(e.to_string()))?; Ok(base64_engine().encode(raw)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decompression_obeys_the_remaining_package_budget() { + let encoded = encode_embedded(&[1, 2, 3, 4]).unwrap(); + assert_eq!(decode_embedded(&encoded, 4).unwrap(), [1, 2, 3, 4]); + assert!(decode_embedded(&encoded, 3).unwrap_err().contains("limit")); + let mut raw = base64_engine().decode(&encoded).unwrap(); + raw[..4].copy_from_slice(&1u32.to_be_bytes()); + assert!(decode_embedded(&base64_engine().encode(raw), 1).is_err()); + } +} diff --git a/crates/formats/src/sbs/filter_map.rs b/crates/formats/src/sbs/filter_map.rs index 3a87b7f0..9ddeed34 100644 --- a/crates/formats/src/sbs/filter_map.rs +++ b/crates/formats/src/sbs/filter_map.rs @@ -55,7 +55,7 @@ pub(super) const FILTERS: &[FilterMap] = &[ 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: "bitmap", def: "bitmap", inputs: &[], params: &[("colorswitch", "color_mode"), ("colorspace", "colour_space")] }, FilterMap { sbs: "levels", def: "levels", @@ -108,13 +108,8 @@ pub(super) const FILTERS: &[FilterMap] = &[ }, ]; 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) const HANDLED_PARAMS: &[(&str, &str)] = + &[("bitmap", "bitmapresourcepath"), ("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) diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs index e66e99bb..4ada3784 100644 --- a/crates/formats/src/sbs/function_graph.rs +++ b/crates/formats/src/sbs/function_graph.rs @@ -1,4 +1,4 @@ -use super::sbs_value::{constant_xml, sbs_constant, to_natural_value}; +use super::sbs_value::{constant_xml, sbs_constant, sbs_constant_element, 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}; @@ -35,8 +35,7 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result { .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) + .and_then(|data| data.children().filter(|child| child.is_element()).find_map(|child| sbs_constant_element(child).or_else(|| sbs_constant(child)))) .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 { diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index b3545a6a..ee497404 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -34,3 +34,5 @@ mod tests; mod read; mod write; + +mod preview_binding; diff --git a/crates/formats/src/sbs/preview_binding.rs b/crates/formats/src/sbs/preview_binding.rs new file mode 100644 index 00000000..34e39615 --- /dev/null +++ b/crates/formats/src/sbs/preview_binding.rs @@ -0,0 +1,29 @@ +use super::xml::{child_value, xml_escape}; +use materialcraft_core::Graph; +use roxmltree::Node as XmlNode; +use std::fmt::Write as _; + +const IMAGE_PREFIX: &str = "materialcraft.previewImage."; +const LINEAR_PREFIX: &str = "materialcraft.previewLinear."; + +pub(super) fn write(out: &mut String, graph: &Graph) { + for (identifier, resource) in &graph.input_images { + let _ = write!(out, "", xml_escape(identifier), xml_escape(resource)); + if graph.input_images_linear.contains(identifier) { + let _ = write!(out, "", xml_escape(identifier)); + } + } +} + +pub(super) fn read(option: XmlNode, graph: &mut Graph) { + let Some(name) = child_value(option, "name") else { return }; + let Some(value) = child_value(option, "value") else { return }; + + if let Some(identifier) = name.strip_prefix(IMAGE_PREFIX) { + graph.input_images.insert(identifier.to_string(), value.to_string()); + } else if let Some(identifier) = name.strip_prefix(LINEAR_PREFIX) + && value == "1" + { + graph.input_images_linear.insert(identifier.to_string()); + } +} diff --git a/crates/formats/src/sbs/read.rs b/crates/formats/src/sbs/read.rs index 1958dd9d..003272b5 100644 --- a/crates/formats/src/sbs/read.rs +++ b/crates/formats/src/sbs/read.rs @@ -34,8 +34,15 @@ pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option "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 }; + let mut reader = SbsReader { + text, + warnings: &mut warnings, + dependencies: HashMap::new(), + graph_names: HashMap::new(), + resource_names: HashMap::new(), + node_count: 0, + resource_bytes: 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()); diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index ffde83e7..1c8dc7ed 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -27,6 +27,7 @@ pub(super) struct SbsReader<'text, 'warnings> { pub(super) graph_names: HashMap, pub(super) resource_names: HashMap, pub(super) node_count: usize, + pub(super) resource_bytes: usize, } impl<'text> SbsReader<'text, '_> { @@ -61,6 +62,7 @@ impl<'text> SbsReader<'text, '_> { } pub(super) fn read_resource(&mut self, item: XmlNode, identifier: &str, path: &str, pkg: &mut Package, linked: &dyn Fn(&str) -> Option>) { + let remaining = super::constant::MAX_PACKAGE_BYTES.saturating_sub(self.resource_bytes).min(super::constant::MAX_EMBEDDED_BYTES); 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"); @@ -68,7 +70,7 @@ impl<'text> SbsReader<'text, '_> { 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("")) { + match decode_embedded(child_value(embedded, "strdata").unwrap_or(""), remaining) { Ok(data) => bytes = Some(data), Err(e) => why_missing = format!("its embedded data is damaged ({e})"), } @@ -95,7 +97,9 @@ impl<'text> SbsReader<'text, '_> { 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) if data.len() > remaining => self.warnings.add(format!("resource `{path}` exceeds the remaining {remaining}-byte package budget")), Some(data) => { + self.resource_bytes += data.len(); 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))); @@ -121,6 +125,7 @@ impl<'text> SbsReader<'text, '_> { // The default parent size option ("11x11", log2 sizes) for option in child_element(element, "options").into_iter().flat_map(|o| children_named(o, "option")) { + super::preview_binding::read(option, &mut graph); if child_value(option, "name") == Some("defaultParentSize") && let Some((width, height)) = child_value(option, "value").and_then(|v| v.split_once('x')) { diff --git a/crates/formats/src/sbs/sbs_value.rs b/crates/formats/src/sbs/sbs_value.rs index a1072e92..eecf2e47 100644 --- a/crates/formats/src/sbs/sbs_value.rs +++ b/crates/formats/src/sbs/sbs_value.rs @@ -46,7 +46,10 @@ impl SbsValue { } } pub(super) fn sbs_constant(holder: XmlNode) -> Option { - let element = holder.children().find(|c| c.is_element())?; + sbs_constant_element(holder.children().find(|child| child.is_element())?) +} + +pub(super) fn sbs_constant_element(element: XmlNode) -> Option { let text = element.attribute("v").unwrap_or(""); let tag = element.tag_name().name(); diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs index 6915524d..1d4218cd 100644 --- a/crates/formats/src/sbs/sbs_writer.rs +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -154,7 +154,9 @@ impl SbsWriter { write_canvas_items(out, graph, self); let [width, height] = graph.size.map(|s| s.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)); - let _ = write!(out, ""); + let _ = write!(out, ""); + super::preview_binding::write(out, graph); + out.push_str(""); for uid in graph.nodes.iter().filter_map(|n| output_uids.get(&n.id)) { let _ = write!(out, ""); } diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index 5b1c1dca..ccbc943d 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -220,11 +220,11 @@ fn linked_resources_load_through_the_callback() { fn embedded_data_round_trips_and_checks_its_length() { let data: Vec = (0..5000u32).map(|i| (i * 7 % 251) as u8).collect(); let encoded = encode_embedded(&data).unwrap(); - assert_eq!(decode_embedded(&encoded).unwrap(), data); + assert_eq!(decode_embedded(&encoded, super::constant::MAX_EMBEDDED_BYTES).unwrap(), data); let mut raw = base64_engine().decode(&encoded).unwrap(); raw[3] ^= 1; - assert!(decode_embedded(&base64_engine().encode(raw)).unwrap_err().contains("declared")); + assert!(decode_embedded(&base64_engine().encode(raw), super::constant::MAX_EMBEDDED_BYTES).unwrap_err().contains("declared")); } #[test] diff --git a/crates/formats/src/tests.rs b/crates/formats/src/tests.rs index d415d87b..e8fe792c 100644 --- a/crates/formats/src/tests.rs +++ b/crates/formats/src/tests.rs @@ -10,13 +10,13 @@ fn export_every_format() { for depth in [Depth::U8, Depth::U16, Depth::F32] { for i in [&img, &gray] { let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); - let back = decode(&b).unwrap_or_else(|e| panic!("{ext} decode: {e}")); + let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}")); assert_eq!((back.w, back.h), (8, 8)); } } } let png16 = encode(&gray, "png", Depth::U16, false).unwrap(); - assert!((decode(&png16).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); + assert!((decode(&png16, false).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); } #[test] @@ -30,7 +30,7 @@ fn names_are_safe() { fn oversized_images_are_refused_before_decoding() { let mut png = Cursor::new(Vec::new()); ::image::GrayImage::new(8193, 1).write_to(&mut png, ::image::ImageFormat::Png).unwrap(); - let err = decode(png.get_ref()).unwrap_err().to_string(); + let err = decode(png.get_ref(), false).unwrap_err().to_string(); assert!(err.contains("8192"), "{err}"); } @@ -38,7 +38,7 @@ fn oversized_images_are_refused_before_decoding() { fn tga_still_decodes() { let mut tga = Cursor::new(Vec::new()); ::image::RgbaImage::new(2, 2).write_to(&mut tga, ::image::ImageFormat::Tga).unwrap(); - let img = decode(tga.get_ref()).unwrap(); + let img = decode(tga.get_ref(), false).unwrap(); assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color)); } @@ -46,7 +46,7 @@ fn tga_still_decodes() { fn decode_matches_previous_values() { let mut png = Cursor::new(Vec::new()); ::image::RgbImage::from_pixel(2, 2, ::image::Rgb([128, 128, 128])).write_to(&mut png, ::image::ImageFormat::Png).unwrap(); - let img = decode(png.get_ref()).unwrap(); + let img = decode(png.get_ref(), false).unwrap(); let want = srgb_to_linear(128.0 / 255.0); assert!((img.get(1, 1, false)[0] - want).abs() < 1e-4); } diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs index 426562e4..396f1e5a 100644 --- a/crates/image/src/lib.rs +++ b/crates/image/src/lib.rs @@ -140,6 +140,8 @@ impl Image { if !fx.is_finite() || !fy.is_finite() { return [0.0, 0.0, 0.0, 1.0]; } + // Huge but finite coordinates would saturate the i64 cast and overflow at `+ 1`. + let (fx, fy) = (fx.clamp(-1.0e9, 1.0e9), fy.clamp(-1.0e9, 1.0e9)); let (x0, y0) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - x0, fy - y0); let (x0, y0) = (x0 as i64, y0 as i64); @@ -300,10 +302,53 @@ pub fn srgb_to_linear(v: f32) -> f32 { if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } } +/// Encode the bitmap name and its requested color space without ambiguity. +/// Plain sRGB names remain readable by simple resource callbacks. +pub fn resource_key(name: &str, linear: bool) -> String { + if linear { + format!("\u{1}L{name}") + } else if name.starts_with('\u{1}') { + format!("\u{1}S{name}") + } else { + name.to_string() + } +} + +/// Split a key made by [`resource_key`] into its name and data-map flag. +pub fn split_resource_key(key: &str) -> (&str, bool) { + if let Some(name) = key.strip_prefix("\u{1}L") { + (name, true) + } else if let Some(name) = key.strip_prefix("\u{1}S") { + (name, false) + } else { + (key, false) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn sample_survives_huge_coordinates() { + let img = Image::gray(8, 8, |x, _| x as f32); + for u in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN] { + for tile in [true, false] { + let p = img.sample(u, u, tile); + assert!(p.iter().all(|c| c.is_finite())); + } + } + } + + #[test] + fn resource_keys_round_trip() { + for name in ["n", "", "\u{1}Lnormal", "\u{1}Sn", "n\u{1}linear"] { + for linear in [false, true] { + assert_eq!(split_resource_key(&resource_key(name, linear)), (name, linear)); + } + } + } + #[test] fn sample_wraps_and_clamps() { let img = Image::gray(4, 1, |x, _| x as f32); diff --git a/crates/nodes/src/atomic/bitmap.rs b/crates/nodes/src/atomic/bitmap.rs index 339feeb4..1a98ada3 100644 --- a/crates/nodes/src/atomic/bitmap.rs +++ b/crates/nodes/src/atomic/bitmap.rs @@ -7,6 +7,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .generator() .resource("resource", "Bitmap resource") + .choice("colour_space", "Color space", &["sRGB", "Linear"], 0) .boolean("color_mode", "Color output", true) .any_out() .cook(bitmap) @@ -14,7 +15,7 @@ pub(super) fn definition() -> NodeDefinition { fn bitmap(context: &CookContext) -> CookResult { let name = context.text("resource"); - let image = match (context.resource)(name) { + let image = match (context.resource)(&materialcraft_image::resource_key(name, context.i("colour_space") == 1)) { Some(image) => image.resize(context.w, context.h, context.tile), None if name.is_empty() => context.gen_color(|u, v| { let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 }; diff --git a/crates/nodes/src/atomic/distance.rs b/crates/nodes/src/atomic/distance.rs index df9da4a6..fda95f52 100644 --- a/crates/nodes/src/atomic/distance.rs +++ b/crates/nodes/src/atomic/distance.rs @@ -19,32 +19,23 @@ 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 inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5; let Some(src) = context.sized(1) else { + let d2 = ops::distance_sq(context.w, context.h, inside, context.tile); return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); }; - // 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 = d2.iter().map(|d| d.sqrt()).collect(); + // Propagate the exact nearest site without gaps from gradient-walk stalls + let (d2, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile); let 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); + let i = y as usize * context.w as usize + x as usize; + let site = sites.get(i).copied().unwrap_or(usize::MAX); + let mut c = if site == usize::MAX { + [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }] + } else { + src.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false) + }; + let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt(); if d > maxd { c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]; } else if combine { diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index cd3b0405..6a7bf85e 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -94,62 +94,108 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { /// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is /// true (Felzenszwalb–Huttenlocher, exact, linear time). With `tile`, distances wrap. pub fn distance_sq(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> Vec { + distance_transform::(w, h, inside, tile).0 +} + +/// The same exact distance transform, also retaining the nearest mask pixel's row-major index. +/// Empty masks have no nearest pixel: their indices are `usize::MAX`. +pub fn distance_sq_with_sites(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> (Vec, Vec) { + distance_transform::(w, h, inside, tile) +} + +const DISTANCE_INF: f32 = 1e20; + +fn edt_1d(f: &[f32]) -> (Vec, Vec) { + let n = f.len(); + if n == 0 { + return (Vec::new(), Vec::new()); + } + let f: Vec = f.iter().map(|v| *v as f64).collect(); + let mut d = vec![0.0f32; n]; + // Distance-only callers do not allocate or propagate site indices. + let mut sites = if SITES { vec![usize::MAX; n] } else { Vec::new() }; + let mut v = vec![0usize; n]; + let mut z = vec![0.0f64; n + 1]; + let mut k = 0usize; + z[0] = -(DISTANCE_INF as f64); + z[1] = DISTANCE_INF as f64; + let cross = |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64); + for q in 1..n { + let mut s = cross(q, v[k]); + while k > 0 && s <= z[k] { + k -= 1; + s = cross(q, v[k]); + } + k += 1; + v[k] = q; + z[k] = s; + z[k + 1] = DISTANCE_INF as f64; + } + k = 0; + for (q, dq) in d.iter_mut().enumerate() { + while k + 1 < n && z[k + 1] < q as f64 { + k += 1; + } + let p = v[k]; + *dq = ((q as f64 - p as f64).powi(2) + f[p]) as f32; + if SITES && f[p] < DISTANCE_INF as f64 { + sites[q] = p; + } + } + (d, sites) +} + +fn distance_transform(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> (Vec, Vec) { let (w, h) = (w as usize, h as usize); - const INF: f32 = 1e20; + if w == 0 || h == 0 { + return (Vec::new(), Vec::new()); + } // Tiling: run on a 3x tiled line so distances cross the edges. let rep = if tile { 3 } else { 1 }; - let edt_1d = |f: &[f32]| -> Vec { - let n = f.len(); - let f: Vec = f.iter().map(|v| *v as f64).collect(); - let mut d = vec![0.0f32; n]; - let mut v = vec![0usize; n]; - let mut z = vec![0.0f64; n + 1]; - let mut k = 0usize; - z[0] = -(INF as f64); - z[1] = INF as f64; - let cross = |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64); - for q in 1..n { - let mut s = cross(q, v[k]); - while k > 0 && s <= z[k] { - k -= 1; - s = cross(q, v[k]); - } - k += 1; - v[k] = q; - z[k] = s; - z[k + 1] = INF as f64; - } - k = 0; - for (q, dq) in d.iter_mut().enumerate() { - while k + 1 < n && z[k + 1] < q as f64 { - k += 1; - } - let p = v[k]; - *dq = ((q as f64 - p as f64).powi(2) + f[p]) as f32; - } - d - }; - // Columns. - let cols: Vec> = (0..w) + // Columns. Site indices are vertical coordinates at this stage. + let cols: Vec<_> = (0..w) .into_par_iter() .map(|x| { - let f: Vec = (0..h * rep).map(|y| if inside((y % h) * w + x) { 0.0 } else { INF }).collect(); - let d = edt_1d(&f); + let f: Vec = (0..h * rep).map(|y| if inside((y % h) * w + x) { 0.0 } else { DISTANCE_INF }).collect(); + let (d, sites) = edt_1d::(&f); let off = if tile { h } else { 0 }; - d[off..off + h].to_vec() + (d[off..off + h].to_vec(), if SITES { sites[off..off + h].to_vec() } else { Vec::new() }) }) .collect(); - // Rows. - let rows: Vec> = (0..h) + // Rows. Carry the chosen column's vertical site through the horizontal transform. + let rows: Vec<_> = (0..h) .into_par_iter() .map(|y| { - let f: Vec = (0..w * rep).map(|x| cols[x % w][y]).collect(); - let d = edt_1d(&f); + let f: Vec = (0..w * rep).map(|x| cols[x % w].0[y]).collect(); + let (d, sites) = edt_1d::(&f); let off = if tile { w } else { 0 }; - d[off..off + w].to_vec() + let sites = if SITES { + sites[off..off + w] + .iter() + .map(|&x| { + if x == usize::MAX { + usize::MAX + } else { + let x = x % w; + let sy = cols[x].1[y]; + if sy == usize::MAX { usize::MAX } else { (sy % h) * w + x } + } + }) + .collect() + } else { + Vec::new() + }; + (d[off..off + w].to_vec(), sites) }) .collect(); - rows.concat() + drop(cols); + let mut distances = Vec::with_capacity(w * h); + let mut sites = if SITES { Vec::with_capacity(w * h) } else { Vec::new() }; + for (row, row_sites) in rows { + distances.extend(row); + sites.extend(row_sites); + } + (distances, sites) } /// Slope (dx, dy) of a gray image by central differences, in value units per pixel. @@ -325,6 +371,51 @@ mod tests { assert_eq!(t[8], 1.0); } + #[test] + fn edt_sites_match_brute_force() { + // Exhaust all small masks, including ties and empty/full masks. Larger rectangles use + // deterministic pseudo-random masks; the oracle measures every site independently. + for (w, h) in [(1usize, 1usize), (1, 7), (7, 1), (2, 3), (3, 3), (5, 7), (8, 6)] { + let cases = if w * h <= 9 { 1usize << (w * h) } else { 128 }; + for case in 0..cases { + let mut state = case as u32 + 1; + let mask: Vec = (0..w * h) + .map(|i| { + if w * h <= 9 { + case & (1 << i) != 0 + } else { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + state.is_multiple_of(7) + } + }) + .collect(); + for tile in [false, true] { + let (d, sites) = distance_sq_with_sites(w as u32, h as u32, |i| mask[i], tile); + assert_eq!(d, distance_sq(w as u32, h as u32, |i| mask[i], tile)); + for i in 0..w * h { + let distance = |site: usize| { + let dx = (i % w).abs_diff(site % w); + let dy = (i / w).abs_diff(site / w); + let (dx, dy) = if tile { (dx.min(w - dx), dy.min(h - dy)) } else { (dx, dy) }; + (dx * dx + dy * dy) as f32 + }; + let expected = (0..mask.len()).filter(|&site| mask[site]).map(distance).reduce(f32::min); + if let Some(expected) = expected { + assert_eq!(d[i], expected, "{w}x{h}, mask {case}, tile {tile}, pixel {i}"); + assert!(sites[i] < mask.len() && mask[sites[i]]); + assert_eq!(distance(sites[i]), expected); + } else { + assert_eq!(sites[i], usize::MAX); + assert!(d[i] >= DISTANCE_INF); + } + } + } + } + } + assert!(distance_sq_with_sites(0, 3, |_| true, true).0.is_empty()); + assert!(distance_sq_with_sites(3, 0, |_| true, false).1.is_empty()); + } + #[test] fn hsl_round_trip() { let c = [0.8, 0.3, 0.1, 1.0]; diff --git a/crates/nodes/src/parameter.rs b/crates/nodes/src/parameter.rs index e15f358a..46b5112c 100644 --- a/crates/nodes/src/parameter.rs +++ b/crates/nodes/src/parameter.rs @@ -64,5 +64,10 @@ pub fn resolve_params(def: &NodeDefinition, overrides: &BTreeMap) m.insert(k.clone(), v.clone()); } } + clamp_params(def, &mut m); m } + +#[cfg(test)] +#[path = "parameter.test.rs"] +mod tests; diff --git a/crates/nodes/src/parameter.test.rs b/crates/nodes/src/parameter.test.rs new file mode 100644 index 00000000..226e9e5e --- /dev/null +++ b/crates/nodes/src/parameter.test.rs @@ -0,0 +1,58 @@ +//! Parameter resolution tests. + +use std::collections::BTreeMap; + +use materialcraft_core::Value; + +use crate::{catalog, clamp_params, find, resolve_params}; + +fn over(k: &str, v: Value) -> BTreeMap { + BTreeMap::from([(k.to_string(), v)]) +} + +#[test] +fn resolve_params_clamps_to_hard_limits() { + let def = find("blend").unwrap(); + let p = resolve_params(def, &over("opacity", Value::Float(1e30))); + assert_eq!(p["opacity"], Value::Float(17.0)); + let p = resolve_params(def, &over("opacity", Value::Float(-1e30))); + assert_eq!(p["opacity"], Value::Float(-16.0)); + let p = resolve_params(def, &over("opacity", Value::Float(f32::NAN))); + assert_eq!(p["opacity"], def.param("opacity").unwrap().default); + let levels = find("levels").unwrap(); + let p = resolve_params(levels, &over("in_low", Value::Float4([1e9, -1e9, 0.0, 1.0]))); + assert_eq!(p["in_low"], Value::Float4([17.0, -16.0, 0.0, 1.0])); +} + +#[test] +fn clamp_params_covers_values_set_after_resolution() { + let def = find("blend").unwrap(); + let mut p = resolve_params(def, &BTreeMap::new()); + p.insert("opacity".into(), Value::Float(1e9)); + clamp_params(def, &mut p); + assert_eq!(p["opacity"], Value::Float(17.0)); +} + +#[test] +fn defaults_lie_inside_their_hard_limits() { + for def in catalog() { + let p = resolve_params(def, &BTreeMap::new()); + for d in &def.params { + assert_eq!(p[d.id], d.default, "{}.{} default is outside its range", def.id, d.id); + } + } +} + +#[test] +fn manual_values_beyond_slider_and_multiple_angle_turns_survive() { + let def = find("blend").unwrap(); + assert_eq!(resolve_params(def, &over("opacity", Value::Float(1.25)))["opacity"], Value::Float(1.25)); + for def in catalog() { + for p in &def.params { + if p.angle && matches!(p.default, Value::Float(_)) { + let v = p.max + (p.max - p.min); + assert_eq!(resolve_params(def, &over(p.id, Value::Float(v)))[p.id], Value::Float(v)); + } + } + } +} diff --git a/crates/nodes/tests/distance.rs b/crates/nodes/tests/distance.rs new file mode 100644 index 00000000..2da519af --- /dev/null +++ b/crates/nodes/tests/distance.rs @@ -0,0 +1,66 @@ +use std::collections::BTreeMap; + +use materialcraft_core::Value; +use materialcraft_image::{Image, Kind}; +use materialcraft_nodes::{CookContext, find, resolve_params}; + +fn cook(mask: Image, source: Option, tile: bool, combine: bool, distance: f32) -> Image { + let def = find("distance").unwrap(); + let params = resolve_params(def, &BTreeMap::from([("distance".into(), Value::Float(distance)), ("combine".into(), Value::Bool(combine))])); + let (w, h) = (mask.w, mask.h); + let inputs = [Some(mask), source]; + let vars = BTreeMap::new(); + let resource = |_: &str| None; + let ctx = CookContext { w, h, seed: 0, tile, inputs: &inputs, params: ¶ms, resource: &resource, vars: &vars }; + (def.cook)(&ctx).unwrap().remove(0) +} + +#[test] +fn tiled_distance_spreads_source_across_stationary_gradient() { + let mask = Image::gray(32, 32, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); + let output = cook(mask.clone(), Some(mask), true, false, 256.0); + // This is within range of the only mask pixel, but the symmetric distance field has zero + // slope here. A gradient walk stopped on the black source background instead of the seed. + assert_eq!(output.get_gray(16, 16, false), 1.0); + assert!(output.data.iter().all(|&v| v == 1.0)); +} + +#[test] +fn distance_spreads_source_beyond_the_old_walk_limit() { + let mask = Image::gray(1024, 1, |x, _| if x == 0 { 1.0 } else { 0.0 }); + let output = cook(mask.clone(), Some(mask), false, false, 256.0); + assert_eq!(output.get_gray(1023, 0, false), 1.0); +} + +#[test] +fn distance_preserves_source_alpha_range_and_combine() { + for tile in [false, true] { + let mask = Image::gray(9, 3, |x, y| if x == 0 && y == 1 { 1.0 } else { 0.0 }); + let source = Image::generate(9, 3, Kind::Color, |x, y| if x == 0 && y == 1 { [0.8, 0.4, 0.2, 0.6] } else { [0.1, 0.1, 0.1, 1.0] }); + for combine in [false, true] { + let output = cook(mask.clone(), Some(source.clone()), tile, combine, 512.0 / 9.0); // two pixels + assert_eq!(output.get(0, 1, false), [0.8, 0.4, 0.2, 0.6]); + let expected = if combine { [0.4, 0.2, 0.1, 0.6] } else { [0.8, 0.4, 0.2, 0.6] }; + assert_eq!(output.get(1, 1, false), expected); + assert_eq!(output.get(4, 1, false), [0.0; 4]); + assert_eq!(output.get(8, 1, false), if tile { expected } else { [0.0; 4] }); + } + } +} + +#[test] +fn distance_handles_empty_full_masks_and_no_source() { + for tile in [false, true] { + let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]); + let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]); + let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]); + assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data.iter().all(|&v| v == 0.0)); + assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]); + assert!(cook(empty, None, tile, true, 256.0).data.iter().all(|&v| v == 0.0)); + let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 }); + let ramp = cook(mask, None, tile, false, 512.0 / 7.0); + assert_eq!(ramp.get_gray(0, 0, false), 1.0); + assert_eq!(ramp.get_gray(1, 0, false), 0.5); + assert_eq!(ramp.get_gray(3, 0, false), 0.0); + } +} diff --git a/crates/render/src/displacement.rs b/crates/render/src/displacement.rs new file mode 100644 index 00000000..b31ac1ad --- /dev/null +++ b/crates/render/src/displacement.rs @@ -0,0 +1,13 @@ +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Displacement { + /// How far white rises above black, in world units + pub depth: f32, + /// The height (0..1) that stays on the original surface + pub level: f32, + /// UV repeats of the height map + pub tiling: f32, + /// Subdivide while one more step stays within this many triangles + pub max_triangles: usize, + /// Shade with the displaced surface's normals instead of the original ones + pub shade_relief: bool, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4d42125f..25e484f3 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9,4 +9,9 @@ pub mod ibl; pub mod preview; -pub use preview::{Lighting, Maps, Scene, Settings, builtin_mesh, pan, render, render_cancellable}; +mod displacement; +mod relief; +pub use displacement::Displacement; +pub use relief::Relief; + +pub use preview::{Lighting, Maps, Scene, Settings, VIEW_TRIANGLES, builtin_mesh, pan, render, render_cancellable}; diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 5ae587d4..a7fca3bf 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -1,12 +1,13 @@ //! The 3D view's renderer: one ray per pixel (plus 2×2 supersampling when idle) against the -//! scene mesh's BVH, the material's maps sampled with tiling and parallax occlusion from the -//! height output, then metallic/roughness GGX shading under image-based light (SH diffuse, -//! prefiltered specular, an analytic environment BRDF), exposure and ACES tone mapping. +//! scene mesh's BVH, the material's maps sampled with tiling, then metallic/roughness GGX shading +//! under image-based light (SH diffuse, prefiltered specular, an analytic environment BRDF), +//! exposure and ACES tone mapping. The height output displaces real geometry ([`Scene::with_relief`]). use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use crate::{Displacement, Relief}; use materialcraft_geom::glam::{Vec2, Vec3}; use materialcraft_geom::{Bvh, Mesh, OrbitCamera}; use materialcraft_image::{Image, linear_to_srgb}; @@ -82,37 +83,75 @@ impl Scene { Scene::new(builtin_mesh(id)) } - /// `base` subdivided to at most `max_tris` triangles and pushed along its normals by - /// `depth × (height − 0.5)` (the height map repeated `tiling` times): real silhouettes and - /// self-occlusion for offline renders. Coincident vertices (UV seams, hard edges) move - /// together, so the surface stays closed. - pub fn displaced(base: &Mesh, height: &Image, tiling: f32, depth: f32, max_tris: usize) -> Scene { + /// `base` subdivided and moved along its normals by `depth × (height − level)`; vertices at one spot move together so it stays closed. + pub fn displaced(base: &Mesh, height: &Image, displacement: &Displacement) -> Scene { let mut mesh = base.clone(); if mesh.normals.len() != mesh.positions.len() { mesh.compute_normals(); } - while mesh.triangle_count() > 0 && mesh.triangle_count() * 4 <= max_tris { + while mesh.triangle_count() > 0 && mesh.triangle_count() * 4 <= displacement.max_triangles { mesh = mesh.subdivided(); } - // Pre-filtered so fine detail (left to the normal map) does not spike the silhouette. + + // Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette let height = height.resize(height.w.min(512), height.h.min(512), true); - let key = |p: Vec3| (p * 1e4).round().as_ivec3().to_array(); - let mut welded: HashMap<[i32; 3], (Vec3, f32, f32)> = HashMap::new(); - for ((p, n), uv) in mesh.positions.iter().zip(&mesh.normals).zip(&mesh.uvs) { - let e = welded.entry(key(*p)).or_default(); - e.0 += *n; - e.1 += height.sample_gray(uv.x * tiling, uv.y * tiling, true); - e.2 += 1.0; + let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 }; + let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 }; + let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 }; + + // Vertices at the same spot (to 0.1 mm) are one point of the surface + let spots: Vec<[i32; 3]> = mesh.positions.iter().map(|p| (*p * 1e4).round().as_ivec3().to_array()).collect(); + let mut spot_sums: HashMap<[i32; 3], (Vec3, f32, f32)> = HashMap::new(); + for ((spot, n), uv) in spots.iter().zip(&mesh.normals).zip(&mesh.uvs) { + let (normal_sum, height_sum, count) = spot_sums.entry(*spot).or_default(); + *normal_sum += *n; + *height_sum += height.sample_gray(uv.x * tiling, uv.y * tiling, true); + *count += 1.0; } - for p in &mut mesh.positions { - if let Some((n, h, count)) = welded.get(&key(*p)) { - *p += n.normalize_or_zero() * depth * (h / count - 0.5); + let offsets: Vec = + spots.iter().map(|spot| spot_sums.get(spot).map_or(Vec3::ZERO, |(n, h, count)| n.normalize_or_zero() * depth * (h / count - level))).collect(); + + if displacement.shade_relief { + // Normals of the displaced surface, shared per spot so seams don't show + let moved = |i: u32| mesh.positions.get(i as usize).zip(offsets.get(i as usize)).map(|(p, o)| *p + *o); + let mut face_sums: HashMap<[i32; 3], Vec3> = HashMap::new(); + for triangle in mesh.indices.chunks_exact(3) { + let (Some(a), Some(b), Some(c)) = (moved(triangle[0]), moved(triangle[1]), moved(triangle[2])) else { continue }; + let face = (b - a).cross(c - a); + for spot in triangle.iter().filter_map(|&i| spots.get(i as usize)) { + *face_sums.entry(*spot).or_default() += face; + } } + for (spot, n) in spots.iter().zip(mesh.normals.iter_mut()) { + if let Some(sum) = face_sums.get(spot).and_then(|s| s.try_normalize()) { + *n = sum; + } + } + mesh.tangents.clear(); + } + + for (p, offset) in mesh.positions.iter_mut().zip(&offsets) { + *p += *offset; } Scene::new(mesh) } + + /// The scene the 3D view shows for `maps`: displaced by the height output, or `None` when nothing moves. + pub fn with_relief(&self, maps: &Maps, relief: Relief, tiling: f32, max_triangles: usize) -> Option { + let height = maps.height.as_ref()?; + if !(relief.depth.is_finite() && relief.depth > 0.0) { + return None; + } + + // Without a normal map the displaced surface's own normals show the relief + let displacement = Displacement { depth: relief.depth * self.radius, level: relief.level, tiling, max_triangles, shade_relief: maps.normal.is_none() }; + Some(Scene::displaced(&self.mesh, height, &displacement)) + } } +/// Triangle budget of a displaced scene in the interactive 3D view (builds in about 0.2–0.3 s on two cores). +pub const VIEW_TRIANGLES: usize = 500_000; + /// A built-in mesh by id; unknown ids give the rounded cube. pub fn builtin_mesh(id: &str) -> Mesh { let mut m = materialcraft_geom::primitives::builtin(id).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15)); @@ -173,8 +212,8 @@ pub struct Settings { pub exposure: f32, /// Degrees. pub env_rotation: f32, - /// Parallax depth in UV units (0 = off). - pub height_scale: f32, + /// Interpret the green channel as DirectX (-Y) instead of OpenGL (+Y). + pub normal_y_flip: bool, /// Show the (blurred) environment behind the mesh instead of the flat backdrop. pub show_env: bool, /// 1 = one ray per pixel, 2 = 2×2 supersampling. @@ -201,7 +240,7 @@ impl Default for Settings { tiling: 1.0, exposure: 0.0, env_rotation: 0.0, - height_scale: 0.03, + normal_y_flip: false, show_env: false, supersample: 1, ao_rays: 0, @@ -348,36 +387,8 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec let tan = (tan - nrm * nrm.dot(tan)).normalize_or_zero(); let bit = nrm.cross(tan) * sign; let uv0 = *m.uvs.get(i0)? * w0 + *m.uvs.get(i1)? * w1 + *m.uvs.get(i2)? * w2; - let mut uv = uv0 * s.tiling; + let uv = uv0 * s.tiling; let v = -dir; - // Parallax occlusion: march the height field along the view direction in tangent space. - if s.height_scale > 0.0 - && let Some(h) = &maps.height - { - let vt = Vec3::new(v.dot(tan), v.dot(bit), v.dot(nrm).max(0.05)); - let steps = 32; - let delta = Vec2::new(vt.x, -vt.y) / vt.z * s.height_scale * s.tiling / steps as f32; - let mut layer = 1.0; - let mut cur = uv; - let mut prev_h = h.sample_gray(cur.x, cur.y, true); - let mut prev_layer = layer; - for _ in 0..steps { - let hv = h.sample_gray(cur.x, cur.y, true); - if hv >= layer { - // Linear refinement between the last two samples. - let a = prev_h - prev_layer; - let b = hv - layer; - let t = if (b - a).abs() > 1e-6 { a / (a - b) } else { 0.0 }; - cur -= delta * (1.0 - t.clamp(0.0, 1.0)); - break; - } - prev_h = hv; - prev_layer = layer; - layer -= 1.0 / steps as f32; - cur -= delta; - } - uv = cur; - } let a = alpha(maps, uv); if s.alpha_view { return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t }); @@ -388,7 +399,10 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec let ao = tex_gray(&maps.ao, uv, 1.0).clamp(0.0, 1.0); let n = match tex(&maps.normal, uv) { Some(c) => { - let t = Vec3::new(c[0] * 2.0 - 1.0, c[1] * 2.0 - 1.0, c[2] * 2.0 - 1.0); + let mut t = Vec3::new(c[0] * 2.0 - 1.0, c[1] * 2.0 - 1.0, c[2] * 2.0 - 1.0); + if s.normal_y_flip { + t.y = -t.y; + } // OpenGL convention: green points along +v in texture space, which is -bitangent // with top-left UVs. (tan * t.x - bit * t.y + nrm * t.z.max(0.05)).normalize_or_zero() @@ -568,6 +582,80 @@ mod tests { assert_eq!(&px[c..c + 3], &[255, 255, 255]); } + fn flat(value: f32) -> Image { + Image::filled(8, 8, Kind::Gray, [value; 4]) + } + + fn displacement(depth: f32, level: f32) -> Displacement { + Displacement { depth, level, tiling: 1.0, max_triangles: 2048, shade_relief: false } + } + + /// Heights of a displaced plane's vertices (it faces +y and starts at y = 0). + fn plane_heights(height: &Image, displacement: &Displacement) -> Vec { + let plane = materialcraft_geom::primitives::plane(2.0, 4); + Scene::displaced(&plane, height, displacement).mesh.positions.iter().map(|p| p.y).collect() + } + + /// At level 0 the relief rises out of the surface: black stays on it and nothing sinks in. + #[test] + fn the_relief_rises_out_of_the_surface() { + let near = |heights: Vec, expected: f32| heights.iter().all(|y| (y - expected).abs() < 1e-5); + + assert!(near(plane_heights(&flat(0.0), &displacement(0.2, 0.0)), 0.0), "black stays on the surface"); + assert!(near(plane_heights(&flat(1.0), &displacement(0.2, 0.0)), 0.2), "white rises by the depth"); + assert!(near(plane_heights(&flat(0.5), &displacement(0.2, 0.5)), 0.0), "the level height stays on the surface"); + assert!(near(plane_heights(&flat(0.0), &displacement(0.2, 0.5)), -0.1), "below the level sinks"); + assert!(near(plane_heights(&flat(1.0), &displacement(0.2, f32::NAN)), 0.2), "a broken level reads as 0"); + } + + /// Vertices at one spot (UV seams, hard edges) move together, so a displaced cube stays closed. + #[test] + fn a_displaced_cube_stays_closed() { + // No subdivision, so vertex i of the result is vertex i of the cube + let cube = builtin_mesh("cube"); + let ramp = Image::gray(32, 32, |x, y| ((x + y) % 32) as f32 / 31.0); + let displaced = Scene::displaced(&cube, &ramp, &Displacement { max_triangles: 0, ..displacement(0.1, 0.0) }); + assert_eq!(displaced.mesh.positions.len(), cube.positions.len()); + + let spot = |p: Vec3| (p * 1e4).round().as_ivec3().to_array(); + let mut moved_to: HashMap<[i32; 3], Vec3> = HashMap::new(); + for (before, after) in cube.positions.iter().zip(&displaced.mesh.positions) { + let first = *moved_to.entry(spot(*before)).or_insert(*after); + assert!((first - *after).length() < 1e-4, "{before:?} split into {first:?} and {after:?}"); + } + } + + /// Without a normal map the displaced surface's own normals shade the relief; with one, the original normals stay. + #[test] + fn relief_normals_follow_the_displaced_surface_only_when_asked() { + let plane = materialcraft_geom::primitives::plane(2.0, 8); + let slope = Image::gray(16, 16, |x, _| x as f32 / 15.0); + let tilted = |shade_relief| { + let scene = Scene::displaced(&plane, &slope, &Displacement { shade_relief, ..displacement(0.5, 0.0) }); + scene.mesh.normals.iter().map(|n| n.x.abs()).fold(0.0f32, f32::max) + }; + + assert!(tilted(true) > 0.1, "a slope tilts the normals"); + assert!(tilted(false) < 1e-5, "the original normals are kept"); + } + + #[test] + fn with_relief_needs_a_height_output_and_a_depth() { + let scene = Scene::builtin("plane"); + let maps = Maps { height: Some(flat(1.0)), ..Maps::default() }; + let relief = Relief { depth: 0.1, level: 0.0 }; + + assert!(scene.with_relief(&Maps::default(), relief, 1.0, 2048).is_none()); + for depth in [0.0, -1.0, f32::NAN] { + assert!(scene.with_relief(&maps, Relief { depth, ..relief }, 1.0, 2048).is_none(), "{depth}"); + } + + // The depth is in scene radii + let raised = scene.with_relief(&maps, relief, 1.0, 2048).unwrap(); + let top = raised.mesh.positions.iter().map(|p| p.y).fold(f32::MIN, f32::max); + assert!((top - 0.1 * scene.radius).abs() < 1e-4, "{top} vs {}", 0.1 * scene.radius); + } + #[test] fn a_cancelled_render_gives_up_and_an_uncancelled_one_matches_render() { let (scene, light, maps, s) = (Scene::builtin("sphere"), Lighting::new("studio"), Maps::default(), Settings::default()); diff --git a/crates/render/src/relief.rs b/crates/render/src/relief.rs new file mode 100644 index 00000000..ed3f01f9 --- /dev/null +++ b/crates/render/src/relief.rs @@ -0,0 +1,7 @@ +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Relief { + /// How far white rises above black, in scene radii; 0 = off + pub depth: f32, + /// The height (0..1) that stays on the original surface: 0 = everything rises out of it + pub level: f32, +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2d92d217..b99fb84b 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -208,6 +208,23 @@ pub fn parse_events(list: &[Value]) -> Result, String> { Ok(frames) } +/// Recursive JSON merge: objects merge key by key, anything else in `patch` replaces `dst`. +fn merge_json(dst: &mut Value, patch: &Value) { + match (dst, patch) { + (Value::Object(d), Value::Object(p)) => { + for (k, v) in p { + match d.get_mut(k) { + Some(slot) => merge_json(slot, v), + None => { + d.insert(k.clone(), v.clone()); + } + } + } + } + (slot, v) => *slot = v.clone(), + } +} + pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value { match method { "ping" => ok(json!("pong")), @@ -225,8 +242,13 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: "command.run" => { 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) { + match crate::cook::guard("command request", || { + materialcraft_engine::commands::execute_request(&mut app.session, id, ¶ms).map_err(|error| error.to_string()) + }) { Ok(v) => { + if id == "view.previewSize" { + app.ui.prefs.preview_size = app.session.preview_size.unwrap_or(0); + } app.close_subgraph_after(id); ok(v) } @@ -283,13 +305,14 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: } "ui.set" => { let mut cur = serde_json::to_value(&app.ui).unwrap_or(Value::Null); - if let (Some(obj), Some(patch)) = (cur.as_object_mut(), p.as_object()) { - for (k, v) in patch { - obj.insert(k.clone(), v.clone()); - } + if p.is_object() { + merge_json(&mut cur, p); } - match serde_json::from_value(cur) { - Ok(ui) => { + match serde_json::from_value::(cur) { + Ok(mut ui) => { + ui.graph_camera = ui.graph_camera.sanitized(); + ui.image_camera = ui.image_camera.sanitized(); + ui.windows.unsaved = app.ui.windows.unsaved.clone(); app.ui = ui; ok(Value::Null) } @@ -339,4 +362,33 @@ mod tests { assert!(parse_events(&[json!({"type": "click"})]).is_err()); assert!(parse_events(&[json!({"pos": [1, 2]})]).is_err()); } + + fn app() -> MaterialCraftApp { + MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::state::UiState::default()) + } + + #[test] + fn ui_set_merges_nested_objects_instead_of_resetting_siblings() { + let mut app = app(); + let ctx = egui::Context::default(); + app.ui.prefs.ui_scale = 1.5; + app.ui.prefs.autosave_minutes = 9; + let r = handle(&mut app, &ctx, "ui.set", &json!({"prefs": {"thumbnails": false}})); + assert_eq!(r["ok"], json!(true), "{r}"); + assert!(!app.ui.prefs.thumbnails); + assert_eq!(app.ui.prefs.ui_scale, 1.5); + assert_eq!(app.ui.prefs.autosave_minutes, 9); + } + + #[test] + fn ui_set_clamps_camera_zoom() { + let mut app = app(); + let ctx = egui::Context::default(); + let r = handle(&mut app, &ctx, "ui.set", &json!({"graphCamera": {"zoom": 0.0}, "imageCamera": {"zoom": 0.0, "fit": false}})); + assert_eq!(r["ok"], json!(true), "{r}"); + assert!(app.ui.graph_camera.zoom > 0.0); + assert!(app.ui.image_camera.zoom > 0.0); + let c = &app.ui.graph_camera; + assert!((c.pan[0] + 100.0 / c.zoom).is_finite()); + } } diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index f2828a94..28d18ced 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -1,20 +1,50 @@ //! Background cooking: when the open graph changes, a worker thread cooks a snapshot of the -//! package through the shared cache while the UI keeps drawing the previous results. +//! package through the shared cache while the UI keeps drawing the previous results +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::mpsc::{Receiver, TryRecvError}; use materialcraft_engine::PreviewCook; +use materialcraft_engine::eval::{Cooked, NodeResult}; use crate::MaterialCraftApp; +/// Run `f`, turning a panic into an error naming `what`, so one bad node or command can't take +/// the app (and unsaved work) down +pub fn guard(what: &str, f: impl FnOnce() -> Result) -> Result { + catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|p| { + let msg = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); + Err(format!("internal error in {what}: {msg}")) + }) +} + +/// Run an engine command; a panic inside it becomes an error reply (the session is kept) +pub fn execute_guarded(session: &mut materialcraft_engine::Session, id: &str, params: &serde_json::Value) -> Result { + guard(&format!("command `{id}`"), || materialcraft_engine::execute(session, id, params).map_err(|e| e.to_string())) +} + +/// A cook that crashed or died: every node of the open graph shows the error instead of stale +/// previews, and the user sees a toast +fn report_failure(app: &mut MaterialCraftApp, msg: String) { + let ids: Vec<_> = app.session.graph().map(|g| g.nodes.iter().map(|n| n.id).collect()).unwrap_or_default(); + let mut cooked = Cooked::default(); + for id in ids { + cooked.nodes.insert(id, NodeResult { outputs: Default::default(), error: Some(msg.clone()), ms: 0.0, key: 0, cached: false }); + } + app.session.accept_preview(PreviewCook { graph: app.session.graph, cooked, ..Default::default() }); + app.toast(msg, true); +} + #[derive(Default)] pub struct Cooker { - rx: Option>, - /// Stops the running cook between nodes once its result is stale. + 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). + /// When the running cook started (app seconds) pub started: Option, + /// `Session::cook_epoch` when the running cook started + epoch: u64, } impl Cooker { @@ -23,28 +53,37 @@ impl Cooker { } } -/// Collect a finished cook and start the next one if the graph changed. +/// Collect a finished cook and start the next one if the graph changed 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() { - // A stopped cook is partial: keep the previous results and cook again. - app.session.dirty = true; - } else if !app.session.dirty { - app.session.accept_preview(c); - } + Ok(result) => { app.cooker.rx = None; app.cooker.started = None; #[cfg(not(target_arch = "wasm32"))] { app.cooker.cancel = None; } + match result { + // A stopped cook is partial: keep the previous results and cook again + Ok(c) if c.cancelled() => { + if app.cooker.epoch == app.session.cook_epoch { + app.session.dirty = true; + } + } + Ok(c) => { + if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { + app.session.accept_preview(c); + } + } + Err(msg) if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch => report_failure(app, msg), + Err(_) => {} + } ctx.request_repaint(); } Err(TryRecvError::Empty) if app.session.dirty => { // Stop between nodes, but wait for this worker to finish before starting - // another. A slow node must not accumulate workers during rapid edits. + // another. A slow node must not accumulate workers during rapid edits #[cfg(not(target_arch = "wasm32"))] if let Some(flag) = &app.cooker.cancel { flag.store(true, std::sync::atomic::Ordering::Relaxed); @@ -59,6 +98,9 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { Err(TryRecvError::Disconnected) => { app.cooker.rx = None; app.cooker.started = None; + if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch { + report_failure(app, "the cook worker stopped unexpectedly".into()); + } #[cfg(not(target_arch = "wasm32"))] { app.cooker.cancel = None; @@ -80,6 +122,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let (gi, max) = (s.graph, s.preview_size); let materials = s.material_preview.graphs(); let cache = s.cache.clone(); + let epoch = s.cook_epoch; let dec = s.resource_decoder(); let (tx, rx) = std::sync::mpsc::channel(); let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -89,28 +132,43 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let mut opts = Options::new(&dec); opts.max_size = max; opts.cancel = Some(&thread_flag); - let cooked = PreviewCook::run(&pkg, gi, &materials, &opts, &cache); + let cooked = guard("cook", || Ok(PreviewCook::run(&pkg, gi, &materials, &opts, &cache))); let _ = tx.send(cooked); }); match spawned { Ok(_) => { app.cooker.rx = Some(rx); + app.cooker.epoch = epoch; app.cooker.cancel = Some(flag); app.cooker.started = Some(now); } Err(e) => { log::warn!("could not start a cook thread ({e}); cooking here"); - app.session.cook(); + cook_here(app); } } } +fn cook_here(app: &mut MaterialCraftApp) { + if let Err(msg) = guard("cook", || { + app.session.cook(); + Ok(()) + }) { + app.session.dirty = false; + report_failure(app, msg); + } +} + #[cfg(target_arch = "wasm32")] fn start(app: &mut MaterialCraftApp, _now: f64) { - // shortcut: no threads on the web; the cook runs on the UI thread (the page pauses). - app.session.cook(); + // shortcut: no threads on the web; the cook runs on the UI thread (the page pauses) + cook_here(app); } +#[cfg(test)] +#[path = "cook.test.rs"] +mod tests; + #[cfg(all(test, not(target_arch = "wasm32")))] #[path = "cook_cancellation.test.rs"] mod cancellation_tests; diff --git a/crates/ui-egui/src/cook.test.rs b/crates/ui-egui/src/cook.test.rs new file mode 100644 index 00000000..8438cede --- /dev/null +++ b/crates/ui-egui/src/cook.test.rs @@ -0,0 +1,111 @@ +#[cfg(test)] +mod cook_tests { + use crate::MaterialCraftApp; + use crate::cook::{drive, start}; + use crate::state::UiState; + use materialcraft_engine::{execute, sample_session}; + use serde_json::json; + + fn wait_and_drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { + for _ in 0..2000 { + drive(app, ctx); + if !app.cooker.busy() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("background cook never finished"); + } + + /// A background cook of version A lands after a synchronous cook of version B (as in + /// `session.inspect`): B's results must survive. + #[test] + fn stale_background_cook_does_not_overwrite_newer_sync_cook() { + let mut session = sample_session(); + session.preview_size = Some(64); + let mut app = MaterialCraftApp::headless(session, UiState::default()); + let ctx = egui::Context::default(); + + start(&mut app, 0.0); // cook of version A runs in the background + let added = execute(&mut app.session, "graph.node.add", &json!({"def": "uniform", "at": [0, 0]})).unwrap(); + let id = materialcraft_engine::core::NodeId(added["id"].as_u64().unwrap()); + assert!(app.session.dirty); + app.session.cook_if_dirty(); // version B cooked synchronously, dirty cleared + assert!(app.session.cooked.nodes.contains_key(&id)); + + wait_and_drive(&mut app, &ctx); + assert!(app.session.cooked.nodes.contains_key(&id), "stale cook replaced the newer results"); + } +} + +#[cfg(test)] +mod worker_failure_tests { + use crate::MaterialCraftApp; + use crate::cook::{drive, guard}; + use crate::state::UiState; + use materialcraft_engine::PreviewCook; + use materialcraft_engine::sample_session; + + fn app() -> MaterialCraftApp { + let mut session = sample_session(); + session.preview_size = Some(64); + session.cook(); + MaterialCraftApp::headless(session, UiState::default()) + } + + #[test] + fn guard_turns_a_panic_into_an_error() { + let r: Result = guard("test", || -> Result { panic!("boom") }); + let e = r.unwrap_err(); + assert!(e.contains("boom"), "{e}"); + assert_eq!(guard("test", || Ok::<_, String>(7)).unwrap(), 7); + } + + #[test] + fn a_panicked_cook_worker_reports_errors_on_every_node() { + let mut app = app(); + assert!(app.session.cook_failures().0.is_empty()); + let (tx, rx) = std::sync::mpsc::channel::>(); + app.cooker.rx = Some(rx); + app.cooker.epoch = app.session.cook_epoch; + tx.send(Err("boom".into())).unwrap(); + app.session.dirty = false; + drive(&mut app, &egui::Context::default()); + assert!(!app.cooker.busy()); + let (failed, _) = app.session.cook_failures(); + assert!(!failed.is_empty()); + assert!(failed.iter().all(|(_, e)| e.contains("boom"))); + assert!(app.toasts.iter().any(|t| t.error && t.text.contains("boom"))); + } + + #[test] + fn a_dead_cook_worker_is_reported_not_silent() { + let mut app = app(); + let (tx, rx) = std::sync::mpsc::channel::>(); + app.cooker.rx = Some(rx); + app.cooker.epoch = app.session.cook_epoch; + drop(tx); + app.session.dirty = false; + drive(&mut app, &egui::Context::default()); + assert!(!app.cooker.busy()); + assert!(app.toasts.iter().any(|t| t.error)); + assert!(!app.session.cook_failures().0.is_empty()); + } +} + +#[test] +fn stale_worker_failure_does_not_replace_a_newer_sync_cook() { + let mut session = materialcraft_engine::sample_session(); + session.preview_size = Some(64); + session.cook(); + let mut app = crate::MaterialCraftApp::headless(session, crate::UiState::default()); + let (tx, rx) = std::sync::mpsc::channel(); + app.cooker.rx = Some(rx); + app.cooker.epoch = app.session.cook_epoch.wrapping_sub(1); + tx.send(Err("stale failure".into())).unwrap(); + let count = app.session.cooked.nodes.len(); + crate::cook::drive(&mut app, &egui::Context::default()); + assert_eq!(app.session.cooked.nodes.len(), count); + assert!(app.session.cook_failures().0.is_empty()); + assert!(app.toasts.is_empty()); +} diff --git a/crates/ui-egui/src/cook_cancellation.test.rs b/crates/ui-egui/src/cook_cancellation.test.rs index cb4ab3db..3887ebb8 100644 --- a/crates/ui-egui/src/cook_cancellation.test.rs +++ b/crates/ui-egui/src/cook_cancellation.test.rs @@ -6,13 +6,14 @@ use std::sync::{ mpsc, }; -fn waiting() -> (MaterialCraftApp, mpsc::Sender, Arc) { +fn waiting() -> (MaterialCraftApp, mpsc::Sender>, Arc) { let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); app.session.cook(); app.session.cooked.ms = 123.0; let (tx, rx) = mpsc::channel(); let flag = Arc::new(AtomicBool::new(false)); app.cooker.rx = Some(rx); + app.cooker.epoch = app.session.cook_epoch; app.cooker.cancel = Some(flag.clone()); (app, tx, flag) } @@ -27,7 +28,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(PreviewCook { cooked: Cooked { cancelled: true, ..Default::default() }, ..Default::default() }).unwrap(); + tx.send(Ok(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"); @@ -36,7 +37,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(PreviewCook { cooked: Cooked { ms: 7.0, ..Default::default() }, ..Default::default() }).unwrap(); + tx.send(Ok(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/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index c876e19b..2774fede 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -6,6 +6,7 @@ use super::{ wire_geometry::{bezier, bezier_points, wire_at}, }; use super::{node_card, node_card::port as port_pos, node_layout::NodeLayout}; +use crate::i18n::tr; use crate::{MaterialCraftApp, theme::Tokens}; use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; use egui_phosphor::regular as icon; @@ -222,7 +223,21 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { 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); + let format = format!("{}{bits}", if img.is_gray() { "L" } else { "C" }); + let txt = if let Some(limit) = app.session.preview_size { + let [width, height] = graph.size_px(); + resp.clone().on_hover_text(format!( + "{} x {} ({bits}bpc)\n{}: {width} x {height}\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(), theme.text_dim); } if node.def == "output" { diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs index cbc75a0f..472969c6 100644 --- a/crates/ui-egui/src/graph/graph_camera.rs +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -32,7 +32,7 @@ impl GraphCamera { } pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect) { - self.zoom = self.zoom.clamp(0.08, 4.0); + self.zoom = self.zoom.clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); if !ui.rect_contains_pointer(view) { return; } @@ -42,7 +42,7 @@ impl GraphCamera { 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.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); self.pan = before.to_vec2() - (pointer - self.origin) / self.zoom; } } diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index 64642993..fe7a93c3 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -56,3 +56,7 @@ pub(crate) mod editor_target; pub(crate) mod gesture; pub(crate) mod canvas_geometry; + +pub use navigation::import_bitmap_bytes; +#[cfg(not(target_arch = "wasm32"))] +pub use navigation::import_bitmap_file; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs index 46bf08f2..04d9f9e7 100644 --- a/crates/ui-egui/src/graph/navigation.rs +++ b/crates/ui-egui/src/graph/navigation.rs @@ -46,3 +46,37 @@ pub(super) fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool } app.ui.graph_camera = super::GraphCamera::fit(view, r).state(); } + +/// Import the resource and its graph node in one atomic undo entry +fn import_bitmap(app: &mut MaterialCraftApp, import: impl FnOnce(&mut materialcraft_engine::Session) -> materialcraft_engine::Result) { + let center = view_center(app); + let snap = app.ui.prefs.snap_to_grid; + let result = app.session.group("Import bitmap", |session| { + let resource = import(session)?; + materialcraft_engine::execute( + session, + "graph.node.add", + &json!({ + "def": "bitmap", "at": [center.x - NODE_W * 0.5, center.y - 60.0], + "snapToGrid": snap, "params": {"resource": resource} + }), + )?; + Ok(resource) + }); + match result { + Ok(resource) => app.toast(format!("{} {resource}", crate::i18n::tr("Imported")), false), + Err(error) => app.toast(error.to_string(), true), + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn import_bitmap_file(app: &mut MaterialCraftApp, path: &str) { + import_bitmap(app, |session| { + let result = materialcraft_engine::execute(session, "file.importBitmap", &json!({"path": path}))?; + Ok(result["name"].as_str().unwrap_or_default().to_string()) + }); +} + +pub fn import_bitmap_bytes(app: &mut MaterialCraftApp, name: &str, bytes: Vec) { + import_bitmap(app, |session| materialcraft_engine::file_cmds::add_resource(session, name, bytes, None)); +} diff --git a/crates/ui-egui/src/graph/search.rs b/crates/ui-egui/src/graph/search.rs index 3ce3d587..adc1a46f 100644 --- a/crates/ui-egui/src/graph/search.rs +++ b/crates/ui-egui/src/graph/search.rs @@ -36,6 +36,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { 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); + let mut reveal_selection = s.focus; 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)); @@ -46,6 +47,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { } if r.changed() { s.sel = 0; + reveal_selection = true; } }); let list = matches(&s.text); @@ -65,12 +67,13 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) { 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)) + .min_size(egui::vec2(ui.available_width(), 0.0)) .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), ); - if i == s.sel && (up || down) { + if i == s.sel && (up || down || reveal_selection) { r.scroll_to_me(None); } if r.clicked() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8f3d144b..39d1e5f4 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -110,33 +110,6 @@ pub fn os_language() -> &'static str { 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"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9b6eaa26..a8126fed 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,12 +16,14 @@ pub mod library; mod material_preview_menu; mod menu_item; pub mod menus; +mod preview_resolution; #[path = "property/mod.rs"] pub mod properties; pub mod state; pub mod theme; pub mod thumbs; pub mod toolbar; +pub mod unsaved; mod value_input_editor; pub mod view2d; pub mod view3d; diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 8739b835..af2bbbbc 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -32,6 +32,8 @@ pub struct MaterialCraftApp { pub ui_ms: f32, /// The last status message (bottom left) pub status: String, + pub(crate) pending_load: Option<(String, Vec)>, + pub(crate) quit_confirmed: bool, last_time: f64, #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, @@ -77,6 +79,8 @@ impl MaterialCraftApp { fps: 0.0, ui_ms: 0.0, status: String::new(), + pending_load: None, + quit_confirmed: false, last_time: 0.0, next_autosave, styled: None, @@ -96,8 +100,7 @@ impl MaterialCraftApp { } 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; + let _ = materialcraft_engine::execute(&mut self.session, "view.previewSize", &serde_json::json!({"size": p.unwrap_or(0)})); } } @@ -123,8 +126,11 @@ impl MaterialCraftApp { } } - match materialcraft_engine::execute(&mut self.session, id, ¶ms) { + match cook::execute_guarded(&mut self.session, id, ¶ms) { Ok(v) => { + if id == "view.previewSize" { + self.ui.prefs.preview_size = self.session.preview_size.unwrap_or(0); + } self.close_subgraph_after(id); if matches!(id, "view.3d.assign" | "view.3d.outputs") { self.ui.dock.focus(docking::Panel::View3d); @@ -245,12 +251,13 @@ 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 { + if (ctx.zoom_factor() - scale).abs() > 1e-3 && !ctx.input(|input| input.pointer.any_down()) { ctx.set_zoom_factor(scale); } if ctx.input(|input| input.pointer.any_pressed()) { self.session.finish_edit(); } + crate::unsaved::handle_close(self, ctx); control::poll(self, ctx); web_files::poll(self); for f in ctx.input(|i| i.raw.dropped_files.clone()) { @@ -294,3 +301,7 @@ impl MaterialCraftApp { self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; } } + +#[cfg(test)] +#[path = "material_craft_app.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/material_craft_app.test.rs b/crates/ui-egui/src/material_craft_app.test.rs new file mode 100644 index 00000000..2c32f827 --- /dev/null +++ b/crates/ui-egui/src/material_craft_app.test.rs @@ -0,0 +1,74 @@ +#[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; + + #[test] + fn run_reports_errors_as_toasts_and_keeps_the_session() { + let mut app = MaterialCraftApp::headless(sample_session(), UiState::default()); + assert!(app.run("no.such.command", json!({})).is_none()); + 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::{MaterialCraftApp, state::UiState}; + + fn app(modified: bool) -> MaterialCraftApp { + let mut s = materialcraft_engine::sample_session(); + s.modified = modified; + MaterialCraftApp::headless(s, UiState::default()) + } + + #[test] + fn closing_all_over_unsaved_work_waits_for_an_answer() { + let mut a = app(true); + let before = a.session.pkg.name.clone(); + 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`). + let v = serde_json::to_value(&a.ui).unwrap(); + assert_eq!(v["windows"]["unsaved"]["kind"], "menu"); + } + + #[test] + fn closing_all_over_a_clean_package_just_happens() { + let mut a = app(false); + guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); + assert!(a.ui.windows.unsaved.is_none()); + 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); + guard(&mut a, Guarded::Quit); + let saved = serde_json::to_string(&a.ui).unwrap(); + let back: UiState = serde_json::from_str(&saved).unwrap(); + assert!(back.windows.unsaved.is_none()); + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index cecf4920..bcbaa5f2 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -150,9 +150,8 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { "ui.preferences" => app.ui.windows.preferences = true, "ui.view.graph" => {} "ui.resetLayout" => app.ui.dock = crate::docking::Dock::default(), - "ui.closeAll" => { - app.run("file.newPackage", Value::Null); - } + // These replace the open package: ask first when it has unsaved changes. + "ui.closeAll" | "file.newPackage" => crate::unsaved::guard(app, crate::unsaved::Guarded::Menu { id: id.to_string() }), "ui.reloadResources" | "ui.clearCache" => { if let Ok(mut c) = app.session.cache.lock() { c.clear(); diff --git a/crates/ui-egui/src/preview_resolution.rs b/crates/ui-egui/src/preview_resolution.rs new file mode 100644 index 00000000..de82c5ad --- /dev/null +++ b/crates/ui-egui/src/preview_resolution.rs @@ -0,0 +1,31 @@ +use crate::{MaterialCraftApp, i18n::tr}; +use egui::Ui; + +const SIZES: [u32; 6] = [256, 512, 1024, 2048, 4096, 0]; + +pub(crate) fn label(size: u32) -> String { + if size == 0 { tr("Full size").to_string() } else { format!("{size} px") } +} + +pub(crate) fn choices(ui: &mut Ui, size: &mut u32) -> bool { + let mut changed = false; + for option in SIZES { + changed |= ui.selectable_value(size, option, label(option)).changed(); + } + changed +} + +pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { + let mut size = app.session.preview_size.unwrap_or(0); + let response = egui::ComboBox::from_id_salt("preview_resolution") + .selected_text(label(size)) + .width(85.0) + .show_ui(ui, |ui| { + if choices(ui, &mut size) { + app.run("view.previewSize", serde_json::json!({"size": size})); + } + }) + .response; + crate::widgets::name(&response, egui::Role::ComboBox, "Preview resolution"); + response.on_hover_text(tr("Preview size while editing")); +} diff --git a/crates/ui-egui/src/state/graph_camera.rs b/crates/ui-egui/src/state/graph_camera.rs index 9f9a9654..b34febb6 100644 --- a/crates/ui-egui/src/state/graph_camera.rs +++ b/crates/ui-egui/src/state/graph_camera.rs @@ -7,6 +7,19 @@ pub struct GraphCamera { pub zoom: f32, } +impl GraphCamera { + pub const ZOOM: (f32, f32) = (0.08, 4.0); + + /// The camera with a finite pan and a zoom inside [`Self::ZOOM`] (state set from outside can + /// hold a zoom of 0 or NaN, which the view divides by). + pub fn sanitized(self) -> GraphCamera { + let d = GraphCamera::default(); + let pan = |v: f32, d: f32| if v.is_finite() { v.clamp(-1.0e9, 1.0e9) } else { d }; + let zoom = if self.zoom.is_finite() { self.zoom.clamp(Self::ZOOM.0, Self::ZOOM.1) } else { d.zoom }; + GraphCamera { pan: [pan(self.pan[0], d.pan[0]), pan(self.pan[1], d.pan[1])], zoom } + } +} + 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 index b74dfd88..a4b97883 100644 --- a/crates/ui-egui/src/state/image_camera.rs +++ b/crates/ui-egui/src/state/image_camera.rs @@ -9,6 +9,17 @@ pub struct ImageCamera { pub fit: bool, } +impl ImageCamera { + pub const ZOOM: (f32, f32) = (0.02, 64.0); + + /// The camera with a finite offset and a zoom inside [`Self::ZOOM`]. + pub fn sanitized(self) -> ImageCamera { + let off = |v: f32| if v.is_finite() { v.clamp(-1.0e9, 1.0e9) } else { 0.0 }; + let zoom = if self.zoom.is_finite() { self.zoom.clamp(Self::ZOOM.0, Self::ZOOM.1) } else { 1.0 }; + ImageCamera { zoom, offset: [off(self.offset[0]), off(self.offset[1])], fit: self.fit } + } +} + 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/windows.rs b/crates/ui-egui/src/state/windows.rs index c7cce011..a3638ad9 100644 --- a/crates/ui-egui/src/state/windows.rs +++ b/crates/ui-egui/src/state/windows.rs @@ -10,4 +10,6 @@ pub struct Windows { pub preferences: bool, pub shortcuts: bool, pub home: bool, + #[serde(skip_deserializing)] + pub unsaved: Option, } diff --git a/crates/ui-egui/src/unsaved.rs b/crates/ui-egui/src/unsaved.rs new file mode 100644 index 00000000..a2e0b86c --- /dev/null +++ b/crates/ui-egui/src/unsaved.rs @@ -0,0 +1,147 @@ +//! Ask before unsaved work is thrown away +//! +//! Opening a package, closing all, making an empty package, dropping a file on the window and +//! closing the window or quitting all replace or end the open package. When it has unsaved +//! changes, those paths ask first (Save / Discard / Cancel). Only these UI paths ask: engine +//! commands run by the control channel, MCP, the CLI and scripts never open a dialog +//! +//! The decision is a pure state machine ([`request`], [`answer`], [`after_save`]) over the +//! serde [`Guarded`] action held in `Windows::unsaved`, so tests and the control channel +//! (`ui.inspect`) can see it. The glue below runs the held action once it is allowed + +use egui::{Align2, Context, RichText, Window}; +use serde_json::Value; + +use crate::MaterialCraftApp; +use crate::i18n::tr; + +mod choice; +mod guarded; +mod step; +pub use choice::Choice; +pub use guarded::Guarded; +pub use step::Step; + +/// Does throwing this session away lose work? +pub fn needs_confirmation(session: &materialcraft_engine::Session) -> bool { + session.modified +} + +/// Ask to run `action`. Returns it when it can run now; otherwise holds it in `pending` for the +/// dialog (an action already waiting is kept) and returns `None` +pub fn request(pending: &mut Option, modified: bool, action: Guarded) -> Option { + if pending.is_some() { + return None; + } + if !modified { + return Some(action); + } + *pending = Some(action); + None +} + +/// Apply the user's answer to the held action +pub fn answer(pending: &mut Option, choice: Choice) -> Step { + match (pending.take(), choice) { + (Some(a), Choice::Discard) => Step::Run(a), + (Some(a), Choice::Save) => Step::Save(a), + _ => Step::Stop, + } +} + +/// After a save attempt, the action may run only when the package really was saved +pub fn after_save(still_modified: bool, action: Guarded) -> Option { + (!still_modified).then_some(action) +} + +/// Should a window-close request be held back for the dialog? +pub fn holds_close(modified: bool, confirmed: bool) -> bool { + modified && !confirmed +} + +/// Run `action`, asking first when the package has unsaved changes +pub fn guard(app: &mut MaterialCraftApp, action: Guarded) { + let modified = needs_confirmation(&app.session); + if let Some(a) = request(&mut app.ui.windows.unsaved, modified, action) { + perform(app, a); + } +} + +/// Run an allowed action +fn perform(app: &mut MaterialCraftApp, action: Guarded) { + match action { + Guarded::Menu { .. } => { + app.run("file.newPackage", Value::Null); + } + #[cfg(not(target_arch = "wasm32"))] + Guarded::OpenPath { path } => crate::windows::open_path_now(app, &path), + #[cfg(target_arch = "wasm32")] + Guarded::OpenPath { .. } => {} + Guarded::LoadBytes { .. } => { + if let Some((name, bytes)) = app.pending_load.take() { + crate::web_files::load_now(app, &name, &bytes); + } + } + Guarded::Quit => app.quit_confirmed = true, + } +} + +/// Per frame: hold back a window close while there is unsaved work, and finish a confirmed quit +pub fn handle_close(app: &mut MaterialCraftApp, ctx: &Context) { + if ctx.input(|i| i.viewport().close_requested()) && holds_close(needs_confirmation(&app.session), app.quit_confirmed) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + guard(app, Guarded::Quit); + } + if app.quit_confirmed { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } +} + +/// The Save / Discard / Cancel dialog, while an action is held +pub fn show(app: &mut MaterialCraftApp, ctx: &Context) { + if app.ui.windows.unsaved.is_none() { + return; + } + let mut choice = None; + Window::new(tr("Unsaved changes")) + .id(egui::Id::unique("unsaved-changes")) + .collapsible(false) + .resizable(false) + .pivot(Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.label(RichText::new(format!("{} \"{}\"?", tr("Save changes to"), app.session.pkg.name)).strong()); + ui.label(tr("Your changes will be lost if you don't save them.")); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("Save")).clicked() { + choice = Some(Choice::Save); + } + if ui.button(tr("Discard")).clicked() { + choice = Some(Choice::Discard); + } + if ui.button(tr("Cancel")).clicked() { + choice = Some(Choice::Cancel); + } + }); + }); + if choice.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + choice = Some(Choice::Cancel); + } + let Some(choice) = choice else { return }; + match answer(&mut app.ui.windows.unsaved, choice) { + Step::Run(a) => perform(app, a), + Step::Save(a) => { + crate::windows::file_action(app, ctx, "file.save"); + match after_save(needs_confirmation(&app.session), a) { + Some(a) => perform(app, a), + None => app.pending_load = None, + } + } + Step::Stop => app.pending_load = None, + } +} + +#[cfg(test)] +#[path = "unsaved.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/unsaved.test.rs b/crates/ui-egui/src/unsaved.test.rs new file mode 100644 index 00000000..3bdb17b9 --- /dev/null +++ b/crates/ui-egui/src/unsaved.test.rs @@ -0,0 +1,95 @@ +#[cfg(test)] +mod unsaved_tests { + use crate::unsaved::{Choice, Guarded, Step, after_save, answer, needs_confirmation, request}; + + 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()); + assert_eq!(answer(&mut pending, Choice::Cancel), Step::Stop); + assert_eq!(pending, None); + + let mut pending = Some(open()); + assert_eq!(answer(&mut pending, Choice::Discard), Step::Run(open())); + assert_eq!(pending, None); + + let mut pending = Some(open()); + assert_eq!(answer(&mut pending, Choice::Save), Step::Save(open())); + assert_eq!(pending, None); + + 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] +fn a_second_package_cannot_replace_the_payload_waiting_for_confirmation() { + use crate::unsaved::{Choice, Guarded, Step}; + let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.session.modified = true; + let bytes = |name: &str| materialcraft_engine::formats::sbs::write_sbs(&materialcraft_engine::core::Package::new(name)).unwrap(); + crate::web_files::load(&mut app, "first.sbs", bytes("First"), false); + crate::web_files::load(&mut app, "second.sbs", bytes("Second"), false); + assert_eq!(app.ui.windows.unsaved, Some(Guarded::LoadBytes { name: "first.sbs".into() })); + let result = crate::control::handle(&mut app, &egui::Context::default(), "ui.set", &serde_json::json!({"prefs": {"thumbnails": false}})); + assert_eq!(result["ok"], true); + assert!(app.ui.windows.unsaved.is_some()); + if let Step::Run(action) = crate::unsaved::answer(&mut app.ui.windows.unsaved, Choice::Discard) { + crate::unsaved::perform(&mut app, action); + } else { + panic!("missing held action"); + } + assert_eq!(app.session.pkg.name, "First"); +} + +#[test] +fn a_pending_action_is_kept_even_if_the_package_was_saved_elsewhere() { + let first = crate::unsaved::Guarded::Quit; + let mut pending = Some(first.clone()); + assert!(crate::unsaved::request(&mut pending, false, crate::unsaved::Guarded::Menu { id: "ui.closeAll".into() }).is_none()); + assert_eq!(pending, Some(first)); +} diff --git a/crates/ui-egui/src/unsaved/choice.rs b/crates/ui-egui/src/unsaved/choice.rs new file mode 100644 index 00000000..eb2e9b88 --- /dev/null +++ b/crates/ui-egui/src/unsaved/choice.rs @@ -0,0 +1,7 @@ +/// What the user picked in the dialog +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Choice { + Save, + Discard, + Cancel, +} diff --git a/crates/ui-egui/src/unsaved/guarded.rs b/crates/ui-egui/src/unsaved/guarded.rs new file mode 100644 index 00000000..a0a46f62 --- /dev/null +++ b/crates/ui-egui/src/unsaved/guarded.rs @@ -0,0 +1,15 @@ +use serde::{Deserialize, Serialize}; + +/// An action that would throw the open package's unsaved work away +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum Guarded { + /// A menu item: `ui.closeAll` or `file.newPackage` + Menu { id: String }, + /// Open the package at `path` (desktop) + OpenPath { path: String }, + /// Open the package whose bytes wait in `MaterialCraftApp::pending_load` (browser) + LoadBytes { name: String }, + /// Close the window + Quit, +} diff --git a/crates/ui-egui/src/unsaved/step.rs b/crates/ui-egui/src/unsaved/step.rs new file mode 100644 index 00000000..28f9b9a7 --- /dev/null +++ b/crates/ui-egui/src/unsaved/step.rs @@ -0,0 +1,12 @@ +use super::Guarded; + +/// What to do after an answer +#[derive(Clone, Debug, PartialEq)] +pub enum Step { + /// Run the action now + Run(Guarded), + /// Save first, then run the action if the package is no longer modified + Save(Guarded), + /// Do nothing + Stop, +} diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 7b6a625e..56fc6ce6 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -58,6 +58,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { // Toolbar. egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { ui.horizontal(|ui| { + crate::preview_resolution::show(app, ui); for (c, label) in [("rgba", "RGBA"), ("r", "R"), ("g", "G"), ("b", "B"), ("a", "A")] { if crate::widgets::chip(ui, label, app.session.view2d.channel == c).clicked() { app.run("view.2d", json!({"channel": c})); @@ -91,13 +92,22 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { 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 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) ^ (app.session.view2d.port as u64).wrapping_mul(0x9e37) ^ (app.session.view2d.channel.len() as u64 * 31) ^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64; if app.view2d.tex.as_ref().is_none_or(|(k, _)| *k != key) { let px = rgba8(&img, &app.session.view2d.channel); - let ci = ColorImage::from_rgba_unmultiplied([img.w as usize, img.h as usize], &px); + // Keep source pixels for readout/screenshots, but respect the renderer's upload limit. + let ci = if img.w.max(img.h) as usize > texture_limit { + let scale = texture_limit as f64 / f64::from(img.w.max(img.h)); + let display = img.resize((f64::from(img.w) * scale).floor().max(1.0) as u32, (f64::from(img.h) * scale).floor().max(1.0) as u32, false); + ColorImage::from_rgba_unmultiplied([display.w as usize, display.h as usize], &rgba8(&display, &app.session.view2d.channel)) + } else { + ColorImage::from_rgba_unmultiplied([img.w as usize, img.h as usize], &px) + }; app.view2d.tex = Some((key, ctx.load_texture("view2d", ci, TextureOptions::NEAREST))); app.view2d.shown = Some((img.w, img.h, px)); } @@ -107,6 +117,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let p = ui.painter_at(rect); p.rect_filled(rect, 0.0, tk.viewport); // Camera: fit, wheel zoom around the pointer, drag to pan. + app.ui.image_camera = app.ui.image_camera.sanitized(); let cam = &mut app.ui.image_camera; let tiles = if app.session.view2d.tiled { 3.0 } else { 1.0 }; let fit_zoom = ((rect.width() - 16.0) / (img.w as f32 * tiles)).min((rect.height() - 16.0) / (img.h as f32 * tiles)).max(0.01); diff --git a/crates/ui-egui/src/view3d.rs b/crates/ui-egui/src/view3d.rs index adce9d1f..af0f89b8 100644 --- a/crates/ui-egui/src/view3d.rs +++ b/crates/ui-egui/src/view3d.rs @@ -7,6 +7,8 @@ //! (a panel, divider or window drag changes the size on every step), then renders on a worker //! thread so the UI never waits for it; until it lands the last frame stays up, kept in proportion. //! A frame that is no longer wanted is cancelled. The browser has no threads and renders here. +//! +//! The height output raises the mesh for real ([`Scene::with_relief`]), built on a worker thread and cached until its inputs change. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -16,7 +18,7 @@ use std::time::Duration; use egui::{Color32, ColorImage, Rect, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2}; use egui_phosphor::regular as icon; use materialcraft_engine::view_cmds::{ENVIRONMENTS, SCENES}; -use materialcraft_render::{Lighting, Maps, Scene, Settings}; +use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings}; use serde_json::json; use crate::MaterialCraftApp; @@ -26,9 +28,16 @@ use crate::theme::Tokens; /// Seconds the view's size and the camera rest before the full-quality frame renders. pub const SETTLE: f64 = 0.15; +/// Triangle budget of the displaced mesh; the browser builds it on the UI thread, so it gets a smaller one. +const RELIEF_TRIANGLES: usize = if cfg!(target_arch = "wasm32") { 120_000 } else { materialcraft_render::VIEW_TRIANGLES }; + #[derive(Default)] pub struct View3dState { scene: Option<(String, Arc)>, + /// The scene displaced by the height output, keyed by what it was built from (see [`relief_key`]). + displaced: Option<(u64, Arc)>, + /// The displaced scene building on a worker thread. + relief_job: Option, light: Option>, tex: Option, /// What the texture shows: (content key, full quality). @@ -50,9 +59,9 @@ pub struct View3dState { } impl View3dState { - /// A full-quality frame is rendering in the background. + /// A frame or its displaced geometry is still being built in the background. pub fn busy(&self) -> bool { - self.job.is_some() + self.job.is_some() || self.relief_job.is_some() } } @@ -79,6 +88,9 @@ impl Drop for Job { } } +mod relief_job; +use relief_job::ReliefJob; + pub fn scene_label(app: &MaterialCraftApp) -> String { let id = &app.session.view3d.scene; if id == "custom" @@ -160,6 +172,13 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); ui.menu_button(tr("Display"), |ui| { + crate::preview_resolution::show(app, ui); + ui.separator(); + let mut flip = app.session.view3d.normal_y_flip; + if ui.checkbox(&mut flip, tr("Flip normal map Y (DirectX)")).changed() { + app.run("view.3d", json!({"normalYFlip": flip})); + } + ui.separator(); ui.checkbox(&mut app.view3d.show_env, tr("Environment background")); ui.separator(); let mut t = app.session.view3d.transparency; @@ -172,9 +191,13 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); ui.menu_button(tr("Renderer"), |ui| { - let mut h = app.session.view3d.height_scale * 100.0; - if crate::widgets::slider(ui, tr("Height (parallax) depth"), &mut h, 0.0..=10.0, 2).changed() { - app.run("view.3d", json!({"heightScale": h / 100.0})); + let mut depth_percent = app.session.view3d.height_scale * 100.0; + if crate::widgets::slider(ui, tr("Height depth (% of the mesh size)"), &mut depth_percent, 0.0..=20.0, 1).changed() { + app.run("view.3d", json!({"heightScale": depth_percent / 100.0})); + } + let mut level = app.session.view3d.height_level; + if crate::widgets::slider(ui, tr("Height level (0 = rises out of the surface)"), &mut level, 0.0..=1.0, 2).changed() { + app.run("view.3d", json!({"heightLevel": level})); } let mut t = app.session.view3d.tiling; if crate::widgets::slider(ui, tr("Tiling"), &mut t, 0.25..=8.0, 2).changed() { @@ -308,12 +331,13 @@ fn frame_rect(rect: Rect, rendered: Option<(u32, u32)>) -> Rect { } } -fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 { +fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool, relief_shown: Option) -> u64 { use std::hash::{DefaultHasher, Hash, Hasher}; let mut hs = DefaultHasher::new(); let v = &app.session.view3d; - (w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view).hash(&mut hs); - 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] { + (w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view, relief_shown).hash(&mut hs); + v.normal_y_flip.hash(&mut hs); + 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, v.height_level] { f.to_bits().hash(&mut hs); } app.session.material_key().hash(&mut hs); @@ -329,7 +353,8 @@ fn render(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, moving: b app.view3d.changed_at = Some(now); } app.view3d.size = Some(size); - let key = content_key(app, size.0, size.1, app.view3d.show_env); + let relief_shown = update_relief(app, ctx); + let key = content_key(app, size.0, size.1, app.view3d.show_env, relief_shown); collect(app, ctx, key); if app.view3d.key == Some((key, true)) || (moving && app.view3d.key == Some((key, false))) { return; @@ -369,23 +394,112 @@ fn collect(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64) { } } -/// The scene, lighting, maps and settings of the current view (scene and lighting are cached). -fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, Arc, Maps, Settings)> { - let v = app.session.view3d.clone(); +/// The plain scene of the current view and its cache key, building it when the scene changed. +fn base_scene(app: &mut MaterialCraftApp) -> (String, Arc) { + let v = &app.session.view3d; let scene_key = match (&*v.scene, &app.session.custom_mesh) { ("custom", Some((name, _))) => format!("custom:{name}"), _ => v.scene.clone(), }; - if app.view3d.scene.as_ref().is_none_or(|(id, _)| *id != scene_key) { - let scene = match (&*v.scene, &app.session.custom_mesh) { - ("custom", Some((_, mesh))) => Scene::new((**mesh).clone()), - _ => Scene::builtin(&v.scene), - }; - app.view3d.scene = Some((scene_key, Arc::new(scene))); + + match &app.view3d.scene { + Some((key, scene)) if *key == scene_key => (scene_key, scene.clone()), + _ => { + let scene = match (&*v.scene, &app.session.custom_mesh) { + ("custom", Some((_, mesh))) => Scene::new((**mesh).clone()), + _ => Scene::builtin(&v.scene), + }; + let scene = Arc::new(scene); + app.view3d.scene = Some((scene_key.clone(), scene.clone())); + (scene_key, scene) + } } +} + +/// What the displaced scene depends on (scene, height output cook, relief settings, normal map); `None` when nothing is raised. +fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option { + use std::hash::{DefaultHasher, Hash, Hasher}; + + let v = &app.session.view3d; + if maps.height.is_none() || v.height_scale <= 0.0 { + return None; + } + + let sources = app.session.material_preview.sources(&app.session.pkg); + let height_source = sources.get(&materialcraft_engine::core::MaterialChannel::Height)?; + let height_cook = app.session.material_source_key(height_source); + + let mut hasher = DefaultHasher::new(); + (scene_key, height_cook, maps.normal.is_some()).hash(&mut hasher); + for f in [v.height_scale, v.height_level, v.tiling] { + f.to_bits().hash(&mut hasher); + } + Some(hasher.finish()) +} + +/// Collect a finished relief build or start a missing one; returns the key of the displaced scene shown (`None` = plain mesh). +fn update_relief(app: &mut MaterialCraftApp, ctx: &egui::Context) -> Option { + let (scene_key, base) = base_scene(app); + let maps = Maps::from_usages(app.session.material_maps()); + let wanted = relief_key(app, &scene_key, &maps); + + if let Some(job) = app.view3d.relief_job.take() { + match job.rx.try_recv() { + Ok(Some(scene)) if Some(job.key) == wanted => app.view3d.displaced = Some((job.key, scene)), + Ok(_) | Err(TryRecvError::Disconnected) => {} + // Finish the active build before starting a newer one. Dropping its receiver + // cannot cancel subdivision, so rapid edits must not accumulate workers. + Err(TryRecvError::Empty) => app.view3d.relief_job = Some(job), + } + } + + let wanted = wanted?; + + if app.view3d.displaced.as_ref().is_some_and(|(key, _)| *key == wanted) { + return Some(wanted); + } + if app.view3d.relief_job.is_none() { + let v = &app.session.view3d; + let relief = Relief { depth: v.height_scale, level: v.height_level }; + start_relief(app, ctx, wanted, base, maps, relief, v.tiling); + } + None +} + +/// Build the displaced scene on a worker thread. +#[cfg(not(target_arch = "wasm32"))] +fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc, maps: Maps, relief: Relief, tiling: f32) { + let (tx, rx) = std::sync::mpsc::channel(); + let (repaint, viewport) = (ctx.clone(), ctx.viewport_id()); + let (thread_base, thread_maps) = (base.clone(), maps.clone()); + let spawned = std::thread::Builder::new().name("materialcraft-relief".into()).spawn(move || { + let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, RELIEF_TRIANGLES).map(Arc::new)); + repaint.request_repaint_of(viewport); + }); + + match spawned { + Ok(_) => app.view3d.relief_job = Some(ReliefJob { key, rx }), + Err(e) => { + log::warn!("could not start a 3D view relief thread ({e}); building it here"); + app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene))); + } + } +} + +/// The browser has no threads: the displaced scene builds here (the page pauses). +#[cfg(target_arch = "wasm32")] +fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc, maps: Maps, relief: Relief, tiling: f32) { + app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene))); +} + +/// The scene, lighting, maps and settings of the current view: the displaced scene when it is current, else the plain one. +fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, Arc, Maps, Settings)> { + let (scene_key, base) = base_scene(app); + let v = app.session.view3d.clone(); if app.view3d.light.as_ref().is_none_or(|l| l.name != v.environment) { app.view3d.light = Some(Arc::new(Lighting::new(&v.environment))); } + let settings = Settings { yaw: v.yaw, pitch: v.pitch, @@ -394,7 +508,7 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, A tiling: v.tiling, exposure: v.exposure, env_rotation: v.env_rotation, - height_scale: v.height_scale, + normal_y_flip: v.normal_y_flip, show_env: app.view3d.show_env, supersample, transparency: v.transparency, @@ -402,8 +516,13 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, A ..Settings::default() }; let maps = Maps::from_usages(app.session.material_maps()); - let (Some((_, scene)), Some(light)) = (&app.view3d.scene, &app.view3d.light) else { return None }; - Some((scene.clone(), light.clone(), maps, settings)) + let wanted = relief_key(app, &scene_key, &maps); + let scene = match &app.view3d.displaced { + Some((key, displaced)) if Some(*key) == wanted => displaced.clone(), + _ => base, + }; + let light = app.view3d.light.clone()?; + Some((scene, light, maps, settings)) } /// Texture pixels for `rect` at `scale` pixels per point. @@ -472,6 +591,48 @@ fn show_frame(app: &mut MaterialCraftApp, ctx: &egui::Context, frame: Frame, key mod tests { use super::*; + #[test] + fn relief_tracks_assigned_height_while_another_graph_is_open() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.session.preview_size = Some(16); + app.session.cook(); + let (scene_key, _) = base_scene(&mut app); + let original = relief_key(&app, &scene_key, &Maps::from_usages(app.session.material_maps())).unwrap(); + app.session.pkg.graphs.push(materialcraft_engine::core::Graph::new("Other")); + app.session.graph = 1; + app.session.cook(); + assert_eq!(relief_key(&app, &scene_key, &Maps::from_usages(app.session.material_maps())), Some(original)); + app.session.pkg.graphs[0].seed += 1; + app.session.cook(); + assert_ne!(relief_key(&app, &scene_key, &Maps::from_usages(app.session.material_maps())), Some(original)); + } + + #[test] + fn changing_relief_keeps_one_worker_and_discards_stale_geometry() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + app.session.cook(); + let (scene_key, base) = base_scene(&mut app); + let maps = Maps::from_usages(app.session.material_maps()); + let old_key = relief_key(&app, &scene_key, &maps).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + app.view3d.relief_job = Some(ReliefJob { key: old_key, rx }); + let ctx = egui::Context::default(); + for index in 1..=20 { + app.session.view3d.height_scale = index as f32 * 0.001; + assert_eq!(update_relief(&mut app, &ctx), None); + assert_eq!(app.view3d.relief_job.as_ref().unwrap().key, old_key, "a second subdivision worker started"); + assert!(app.view3d.busy(), "geometry work must count as a busy view"); + } + let wanted = relief_key(&app, &scene_key, &maps).unwrap(); + assert_ne!(old_key, wanted); + app.view3d.displaced = Some((wanted, base.clone())); + tx.send(Some(Arc::new(Scene::builtin("sphere")))).unwrap(); + assert_eq!(update_relief(&mut app, &ctx), Some(wanted)); + assert!(app.view3d.relief_job.is_none()); + assert!(!app.view3d.busy()); + assert!(Arc::ptr_eq(&app.view3d.displaced.as_ref().unwrap().1, &base), "outdated geometry replaced the current scene"); + } + #[test] fn a_frame_for_another_size_keeps_its_proportions() { let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(400.0, 200.0)); diff --git a/crates/ui-egui/src/view3d/relief_job.rs b/crates/ui-egui/src/view3d/relief_job.rs new file mode 100644 index 00000000..76124019 --- /dev/null +++ b/crates/ui-egui/src/view3d/relief_job.rs @@ -0,0 +1,9 @@ +use materialcraft_render::Scene; +use std::sync::{Arc, mpsc::Receiver}; + +/// A displaced scene building on a worker thread (`None` arrives when nothing moves) +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(super) struct ReliefJob { + pub(super) key: u64, + pub(super) rx: Receiver>>, +} diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index ff96e0b5..8a0ca128 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -59,19 +59,18 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec, bitmap: bool return; } 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::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})); - } - app.toast(format!("{} {res}", tr("Imported")), false); - } - Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't import")), true), - } + crate::graph::import_bitmap_bytes(app, name, bytes); return; } - match materialcraft_engine::file_cmds::open_bytes(&mut app.session, &bytes, Some(name.to_string())) { + if app.ui.windows.unsaved.is_some() { + return; + } + app.pending_load = Some((name.to_string(), bytes)); + crate::unsaved::guard(app, crate::unsaved::Guarded::LoadBytes { name: name.to_string() }); +} + +pub(crate) fn load_now(app: &mut MaterialCraftApp, name: &str, bytes: &[u8]) { + 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; @@ -241,6 +240,30 @@ mod web { mod tests { use super::*; + fn app(modified: bool) -> MaterialCraftApp { + let mut s = materialcraft_engine::sample_session(); + s.modified = modified; + MaterialCraftApp::headless(s, crate::state::UiState::default()) + } + + #[test] + fn a_package_picked_over_unsaved_work_is_held_not_loaded() { + let mut app = app(true); + let before = app.session.pkg.name.clone(); + load(&mut app, "other.sbs", b"not a package".to_vec(), false); + assert_eq!(app.ui.windows.unsaved, Some(crate::unsaved::Guarded::LoadBytes { name: "other.sbs".into() })); + assert_eq!(app.pending_load.as_ref().map(|(n, _)| n.as_str()), Some("other.sbs")); + assert_eq!(app.session.pkg.name, before); + assert!(app.toasts.is_empty()); + } + + #[test] + fn an_image_import_is_not_a_replacement_and_never_asks() { + let mut app = app(true); + load(&mut app, "x.png", b"junk".to_vec(), true); + assert!(app.ui.windows.unsaved.is_none()); + } + #[test] fn zip_round_trips() { let files = vec![("a.png".to_string(), b"one".to_vec()), ("b.png".to_string(), vec![7u8; 4096])]; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 1f86f196..ac48b272 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -64,8 +64,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/src/windows.rs b/crates/ui-egui/src/windows.rs index 8e2c489e..ed24d8dd 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -27,7 +27,7 @@ const PREVIEW: u32 = 96; fn render_templates() -> crate::thumbs::Previews { let light = materialcraft_render::Lighting::new("studio"); let scene = materialcraft_render::Scene::builtin("sphere"); - let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, height_scale: 0.0, ..Default::default() }; + let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() }; materialcraft_engine::samples::TEMPLATES .iter() .filter_map(|(id, _)| { @@ -95,6 +95,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { if app.ui.windows.home { home(app, ctx); } + crate::unsaved::show(app, ctx); } fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) { @@ -282,17 +283,9 @@ fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) { if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut auto, 0.0..=60.0, 0).changed() { p.autosave_minutes = auto.round() as u32; } - crate::widgets::combo( - ui, - tr("Preview size while editing"), - if p.preview_size == 0 { tr("Full size").to_string() } else { format!("{} px", p.preview_size) }, - |ui| { - for s in [256u32, 512, 1024, 2048, 0] { - let label = if s == 0 { tr("Full size").to_string() } else { format!("{s} px") }; - ui.selectable_value(&mut p.preview_size, s, label); - } - }, - ); + crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(p.preview_size), |ui| { + crate::preview_resolution::choices(ui, &mut p.preview_size); + }); ui.checkbox(&mut p.thumbnails, tr("Show node thumbnails")); crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut p.camera.pan_limit, 0.0..=20.0, 1); crate::widgets::slider(ui, tr("3D pan speed"), &mut p.camera.pan_speed, 0.1..=4.0, 2); @@ -574,14 +567,8 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> true } "file.importBitmap" => { - if let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - && 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::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})); - } + if let Some(path) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() { + crate::graph::import_bitmap_file(app, &path.display().to_string()); } true } @@ -604,6 +591,11 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> /// Open a package from a path (recent list, command line) #[cfg(not(target_arch = "wasm32"))] pub fn open_path(app: &mut MaterialCraftApp, path: &str) { + crate::unsaved::guard(app, crate::unsaved::Guarded::OpenPath { path: path.to_string() }); +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn open_path_now(app: &mut MaterialCraftApp, path: &str) { if app.run("file.open", json!({"path": path})).is_some() { app.ui.add_recent(path); app.ui.frame_all = true; @@ -611,3 +603,7 @@ pub fn open_path(app: &mut MaterialCraftApp, path: &str) { after_open(app); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "windows.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/windows.test.rs b/crates/ui-egui/src/windows.test.rs new file mode 100644 index 00000000..c963c3e6 --- /dev/null +++ b/crates/ui-egui/src/windows.test.rs @@ -0,0 +1,47 @@ +#[cfg(test)] +mod open_guard_tests { + use crate::unsaved::Guarded; + use crate::{MaterialCraftApp, state::UiState}; + + #[test] + fn opening_a_path_over_unsaved_work_asks_first() { + let mut s = materialcraft_engine::sample_session(); + s.modified = true; + let mut app = MaterialCraftApp::headless(s, UiState::default()); + crate::windows::open_path(&mut app, "does-not-exist.sbs"); + assert_eq!(app.ui.windows.unsaved, Some(Guarded::OpenPath { path: "does-not-exist.sbs".into() })); + assert!(app.toasts.is_empty(), "nothing was attempted yet"); + } + + #[test] + fn opening_a_path_over_a_clean_package_goes_straight_to_open() { + let mut s = materialcraft_engine::sample_session(); + s.modified = false; + let mut app = MaterialCraftApp::headless(s, UiState::default()); + crate::windows::open_path(&mut app, "does-not-exist.sbs"); + assert!(app.ui.windows.unsaved.is_none()); + assert!(!app.toasts.is_empty(), "the open was attempted and its error reported"); + } +} + +#[cfg(test)] +mod import_tests { + use crate::{MaterialCraftApp, state::UiState}; + use materialcraft_engine::formats::{Depth, encode}; + use materialcraft_engine::image::{Image, Kind}; + + #[test] + fn importing_a_bitmap_file_is_one_undo_entry() { + let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.2, 0.1, 1.0]), "png", Depth::U8, true).unwrap(); + let path = std::env::temp_dir().join(format!("mc-import-{}.png", std::process::id())); + std::fs::write(&path, png).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + let base = app.session.history().len(); + crate::graph::import_bitmap_file(&mut app, &path.display().to_string()); + std::fs::remove_file(&path).ok(); + assert_eq!(app.session.history().len(), base + 1, "history: {:?}", app.session.history()); + assert_eq!(app.session.history().last().map(String::as_str), Some("Import bitmap")); + app.session.undo(); + assert_eq!(app.session.history().len(), base); + } +} diff --git a/crates/ui-egui/tests/common/search.rs b/crates/ui-egui/tests/common/search.rs new file mode 100644 index 00000000..63735d78 --- /dev/null +++ b/crates/ui-egui/tests/common/search.rs @@ -0,0 +1,40 @@ +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> { + 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 mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + let pointer = h.state().graph.view.center(); + h.event(Event::PointerMoved(pointer)); + h.step(); + h.key_press(egui::Key::Tab); + h.step(); + h.run_steps(3); + assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).is_some()); + assert!(label_position(&h, "Bitmap").is_some(), "fresh search must show its first result"); + h +} + +pub fn label_position(h: &Harness<'static, MaterialCraftApp>, label: &str) -> Option { + 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 { + match shape { + Shape::Text(t) if clip.contains(t.pos) && popup.contains(t.pos) && t.galley.text().trim() == label => { + Some(t.pos + vec2(0.0, t.galley.size().y * 0.5)) + } + Shape::Vec(v) => v.iter().find_map(|s| find(s, clip, popup, label)), + _ => None, + } + } + h.output().shapes.iter().find_map(|s| find(&s.shape, s.clip_rect, popup, label)) +} 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(); +} diff --git a/crates/ui-egui/tests/language_switching.rs b/crates/ui-egui/tests/language_switching.rs new file mode 100644 index 00000000..f3f81322 --- /dev/null +++ b/crates/ui-egui/tests/language_switching.rs @@ -0,0 +1,29 @@ +//! Isolate process-global language switching from tests that construct the UI. +use materialcraft_ui_egui::i18n::{current, is_rtl, set_language, tr, trf}; + +#[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"); +} diff --git a/crates/ui-egui/tests/normal_maps.rs b/crates/ui-egui/tests/normal_maps.rs new file mode 100644 index 00000000..dcdd225d --- /dev/null +++ b/crates/ui-egui/tests/normal_maps.rs @@ -0,0 +1,79 @@ +use egui::vec2; +use egui_kittest::{Harness, kittest::Queryable}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; +use std::time::Duration; + +fn app() -> MaterialCraftApp { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + let node = app.run("graph.node.add", json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap(); + app.run("graph.node.add", json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap(); + app +} + +fn settle(h: &mut Harness<'static, MaterialCraftApp>, after: u64) { + for _ in 0..300 { + h.step(); + let app = h.state(); + if app.view3d.renders > after && !app.session.dirty && !app.cooker.busy() && !app.view3d.busy() { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("the normal-map preview did not finish rendering"); +} + +fn toggle(h: &mut Harness<'static, MaterialCraftApp>) { + h.get_by_label("Display").click(); + h.run_steps(4); + h.get_by_label("Flip normal map Y (DirectX)").click(); + h.run_steps(4); +} + +#[test] +fn display_toggle_updates_the_session_and_rerenders_the_normal_map() { + let mut h = Harness::builder().with_size(vec2(1400.0, 860.0)).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app(), + ); + settle(&mut h, 0); + let before = h.state().view3d.shown.clone().unwrap(); + let rendered = h.state().view3d.renders; + toggle(&mut h); + assert!(h.state().session.view3d.normal_y_flip); + settle(&mut h, rendered); + assert_ne!(before.2, h.state().view3d.shown.as_ref().unwrap().2); + // Close the open menu, then restore the OpenGL setting through the same pointer gesture. + h.key_press(egui::Key::Escape); + h.run_steps(4); + let rendered = h.state().view3d.renders; + toggle(&mut h); + assert!(!h.state().session.view3d.normal_y_flip); + settle(&mut h, rendered); + assert_eq!(before.2, h.state().view3d.shown.as_ref().unwrap().2); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn normal_convention_snapshot() { + let mut h = Harness::builder().with_size(vec2(1400.0, 860.0)).wgpu().build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app(), + ); + settle(&mut h, 0); + let rendered = h.state().view3d.renders; + toggle(&mut h); + settle(&mut h, rendered); + h.get_by_label("Display").click(); + h.run_steps(4); + assert!(h.state().session.view3d.normal_y_flip); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("normal-convention.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/preview_resolution.rs b/crates/ui-egui/tests/preview_resolution.rs new file mode 100644 index 00000000..59c3532d --- /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.image(id, 0).unwrap(); + 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.image(id, 0).unwrap(); + 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.image(id, 0).unwrap(); + 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(); + } + } +} diff --git a/crates/ui-egui/tests/resolution.rs b/crates/ui-egui/tests/resolution.rs new file mode 100644 index 00000000..ae5d15a7 --- /dev/null +++ b/crates/ui-egui/tests/resolution.rs @@ -0,0 +1,80 @@ +//! Resolution changes must reach both material maps and the displayed image, and survive frames. +use egui::vec2; +use egui_kittest::{Harness, kittest::Queryable}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState, control, view2d}; +use serde_json::json; + +fn app() -> MaterialCraftApp { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.run("file.new", json!({"template": "empty", "size": 4096})).unwrap(); + let node = app.run("graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}})).unwrap()["id"].as_u64().unwrap(); + app.run("graph.node.add", json!({"def": "output", "connectFrom": {"node": node}})).unwrap(); + app.run("view.2d", json!({"node": node})).unwrap(); + app.session.cook(); + app +} + +fn choose_4k(h: &mut Harness<'static, MaterialCraftApp>) { + h.get_by_label("Preview resolution").click(); + h.run(); + h.get_by_label("4096 px").click(); + h.run(); + assert_eq!(h.state().session.preview_size, Some(4096)); + assert_eq!(h.state().ui.prefs.preview_size, 4096); + h.state_mut().session.cook(); + h.step(); + let app = h.state(); + let (_, image) = app.session.view2d_image().unwrap(); + assert_eq!((image.w, image.h), (4096, 4096)); + assert!(app.session.material_maps().iter().all(|(_, image)| (image.w, image.h) == (4096, 4096))); + assert!(!app.session.material_maps().is_empty()); + assert_eq!(app.view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); +} + +#[test] +fn selecting_4k_cooks_and_displays_4k_material_maps() { + 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); + choose_4k(&mut h); + // A smaller device limit must refresh the texture without losing the cooked source. + h.input_mut().max_texture_side = Some(2048); + h.step(); + assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); +} + +#[test] +fn command_resolution_survives_preferences_and_invalid_requests() { + let mut app = app(); + let ctx = egui::Context::default(); + for size in [4096, 0, 512] { + let response = control::handle(&mut app, &ctx, "command.run", &json!({"id": "view.previewSize", "params": {"size": size}})); + assert_eq!(response["ok"], true); + app.apply_prefs(); + assert_eq!(app.ui.prefs.preview_size, size); + assert_eq!(app.session.preview_size, if size == 0 { None } else { Some(size) }); + } + assert!(app.run("view.previewSize", json!({"size": -1})).is_none()); + assert_eq!(app.ui.prefs.preview_size, 512); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn resolution_snapshot() { + let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::theme::install).with_size(vec2(1200.0, 800.0)).wgpu().build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.apply_prefs(); + view2d::show(app, ui); + }, + app(), + ); + choose_4k(&mut h); + let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("resolution-4k.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/search_query.rs b/crates/ui-egui/tests/search_query.rs new file mode 100644 index 00000000..5c6d819d --- /dev/null +++ b/crates/ui-egui/tests/search_query.rs @@ -0,0 +1,71 @@ +//! 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; + +fn scroll(h: &mut Harness<'static, MaterialCraftApp>, rows: usize) { + for _ in 0..rows { + h.key_press(Key::ArrowDown); + h.step(); + } + h.run_steps(25); +} +fn filter_after_scrolling(h: &mut Harness<'static, MaterialCraftApp>) { + scroll(h, 45); + 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"); +} +fn assert_inserted(h: &mut Harness<'static, MaterialCraftApp>, def: &str) { + h.key_press(Key::Enter); + h.step(); + let g = h.state().session.graph().unwrap(); + assert_eq!(g.nodes.len(), 1); + assert_eq!(g.nodes[0].def, def); +} +#[test] +fn filtering_after_scrolling_reveals_and_inserts_first_match() { + let mut h = search::harness(false); + filter_after_scrolling(&mut h); + assert_inserted(&mut h, "blur"); +} +#[test] +fn clearing_a_scrolled_query_reveals_and_inserts_first_match() { + let mut h = search::harness(false); + h.event(Event::Text("blur".into())); + h.step(); + scroll(&mut h, 15); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); + 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_inserted(&mut h, "bitmap"); +} +#[test] +fn reopening_a_scrolled_search_reveals_first_match() { + let mut h = search::harness(false); + scroll(&mut h, 45); + h.key_press(Key::Escape); + h.step(); + h.run_steps(3); + h.key_press(Key::Tab); + 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_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 new file mode 100644 index 00000000..5f25bbb4 --- /dev/null +++ b/crates/ui-egui/tests/search_rows.rs @@ -0,0 +1,43 @@ +//! 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 popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); + pos2(popup.right() - 24.0, y) +} +fn click(h: &mut Harness<'static, MaterialCraftApp>, pos: Pos2) { + h.event(Event::PointerMoved(pos)); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(3); +} +#[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) }; + 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(); +} 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..0e6fdf9d --- /dev/null +++ b/crates/ui-egui/tests/slider_round_values.rs @@ -0,0 +1,88 @@ +//! 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, definition: &str) -> (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":definition})).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 angle_value(h: &Harness<'static, MaterialCraftApp>, id: NodeId) -> f32 { + match h.state().session.graph().unwrap().node(id).unwrap().params.get("angle") { + Some(Value::Float(v)) => *v, + None => 0.0, + other => panic!("unexpected angle {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, "directional_blur"); + drag_near(&mut h, "Angle", 0, angle, -360.0, 360.0); + assert_eq!(angle_value(&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!(angle_value(&h, id), 0.0); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(angle_value(&h, id), 0.25); + } + } + } +} + +#[test] +fn fractional_parameter_values_remain_reachable() { + let (mut h, id) = harness(1.0, false, "transformation"); + drag_near(&mut h, "Y", 0, 0.25, -1.0, 1.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("offset"), Some(&Value::Float2([-0.5, 0.25]))); +} + +#[test] +#[ignore = "requires an offscreen GPU"] +fn exact_angle_screenshot() { + let (mut h, id) = harness(1.0, true, "directional_blur"); + drag_near(&mut h, "Angle", 0, 90.0, -360.0, 360.0); + assert_eq!(angle_value(&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(); +} diff --git a/crates/ui-egui/tests/unsaved_changes.rs b/crates/ui-egui/tests/unsaved_changes.rs new file mode 100644 index 00000000..b2d1d00c --- /dev/null +++ b/crates/ui-egui/tests/unsaved_changes.rs @@ -0,0 +1,31 @@ +use egui::{Rect, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; +use materialcraft_ui_egui::{ + MaterialCraftApp, UiState, + unsaved::{self, Guarded}, +}; + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn unsaved_dialog_snapshot_and_cancel() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.session.modified = true; + unsaved::guard(&mut app, Guarded::Menu { id: "ui.closeAll".into() }); + let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(10); + let rect = h.ctx.memory(|m| m.area_rect(egui::Id::unique("unsaved-changes"))).unwrap_or(Rect::NOTHING); + assert!(rect.is_finite() && rect.width() > 100.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("unsaved-changes.png")).unwrap(); + h.get_by_label("Cancel").click(); + h.run_steps(5); + assert!(h.state().ui.windows.unsaved.is_none()); + assert!(h.state().session.modified); +} diff --git a/docs/architecture.md b/docs/architecture.md index a27f13ae..6c0eb838 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -21,7 +21,7 @@ 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 +L3 render the 3D view: BVH ray casts, the height output displacing a subdivided mesh, GGX PBR with prefiltered IBL + SH diffuse, alpha transparency (layered ray compositing) and an alpha channel view, ACES tone mapping; procedural environments L4 automation MCP server (rmcp), JSON-lines RPC (stdio/TCP with token), bridge client, workspace sandbox @@ -54,6 +54,14 @@ offset by powers of two or set absolutely. While editing, outputs are capped at (512 px by default), with pixel-based parameters scaled by `w / 256` so previews and full-size exports look the same. Exports cook at full size through the same cache. +The 2D toolbar and the 3D view's Display menu expose the shared preview limit (256, 512, 1024, +2048 or 4096 px, or Full size). This is a cap, so a 4K preview requires a graph/node configured +for 4096 px or larger. Both controls run `view.previewSize` and persist the choice in preferences; +control-channel calls to the same command also retain their size across UI frames. The 3D view +uses those cooked maps, while its rendered frame follows the panel's physical pixel dimensions. +If the device supports smaller textures than the cooked image, the 2D view reduces only the +uploaded texture to that limit; source pixels, readout and screenshots retain the cooked size. + The desktop UI cooks on a worker thread (`ui-egui/src/cook.rs`) from a snapshot of the package and keeps drawing the last results; the browser cooks on the UI thread. @@ -166,3 +174,8 @@ TextureCraft paints with it and re-cooks it by running `materialcraft-cli run

**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: 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, @@ -34,10 +35,11 @@ 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?, size?, graph?}` | headless | cook at full size and write every output | +| `material.export {path, graph?, size?, values?}` | headless | write a portable `.mcmat` below the write root | | `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 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.set {...}` | app | recursively merge fields into the UI state | | `ui.input {events}` | app | synthetic input, below | | `view.screenshot {view?: "3d"\|"2d"}` | app | PNG of the 3D or 2D view | | `ui.screenshot` | app | PNG of the whole window | @@ -80,7 +82,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.node.function` | `{id?, param, function}` drives a parameter by a function graph of the graph's inputs (dynamic parameter); `{id?, param, remove: true}` removes it | | `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values | | `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance | -| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, parallax depth, `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | +| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | @@ -198,7 +200,7 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k |---|---| | `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.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 | +| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | | `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` | @@ -206,10 +208,23 @@ 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. 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. + +Automation command requests each form a separate undo step. Embedded graph edits may explicitly +pass `merge: true` to continue one gesture; an ordinary request ends that merge. UI slider gestures +still coalesce until release. `material_export` uses the headless write-root capability and does not +expose unrestricted engine file paths. + +Bitmap Color space selects sRGB or Linear. `graph.input.bind` accepts `linear: true` for normal, +height and other data maps. Input preview bindings persist in native SBS graph options with the +`materialcraft.previewImage.` and `materialcraft.previewLinear.` prefixes; these options describe +MaterialCraft editor previews and do not establish external application interoperability. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 40d07b0b..47e9bf29 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -4,6 +4,10 @@ > compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and > [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. +Current integration also provides workspace-scoped `material_export`, real Height displacement +from the assigned material, explicit normal-map convention, and linear bitmap/input previews. +The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. + > **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 d5641762..7c322033 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -4,6 +4,10 @@ > compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and > [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. +Current integration also provides workspace-scoped `material_export`, real Height displacement +from the assigned material, explicit normal-map convention, and linear bitmap/input previews. +The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. + > **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 6f135be5..240cf7a8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -4,6 +4,10 @@ > compatibility claims are historical. See [atomic-workflow.md](atomic-workflow.md) and > [ROADMAP.md](../ROADMAP.md) for the current scope and remaining validation. +Current integration also provides workspace-scoped `material_export`, real Height displacement +from the assigned material, explicit normal-map convention, and linear bitmap/input previews. +The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. + > **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/docs/wires-and-alpha.md b/docs/wires-and-alpha.md index 685234fe..693c4091 100644 --- a/docs/wires-and-alpha.md +++ b/docs/wires-and-alpha.md @@ -89,6 +89,12 @@ session. ## Alpha in the 3D view +The 3D view reads OpenGL normal maps by default, matching the Normal node's default format. +For a DirectX normal map, enable **Display ▸ Flip normal map Y (DirectX)**, or run +`view.3d {"normalYFlip": true}`. Choose the corresponding format in the Normal node's properties. +The setting affects both the interactive view and headless renders, appears as `view3d.normalYFlip` +in `session.inspect`, and returns to OpenGL when the scene is reset. +

The same sphere in the alpha channel view: the opaque grid lines are white and the clear gaps black
The alpha channel view: white is opaque, black is clear @@ -106,7 +112,7 @@ Where the alpha is below one, the surface lets light through: each camera ray co surfaces it meets front to back (`color × alpha`, the rest passes on) through up to eight layers, then shows what lies behind: the backdrop, or the environment when **Display ▸ Environment background** is on. Back faces seen through a clear front are shaded facing the viewer, so a -cut-out sphere shows its inside. Parallax from the height output applies to every layer. +cut-out sphere shows its inside. Every layer is the mesh as the height output displaced it. **Display ▸ Transparency (alpha)** turns this off, so the alpha is ignored and the mesh is opaque. It is on by default.