diff --git a/Cargo.lock b/Cargo.lock index 698d0cf..6a6a1c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2832,6 +2832,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "tempfile", "thiserror 2.0.21", "tokio", ] @@ -2843,6 +2844,7 @@ dependencies = [ "materialcraft-automation", "materialcraft-engine", "serde_json", + "tempfile", "tokio", "winresource", ] diff --git a/README.md b/README.md index acb8f0b..d6bf702 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ cargo run --release -p materialcraft-cli -- mcp # MCP server (stdi cargo run --release -p materialcraft-cli -- new wood wood.sbs cargo run --release -p materialcraft-cli -- render wood.sbs wood.png --scene sphere --full --hq cargo run --release -p materialcraft-cli -- export wood.sbs textures --format png --depth 16 +# Given a separate my.sbs with Materials/Oak and an exposed wear parameter: cargo run --release -p materialcraft-cli -- export my.sbs out --set wear=0.7 # with a graph input "wear" set first cargo run --release -p materialcraft-cli -- publish my.sbs my.mcmat --graph Materials/Oak cargo run --release -p materialcraft-cli -- export my.mcmat build/oak --profile materialx --size 2048 --set wear=0.7 diff --git a/apps/materialcraft-cli/Cargo.toml b/apps/materialcraft-cli/Cargo.toml index c46ca73..025c1c4 100644 --- a/apps/materialcraft-cli/Cargo.toml +++ b/apps/materialcraft-cli/Cargo.toml @@ -17,3 +17,6 @@ tokio = { workspace = true } [build-dependencies] winresource = "0.1" + +[dev-dependencies] +tempfile = "3" diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index dde9305..3d1babc 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -33,7 +33,9 @@ USAGE: [--depth 8|16|32] [--size ] [--pattern

] [--profile maps|materialx] [--preset ] [--input =]... Write output images, or material.mtlx and its baked textures with --profile materialx. - --normal-format opengl|directx declares the input convention for opaque normal maps. + --normal-format opengl|directx requires --profile maps|materialx and declares the input convention. + --graph-path selects a literal path, including numeric names, instead of --graph. + Named profiles choose their own format and filenames; omit --format and --pattern. --displacement-scale scales signed MaterialX displacement (default 1). materialcraft-cli render [--size x] [--view 3d|2d] [--scene ] [--node ] [--yaw ] [--pitch ] [--graph ] [--set =]... [--full] @@ -55,17 +57,18 @@ USAGE: /// (name, flags taking a value, bare flags) const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("info", &[], &[]), - ("publish", &["--graph"], &[]), + ("publish", &["--graph", "--graph-path"], &[]), ("commands", &["--filter"], &[]), ("nodes", &["--filter", "--category"], &[]), ("run", &["-o"], &[]), ("batch", &[], &[]), ("new", &["--size", "--name"], &[]), - ("cook", &["--graph", "--set", "--size", "--input", "--preset"], &["--full"]), + ("cook", &["--graph", "--graph-path", "--set", "--size", "--input", "--preset"], &["--full"]), ( "export", &[ "--graph", + "--graph-path", "--set", "--format", "--depth", @@ -80,7 +83,11 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ], &[], ), - ("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--set", "--tiling", "--displacement"], &["--full", "--hq"]), + ( + "render", + &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--graph-path", "--set", "--tiling", "--displacement"], + &["--full", "--hq"], + ), ("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"], &[]), ]; @@ -155,7 +162,7 @@ fn print(v: &Value) { /// Open `--graph` and apply every `--set =` (the value is JSON, else a string) fn select_graph(h: &mut Headless, a: &Args) -> Result<(), String> { - if let Some(g) = a.get("--graph").map(graph_selector) { + if let Some(g) = selected_graph(a)? { h.command_run("graph.open", json!({"graph": g})).map_err(|e| e.to_string())?; } for (_, v) in a.flags.iter().filter(|(f, _)| f == "--set") { @@ -166,6 +173,15 @@ fn select_graph(h: &mut Headless, a: &Args) -> Result<(), String> { Ok(()) } +fn selected_graph(a: &Args) -> Result, String> { + match (a.get("--graph"), a.get("--graph-path")) { + (Some(_), Some(_)) => Err("use either --graph or --graph-path, not both".into()), + (_, Some(path)) => Ok(Some(json!(path))), + (Some(selector), None) => Ok(Some(graph_selector(selector))), + (None, None) => Ok(None), + } +} + fn graph_selector(selector: &str) -> Value { selector.parse::().map_or_else(|_| json!(selector), |index| json!(index)) } @@ -193,7 +209,7 @@ fn cook_parameters(a: &Args) -> Result { inputs.insert(id.to_string(), json!(value)); } } - let graph = a.get("--graph").map(graph_selector); + let graph = selected_graph(a)?; Ok(json!({"graph":graph,"size":a.get("--size").map(output_size).transpose()?,"preset":a.get("--preset"),"values":values,"inputs":inputs})) } @@ -285,8 +301,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { } "publish" => { let mut h = open(a.pos(0, "")?)?; - let graph = a.get("--graph").ok_or("publish requires --graph ")?; - let graph = graph_selector(graph); + let graph = selected_graph(a)?.ok_or("publish requires --graph or --graph-path ")?; print(&h.export_material(&json!({"path":a.pos(1,"")?, "graph":graph})).map_err(|e| e.to_string())?); } "cook" => { @@ -394,6 +409,16 @@ mod tests { v.iter().map(|s| s.to_string()).collect() } + #[test] + fn graph_paths_remain_literal_even_when_numeric() { + let a = parse("publish", &strings(&["--graph-path", "1"])).unwrap(); + assert_eq!(selected_graph(&a).unwrap(), Some(json!("1"))); + let a = parse("publish", &strings(&["--graph", "1"])).unwrap(); + assert_eq!(selected_graph(&a).unwrap(), Some(json!(1))); + let a = parse("publish", &strings(&["--graph", "1", "--graph-path", "1"])).unwrap(); + assert!(selected_graph(&a).is_err()); + } + #[test] fn automation_root_flags_are_aliases_of_the_short_ones() { for cmd in ["mcp", "serve"] { diff --git a/apps/materialcraft-cli/tests/published.rs b/apps/materialcraft-cli/tests/published.rs index fc888d4..7566359 100644 --- a/apps/materialcraft-cli/tests/published.rs +++ b/apps/materialcraft-cli/tests/published.rs @@ -13,8 +13,8 @@ fn run(dir: &Path, args: &[&str]) -> Value { #[test] fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() { - let dir = std::env::temp_dir().join(format!("materialcraft-cli-published-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().to_path_buf(); run(&dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]); run(&dir, &["run", "source.sbs", "graph.exposed.add", r#"{"id":"tint","bind":{"node":1,"param":"color"}}"#, "-o", "studio.mcraft"]); run(&dir, &["publish", "studio.mcraft", "oak.mcmat", "--graph", "Oak"]); @@ -45,13 +45,12 @@ fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() { let rectangular = run(&dir, &["cook", "oak.mcmat", "--size", "64x32"]); assert_eq!(rectangular["outputs"][0]["size"], json!([64, 32])); assert_eq!(run(&dir, &["info", "oak.mcmat"]), initial); - std::fs::remove_dir_all(&dir).unwrap(); } #[test] fn failed_materialx_reexport_preserves_the_last_complete_material() { - let dir = std::env::temp_dir().join(format!("materialcraft-cli-reexport-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().to_path_buf(); run(&dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]); let export = |folder, size| run(&dir, &["export", "source.sbs", folder, "--profile", "materialx", "--size", size]); let first = export("material", "32"); @@ -85,5 +84,4 @@ fn failed_materialx_reexport_preserves_the_last_complete_material() { for (name, bytes) in original_files { assert_eq!(std::fs::read(material.join(name)).unwrap(), bytes, "{name}"); } - std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index b938cb4..3b96171 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -26,4 +26,5 @@ getrandom = { workspace = true } rustix = { workspace = true } [dev-dependencies] +tempfile = "3" rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/server/parameter/material_export_params.rs b/crates/automation/src/server/parameter/material_export_params.rs index 4998b93..4e94b51 100644 --- a/crates/automation/src/server/parameter/material_export_params.rs +++ b/crates/automation/src/server/parameter/material_export_params.rs @@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; #[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] pub struct MaterialExportParams { /// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The /// parent folder must exist @@ -11,3 +12,19 @@ pub struct MaterialExportParams { #[serde(default, skip_serializing_if = "Option::is_none")] pub graph: Option, } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn material_publication_rejects_legacy_bake_size() { + for size in [json!(256), json!(null)] { + let error = serde_json::from_value::(json!({"path":"material", "size":size})).unwrap_err(); + assert!(error.to_string().contains("unknown field `size`")); + } + let params = serde_json::from_value::(json!({"path":"material", "graph":"Materials/Oak"})).unwrap(); + assert_eq!(params.graph, Some(json!("Materials/Oak"))); + } +} diff --git a/crates/automation/tests/package_files.rs b/crates/automation/tests/package_files.rs index ea5c38b..f3a4a37 100644 --- a/crates/automation/tests/package_files.rs +++ b/crates/automation/tests/package_files.rs @@ -4,7 +4,8 @@ use serde_json::json; #[test] fn reopening_relative_paths_activates_the_existing_document_and_preserves_edits() { - let root = std::env::temp_dir().join(format!("materialcraft-workspace-reopen-{}", std::process::id())); + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().to_path_buf(); std::fs::create_dir_all(&root).unwrap(); for extension in ["sbs", "mcraft"] { @@ -42,13 +43,12 @@ fn reopening_relative_paths_activates_the_existing_document_and_preserves_edits( assert!(root.join(&filename).is_file()); assert_eq!(reopened.session.path.as_deref(), Some(filename.as_str())); } - - std::fs::remove_dir_all(root).unwrap(); } #[test] fn both_formats_save_and_reopen_using_separate_workspace_capabilities() { - let root = std::env::temp_dir().join(format!("materialcraft-workspace-packages-{}", std::process::id())); + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().to_path_buf(); let input = root.join("input"); let output = root.join("output"); std::fs::create_dir_all(&input).unwrap(); @@ -83,14 +83,14 @@ fn both_formats_save_and_reopen_using_separate_workspace_capabilities() { // Release workspace directory handles before Windows removes the test tree drop(app); - std::fs::remove_dir_all(root).unwrap(); } #[test] fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_root() { use materialcraft_engine::core::{Graph, GraphInstance, GraphPort, Value}; use materialcraft_engine::{formats, samples}; - let dir = std::env::temp_dir().join(format!("materialcraft-publish-workspace-{}", std::process::id())); + let temporary = tempfile::tempdir().unwrap(); + let dir = temporary.path().to_path_buf(); let input = dir.join("input"); let output = dir.join("published"); std::fs::create_dir_all(input.join("parts")).unwrap(); @@ -126,6 +126,11 @@ fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_r let (pkg, entry) = formats::material::read_material(&std::fs::read(output.join("surface.sbs.mcmat")).unwrap()).unwrap(); assert_eq!(pkg.graph(entry).unwrap().name, "Oak"); assert_eq!(pkg.graphs.len(), 2); + assert!(pkg.graphs.iter().any(|graph| graph.name == "Finish")); + let calls: Vec<_> = pkg.graph(entry).unwrap().instances().collect(); + assert_eq!(calls.len(), 1); + assert!(calls[0].package.is_empty()); + assert!(pkg.graph_by_name(&calls[0].graph).is_some()); // Saving under a different granted root rebases links from that actual // destination, not from the process working directory or a relative path. @@ -155,9 +160,12 @@ fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_r assert!(reopened.session.pkg.dependencies.values().any(|dependency| dependency.name == "Helpers")); } } else { - assert!(result.is_err()); + let error = result.unwrap_err().to_string(); + assert!(error.contains("the instanced graph does not exist"), "{error}"); + let outside = dir.join("outside.sbs").canonicalize().unwrap().to_string_lossy().into_owned(); + assert!(!app.session.pkg.dependencies.contains_key(&outside)); + assert!(!app.session.pkg.dependencies.values().any(|dependency| dependency.name == "Helpers")); assert!(!output.join("missing.sbs.mcmat").exists()); } } - std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/export_request.rs b/crates/engine/src/export_request.rs index 5bf059a..1057559 100644 --- a/crates/engine/src/export_request.rs +++ b/crates/engine/src/export_request.rs @@ -36,7 +36,13 @@ impl ExportRequest { /// Read `file.export` params, checking them against the session's package pub fn from_params(s: &Session, p: &J) -> Result { - let graph_index = crate::graph_cmds::graph_index(s, p)?; + // Keep file.export's historical numeric selector coercion (including JSON 1.0) + // while allowing the new exact SBS path selector without changing other commands. + let graph_index = if p.get("graph").is_some_and(J::is_number) { + u64p(p, "graph").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(CMD, "`graph` must be a nonnegative index"))? + } else { + crate::graph_cmds::graph_index(s, p)? + }; let graph = s.pkg.graph(graph_index)?; let format = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); @@ -141,3 +147,24 @@ pub(crate) fn export_size(value: Option<&J>) -> Result> { }, } } + +#[cfg(test)] +mod selector_tests { + use super::*; + use serde_json::json; + + #[test] + fn file_export_keeps_numeric_coercion_and_exact_graph_paths() { + let mut package = materialcraft_core::Package::new("selectors"); + package.graphs.push(Graph::new("1")); + package.graphs.push(Graph::new("Second")); + let session = Session::new(package); + for selector in [json!(1), json!(1.0), json!(0.6)] { + assert_eq!(ExportRequest::from_params(&session, &json!({"graph":selector})).unwrap().graph, 1); + } + assert_eq!(ExportRequest::from_params(&session, &json!({"graph":"1"})).unwrap().graph, 0); + for selector in [json!(-1), json!(2.0), json!(1e100)] { + assert!(ExportRequest::from_params(&session, &json!({"graph":selector})).is_err()); + } + } +} diff --git a/crates/engine/src/linked_files.rs b/crates/engine/src/linked_files.rs index 2d288f4..eec6469 100644 --- a/crates/engine/src/linked_files.rs +++ b/crates/engine/src/linked_files.rs @@ -82,6 +82,7 @@ fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str) use std::{collections::BTreeSet, sync::Arc}; let mut visited = BTreeSet::new(); let mut warnings = Vec::new(); + let mut reads = 0; while let Some(path) = pending.pop() { if !visited.insert(path.clone()) { continue; @@ -92,10 +93,13 @@ fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str) continue; } - if visited.len() > 4096 { + // Cached snapshots need traversal, but must not consume the new-read budget. + // Count failed attempts too; visited still prevents repeated reads and cycles. + if reads >= 4096 { warnings.push("linked material exceeds the package dependency limit".into()); break; } + reads += 1; match read(&path) { Ok(read) => { warnings.extend(read.warnings); @@ -112,3 +116,46 @@ fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str) warnings } + +#[cfg(test)] +mod tests { + use super::*; + use std::{cell::Cell, sync::Arc}; + + #[test] + fn cached_paths_do_not_spend_the_new_dependency_read_budget() { + for cached_first in [true, false] { + let mut package = Package::new("root"); + let mut pending = vec!["new".to_string()]; + for i in 0..4096 { + let name = format!("cached{i}"); + package.dependencies.insert(name.clone(), Arc::new(Package::new(&name))); + pending.push(name); + } + if !cached_first { + pending.reverse(); + } + let calls = Cell::new(0); + let warnings = resolve(&mut package, pending, &|path| { + calls.set(calls.get() + 1); + assert_eq!(path, "new"); + Ok(materialcraft_formats::sbs::SbsRead { pkg: Package::new(path), warnings: vec![] }) + }); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(calls.get(), 1); + assert!(package.dependencies.contains_key("new")); + } + } + + #[test] + fn failed_new_reads_still_spend_the_budget_and_duplicates_do_not() { + let calls = Cell::new(0); + let pending = (0..4097).flat_map(|i| [format!("missing{i}"), format!("missing{i}")]).collect(); + let warnings = resolve(&mut Package::new("root"), pending, &|_| { + calls.set(calls.get() + 1); + Err("missing".into()) + }); + assert_eq!(calls.get(), 4096); + assert!(warnings.last().unwrap().contains("dependency limit")); + } +} diff --git a/crates/engine/src/material_bake.rs b/crates/engine/src/material_bake.rs index 20e30a4..0ce8862 100644 --- a/crates/engine/src/material_bake.rs +++ b/crates/engine/src/material_bake.rs @@ -89,6 +89,15 @@ pub fn cook(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Resul /// Encode every file before the caller writes to its destination. Paths in the report are relative. pub fn export(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Result<(Vec, J)> { let request = ExportRequest::from_params(s, p)?; + let has = |key| p.get(key).is_some_and(|value| !value.is_null()); + if has("profile") { + if has("format") || has("pattern") { + return Err(bad("file.export", "named profiles choose their own format and filenames; omit format and pattern")); + } + } else if has("normalFormat") || has("displacementScale") { + return Err(bad("file.export", "normalFormat and displacementScale require an explicit export profile")); + } + let graph = s.pkg.graph(request.graph)?; let options = MaterialOptions::from_params(graph, p, read)?; let selected = request.outputs.as_deref(); @@ -117,7 +126,8 @@ pub fn export(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Res let cooked = options.cook(s, request.graph, selected, None)?; let (files, mut report) = encode_maps(graph, &cooked, &request, materialx, scale, normal_y_down)?; - let mut interface = info(s, p)?; + // Use the graph already selected by file.export, including its legacy numeric coercion. + let mut interface = info(s, &json!({"graph": request.graph}))?; if let Some(params) = interface["parameters"].as_array_mut() { for parameter in params { if let Some(value) = parameter["id"].as_str().and_then(|id| options.values.get(id)) { @@ -209,6 +219,9 @@ fn encode_maps( }; let float = height || request.depth == Some(Depth::F32) || image.data().iter().any(|value| !(0.0..=1.0).contains(value)); + if float && request.color_spaces.get(&identifier).is_some_and(|space| space.encodes_srgb()) { + return Err(bad("file.export", format!("EXR output `{identifier}` requires linear values; omit the sRGB override or select raw or linear"))); + } let (ext, depth) = if float { ("exr", Depth::F32) } else { diff --git a/crates/engine/src/material_cmds.test.rs b/crates/engine/src/material_cmds.test.rs index 6f074ae..3065c8e 100644 --- a/crates/engine/src/material_cmds.test.rs +++ b/crates/engine/src/material_cmds.test.rs @@ -405,3 +405,70 @@ fn published_disabled_and_typed_instance_cooks_match_source() { assert_eq!(restored, original); assert!((restored[0] - 0.2).abs() < 0.01, "disabled levels must preserve its input: {restored:?}"); } + +#[test] +fn material_options_ignore_stale_presets_but_validate_explicit_values() { + let mut session = fixture(); + let graph = session.graph_mut().unwrap(); + graph.presets[0].values.insert("removed".into(), Value::Float(0.5)); + graph.presets[0].values.insert("tint".into(), Value::Text("old type".into())); + let before = graph.clone(); + let read = |_: &str| -> crate::Result> { Err(crate::EngineError::Other("unexpected image read".into())) }; + let options = MaterialOptions::from_params(graph, &json!({"preset":"Dark"}), read).unwrap(); + assert!(options.values.is_empty()); + let options = MaterialOptions::from_params(graph, &json!({"preset":"Dark", "values":{"tint":[0.7,0.6,0.5,1.0]}}), read).unwrap(); + assert_eq!(options.values.len(), 1); + assert_eq!(options.values["tint"], Value::Color([0.7, 0.6, 0.5, 1.0])); + assert!(MaterialOptions::from_params(graph, &json!({"values":{"removed":0.5}}), read).is_err()); + assert!(MaterialOptions::from_params(graph, &json!({"values":{"tint":"wrong"}}), read).is_err()); + assert_eq!(*graph, before); +} + +#[test] +fn material_options_size_errors_name_the_material_command() { + let session = fixture(); + let parameters = json!({"size":"bad"}); + let error = + MaterialOptions::from_params(session.graph().unwrap(), ¶meters, |_| Err(crate::EngineError::Other("unexpected image read".into()))).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { cmd, msg } if cmd == "material.cook" && msg.contains("size"))); + let error = crate::export_request::export_size(parameters.get("size")).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { cmd, msg } if cmd == "file.export" && msg.contains("size"))); +} + +#[test] +fn named_profiles_reject_ignored_format_and_pattern() { + let session = fixture(); + for extra in [json!({"format":"jpg"}), json!({"pattern":"oak_$(identifier)"})] { + let mut params = json!({"graph":"Materials/Oak","profile":"maps"}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let err = material_bake::export(&session, ¶ms, |_| panic!("invalid options must precede input reads")).err().expect("invalid export must fail"); + assert!(err.to_string().contains("omit format and pattern")); + } + let err = + material_bake::export(&session, &json!({"graph":"Materials/Oak","normalFormat":"directx"}), |_| panic!("invalid options must precede input reads")) + .err() + .expect("invalid export must fail"); + assert!(err.to_string().contains("require an explicit export profile")); +} + +#[test] +fn float_maps_reject_explicit_srgb_instead_of_ignoring_it() { + let session = fixture(); + let params = json!({"graph":"Materials/Oak","profile":"maps","outputs":["albedo"],"depth":32,"colorSpaces":{"albedo":"srgb"}}); + let err = material_bake::export(&session, ¶ms, material_bake::read_input).err().expect("invalid export must fail"); + assert!(err.to_string().contains("requires linear values")); +} + +#[test] +fn named_profiles_report_the_validated_numeric_graph_selector() { + let session = fixture(); + for profile in ["maps", "materialx"] { + for selector in [json!(1.0), json!(0.6)] { + let (files, report) = + material_bake::export(&session, &json!({"graph":selector,"profile":profile,"outputs":["albedo"],"size":16}), material_bake::read_input) + .unwrap(); + assert!(!files.is_empty()); + assert_eq!(report["material"]["graph"], "Materials/Oak"); + } + } +} diff --git a/crates/engine/src/material_options.rs b/crates/engine/src/material_options.rs index beb1f3d..493a7a7 100644 --- a/crates/engine/src/material_options.rs +++ b/crates/engine/src/material_options.rs @@ -18,12 +18,23 @@ pub struct MaterialOptions { impl MaterialOptions { pub fn from_params(graph: &Graph, p: &J, read: impl Fn(&str) -> Result>) -> Result { let invalid = |msg| bad("material.cook", msg); - let mut options = Self { size: crate::export_request::export_size(p.get("size"))?, ..Default::default() }; + let size = crate::export_request::export_size(p.get("size")).map_err(|error| match error { + crate::EngineError::BadParams { msg, .. } => invalid(msg), + other => other, + })?; + let mut options = Self { size, ..Default::default() }; if let Some(value) = p.get("preset").filter(|v| !v.is_null()) { let name = value.as_str().ok_or_else(|| invalid("preset must be a name".into()))?; let preset = graph.presets.iter().find(|preset| preset.name == name).ok_or_else(|| invalid(format!("unknown preset `{name}`")))?; - options.values.clone_from(&preset.values); + // Match preset.apply: stale identifiers and changed parameter types are ignored. + options.values.extend( + preset + .values + .iter() + .filter(|(id, value)| graph.exposed.iter().any(|parameter| parameter.id == **id && parameter.default.type_name() == value.type_name())) + .map(|(id, value)| (id.clone(), value.clone())), + ); } if let Some(value) = p.get("values").filter(|v| !v.is_null()) { diff --git a/crates/formats/src/material/snapshot_builder.rs b/crates/formats/src/material/snapshot_builder.rs index 59bb2b7..47093f2 100644 --- a/crates/formats/src/material/snapshot_builder.rs +++ b/crates/formats/src/material/snapshot_builder.rs @@ -27,7 +27,7 @@ type Key = (String, usize); struct SnapshotBuilder<'a> { root: &'a Package, result: Package, - paths: BTreeMap, + paths: BTreeMap, active: BTreeSet, resources: BTreeMap<(String, String), String>, nodes: usize, @@ -42,24 +42,31 @@ impl<'a> SnapshotBuilder<'a> { self.root.dependencies.get(owner).map(AsRef::as_ref).ok_or_else(|| bad(format!("missing source package `{owner}`"))) } - fn reference(&mut self, owner: &str, name: &str) -> Result { + fn reference(&mut self, owner: &str, name: &str, height: &mut usize) -> Result { let (index, _) = self.package(owner)?.graph_by_name(name).ok_or_else(|| bad(format!("missing or ambiguous graph `{name}` in `{owner}`")))?; - self.copy_graph(owner, index) + let (path, child_height) = self.copy_graph(owner, index)?; + *height = (*height).max(child_height + 1); + Ok(path) } - fn copy_graph(&mut self, owner: &str, index: usize) -> Result { + fn copy_graph(&mut self, owner: &str, index: usize) -> Result<(String, usize)> { let key = (owner.to_owned(), index); let source = self.package(owner)?.graph(index).map_err(|e| bad(e.to_string()))?; if self.active.contains(&key) { return Err(bad(format!("cyclic graph reference at `{}`", source.sbs_path()))); } - if let Some(path) = self.paths.get(&key) { - return Ok(path.clone()); + // Bound the complete path, including a shared tail copied on an earlier branch. + // Active entries are rejected above, so cached heights here are complete. + const MAX_DEPENDENCY_DEPTH: usize = 32; + if let Some((path, height)) = self.paths.get(&key) { + if self.active.len() + height > MAX_DEPENDENCY_DEPTH { + return Err(bad("published graph dependencies exceed the depth or graph count limit")); + } + return Ok((path.clone(), *height)); } // Bound publishing independently of the cooker's per-function and per-instance limits - const MAX_DEPENDENCY_DEPTH: usize = 32; if self.active.len() >= MAX_DEPENDENCY_DEPTH || self.paths.len() >= crate::sbs::MAX_GRAPHS { return Err(bad("published graph dependencies exceed the depth or graph count limit")); } @@ -87,11 +94,12 @@ impl<'a> SnapshotBuilder<'a> { graph.folder = if self.paths.is_empty() { String::new() } else { format!("Dependencies/g{}", self.paths.len()) }; let path = graph.sbs_path(); - self.paths.insert(key.clone(), path.clone()); + self.paths.insert(key.clone(), (path.clone(), 0)); + let mut height = 1; self.active.insert(key.clone()); for instance in graph.instances_mut() { let package = if instance.package.is_empty() { owner } else { &instance.package }; - instance.graph = self.reference(package, &instance.graph)?; + instance.graph = self.reference(package, &instance.graph, &mut height)?; instance.package.clear(); } for node in &mut graph.nodes { @@ -103,7 +111,7 @@ impl<'a> SnapshotBuilder<'a> { if let Some(instance) = &node.instance { node.params.insert("graph".into(), Value::Text(instance.graph.clone())); } else if let Some(Value::Text(target)) = node.params.get_mut("graph") { - *target = self.reference(owner, target)?; + *target = self.reference(owner, target, &mut height)?; } else { return Err(bad(format!("missing graph reference in `{path}`"))); } @@ -131,8 +139,9 @@ impl<'a> SnapshotBuilder<'a> { } self.active.remove(&key); + self.paths.insert(key, (path.clone(), height)); self.result.graphs.push(graph); - Ok(path) + Ok((path, height)) } fn resource(&mut self, owner: &str, name: &str) -> Result { @@ -163,3 +172,54 @@ pub fn entry_graph(pkg: &Package) -> Result { _ => Err(bad("source.sbs must have exactly one root material graph; put helper graphs and functions in a dependency folder")), } } + +#[cfg(test)] +mod tests { + use super::*; + + fn graph(name: &str, children: &[String]) -> Graph { + let mut graph = Graph::new(name); + if children.is_empty() { + let source = graph.add_node("uniform", [0.0; 2]); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(source, "output", output, "input").unwrap(); + } + for child in children { + let source = graph.add_node("graph_instance", [0.0; 2]); + graph.node_mut(source).unwrap().params.insert("graph".into(), Value::Text(child.clone())); + let output = graph.add_node("output", [0.0; 2]); + graph.connect(source, "output", output, "input").unwrap(); + } + graph + } + + fn shared_tail(chain: usize, tail: usize, cached_first: bool) -> Package { + let mut package = Package::new("depth"); + let mut children = vec!["tail0".into(), "chain0".into()]; + if !cached_first { + children.reverse(); + } + package.graphs.push(graph("root", &children)); + for i in 0..chain { + let next = if i + 1 == chain { "tail0".into() } else { format!("chain{}", i + 1) }; + package.graphs.push(graph(&format!("chain{i}"), &[next])); + } + for i in 0..tail { + let children = if i + 1 == tail { vec![] } else { vec![format!("tail{}", i + 1)] }; + package.graphs.push(graph(&format!("tail{i}"), &children)); + } + package + } + + #[test] + fn cached_graph_depth_is_independent_of_reference_order() { + for cached_first in [true, false] { + // Root + chain + shared tail: 32 is valid, 33 is not. The cached + // tail can itself contain dependencies, not just a leaf. + for tail in [1, 5] { + assert!(snapshot(&shared_tail(31 - tail, tail, cached_first), 0).is_ok()); + assert!(snapshot(&shared_tail(32 - tail, tail, cached_first), 0).is_err()); + } + } + } +} diff --git a/crates/ui-egui/src/export/export_tests.rs b/crates/ui-egui/src/export/export_tests.rs index c1c69cb..c3f83c7 100644 --- a/crates/ui-egui/src/export/export_tests.rs +++ b/crates/ui-egui/src/export/export_tests.rs @@ -155,3 +155,29 @@ fn material_dialog_identity_is_not_saved_in_preferences() { let restored: ExportSettings = serde_json::from_value(stored).unwrap(); assert_eq!(restored.material.document, None); } + +#[test] +fn folder_graphs_keep_independent_output_selection_and_color_spaces() { + let app = app(); + let mut indoor = app.session.graph().unwrap().clone(); + indoor.name = "Oak".into(); + indoor.folder = "Indoor".into(); + let mut outdoor = indoor.clone(); + outdoor.folder = "Outdoor".into(); + let mut settings = ExportSettings::default(); + settings.include_all(&indoor, false); + assert!(settings.selection(&indoor).is_none()); + assert!(settings.selection(&outdoor).is_some()); + settings.include_all(&indoor, true); + settings.color_spaces.insert(output_key(&indoor.sbs_path(), "base_color"), materialcraft_engine::ColorSpace::Linear); + assert_eq!(settings.selection(&indoor).unwrap().1["base_color"], "linear"); + assert_eq!(settings.selection(&outdoor).unwrap().1["base_color"], "srgb"); +} + +#[test] +fn material_export_reports_missing_shader_connections_on_every_platform() { + assert_eq!(material_export_message(&Value::Null), tr("Material exported")); + let message = material_export_message(&json!({"unmapped":["custom_output"]})); + assert!(message.contains(tr("Exported without shader connections"))); + assert!(message.contains("custom_output")); +} diff --git a/crates/ui-egui/src/export/mod.rs b/crates/ui-egui/src/export/mod.rs index e7ec810..06c0a20 100644 --- a/crates/ui-egui/src/export/mod.rs +++ b/crates/ui-egui/src/export/mod.rs @@ -241,7 +241,7 @@ pub(super) fn path_field(ui: &mut Ui, path: &mut String, width: f32) -> bool { /// The file name the first checked output of `graph` is written to fn preview_file(settings: &ExportSettings, graph: &Graph) -> Option { - let output = outputs::listed(graph).into_iter().find(|output| settings.includes(&graph.name, &output.identifier))?; + let output = outputs::listed(graph).into_iter().find(|output| settings.includes(&graph.sbs_path(), &output.identifier))?; let name = materialcraft_engine::formats::output_name(&settings.pattern, &graph.name, &output.identifier, output.usage); Some(format!("{name}.{}", settings.format)) } @@ -422,21 +422,25 @@ fn publish(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool { let result = if command == "file.exportMaterial" { materialcraft_engine::material_cmds::material_bytes(&app.session, index).map_err(|e| e.to_string()).and_then(|bytes| { let name = format!("{}.mcmat", materialcraft_engine::formats::safe_file_name(&graph.name)); - crate::web_files::download(&name, &bytes) + crate::web_files::download(&name, &bytes).map(|()| Value::Null) }) } else { materialcraft_engine::material_bake::export(&app.session, ¶ms, materialcraft_engine::material_bake::read_input) .map_err(|e| e.to_string()) - .and_then(|(files, _)| { + .and_then(|(files, report)| { let files = files.into_iter().map(|f| (f.file, f.bytes)).collect::>(); crate::web_files::download( &format!("{}_materialx.zip", materialcraft_engine::formats::safe_file_name(&graph.name)), &crate::web_files::zip_files(&files)?, ) + .map(|()| report) }) }; match result { - Ok(()) => true, + Ok(report) => { + app.toast(material_export_message(&report), false); + true + } Err(error) => { app.toast(error, true); false @@ -459,14 +463,14 @@ pub(crate) fn poll(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.material_export_job = None; match result { Ok(report) => { - let unmapped = report["unmapped"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::>(); - let message = if unmapped.is_empty() { - tr("Material exported").to_string() - } else { - format!("{}: {}", tr("Exported without shader connections"), unmapped.join(", ")) - }; - app.toast(message, false); + app.toast(material_export_message(&report), false); } Err(error) => app.toast(error, true), } } + +/// Keep native and browser exports explicit about omitted shader connections. +fn material_export_message(report: &Value) -> String { + let unmapped = report["unmapped"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::>(); + if unmapped.is_empty() { tr("Material exported").to_string() } else { format!("{}: {}", tr("Exported without shader connections"), unmapped.join(", ")) } +} diff --git a/crates/ui-egui/src/export/outputs.rs b/crates/ui-egui/src/export/outputs.rs index fa04d41..6e9fc65 100644 --- a/crates/ui-egui/src/export/outputs.rs +++ b/crates/ui-egui/src/export/outputs.rs @@ -41,7 +41,7 @@ impl ExportSettings { /// Check or uncheck every output of `graph` pub fn include_all(&mut self, graph: &Graph, include: bool) { for output in listed(graph) { - let key = output_key(&graph.name, &output.identifier); + let key = output_key(&graph.sbs_path(), &output.identifier); if include { self.skipped_outputs.remove(&key); } else { @@ -53,7 +53,7 @@ impl ExportSettings { /// The `file.export` `outputs` and `colorSpaces` for `graph`; `None` when none of its outputs is checked pub fn selection(&self, graph: &Graph) -> Option<(Value, Value)> { let outputs = listed(graph); - let included: Vec<&ListedOutput> = outputs.iter().filter(|output| self.includes(&graph.name, &output.identifier)).collect(); + let included: Vec<&ListedOutput> = outputs.iter().filter(|output| self.includes(&graph.sbs_path(), &output.identifier)).collect(); if included.is_empty() { return None; } @@ -61,7 +61,7 @@ impl ExportSettings { let identifiers = if included.len() == outputs.len() { Value::Null } else { json!(included.iter().map(|output| &output.identifier).collect::>()) }; let color_spaces: serde_json::Map = - included.iter().map(|output| (output.identifier.clone(), json!(self.color_space(&graph.name, output).id()))).collect(); + included.iter().map(|output| (output.identifier.clone(), json!(self.color_space(&graph.sbs_path(), output).id()))).collect(); Some((identifiers, Value::Object(color_spaces))) } } @@ -77,8 +77,8 @@ pub fn tree(ui: &mut Ui, settings: &mut ExportSettings, graphs: &[&Graph]) { egui::ScrollArea::vertical().id_salt("export-outputs").max_height(240.0).auto_shrink([false, true]).show(ui, |ui| { for graph in graphs { let outputs = listed(graph); - let included = outputs.iter().filter(|output| settings.includes(&graph.name, &output.identifier)).count(); - let id = ui.make_persistent_id(("export-graph", &graph.name)); + let included = outputs.iter().filter(|output| settings.includes(&graph.sbs_path(), &output.identifier)).count(); + let id = ui.make_persistent_id(("export-graph", graph.sbs_path())); egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) .show_header(ui, |ui| { let mut all = !outputs.is_empty() && included == outputs.len(); @@ -102,10 +102,10 @@ fn outputs_grid(ui: &mut Ui, settings: &mut ExportSettings, graph: &Graph, outpu return; } - egui::Grid::new(("export-outputs-grid", &graph.name)).num_columns(2).min_col_width(OUTPUT_COLUMN_WIDTH).spacing([8.0, 4.0]).show(ui, |ui| { + egui::Grid::new(("export-outputs-grid", graph.sbs_path())).num_columns(2).min_col_width(OUTPUT_COLUMN_WIDTH).spacing([8.0, 4.0]).show(ui, |ui| { for output in outputs { - let key = output_key(&graph.name, &output.identifier); - let mut included = settings.includes(&graph.name, &output.identifier); + let key = output_key(&graph.sbs_path(), &output.identifier); + let mut included = settings.includes(&graph.sbs_path(), &output.identifier); let checkbox = ui.checkbox(&mut included, &output.identifier); crate::widgets::name(&checkbox, egui::Role::CheckBox, &output.identifier); if checkbox.changed() { @@ -116,14 +116,14 @@ fn outputs_grid(ui: &mut Ui, settings: &mut ExportSettings, graph: &Graph, outpu } } - let mut space = settings.color_space(&graph.name, output); + let mut space = settings.color_space(&graph.sbs_path(), output); let combo = egui::ComboBox::from_id_salt(("export-color-space", &key)).width(110.0).selected_text(space.label()).show_ui(ui, |ui| { for choice in ColorSpace::ALL { ui.selectable_value(&mut space, choice, choice.label()); } }); crate::widgets::name(&combo.response, egui::Role::ComboBox, &format!("{} {}", output.identifier, tr("color space"))); - if space != settings.color_space(&graph.name, output) { + if space != settings.color_space(&graph.sbs_path(), output) { settings.color_spaces.insert(key, space); } ui.end_row(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0ee364d..adead15 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -366,6 +366,11 @@ The ZIP contains a version marker (`material.json` with `{"version":3}`), a DEFL TextureCraft requests `--profile maps` at its texture set's resolution and supplies mesh maps through repeated `--input identifier=path`. Common identifiers include `ambientOcclusion`, `curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`, `opacity`, `colorMap` and `worldDirection`. An image override uses the published preview binding’s color space when present. Otherwise the input’s declared usage determines the transfer, with the identifier as a fallback for untagged inputs. The JSON report lists each map's identifier, usage, filename, color space and actual dimensions. +Named bake profiles select their own output formats and filenames: do not supply `format` or `pattern`. +`normalFormat` requires an explicit bake profile. Explicit sRGB overrides are refused for floating-point +EXR outputs; omit the override or choose raw/linear. The CLI's `--graph-path` selects a literal SBS path, +including a numeric name, while `--graph` retains numeric-index shorthand. + The `materialx` profile writes `material.mtlx` with relative texture paths and an OpenPBR surface. Color textures default to sRGB PNG, data textures to linear 16-bit PNG, and out-of-range values to floating-point EXR. Both bake profiles write tangent-space Y+ normals. A directly connected Normal node supplies its evaluated convention, including through routing dots. Other normal sources default to Y+. Use `--normal-format directx` for a Y− source or `--normal-format opengl` for Y+. OpenPBR scalar and normal inputs require linear data. Height becomes signed EXR displacement in scene units using `(height - 0.5) × displacementScale`. The CLI accepts `--displacement-scale`. MaterialX texture filenames include a hash of the output name and bytes. Re-export writes the document last and keeps earlier texture versions, so a failed export leaves the previous material usable. Outputs without an OpenPBR connection are written alongside the document and listed in `unmapped`. | Command | Params |