diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index cb6e7450..dde93050 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -33,6 +33,7 @@ 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. --displacement-scale scales signed MaterialX displacement (default 1). materialcraft-cli render [--size x] [--view 3d|2d] [--scene ] [--node ] [--yaw ] [--pitch ] [--graph ] [--set =]... [--full] @@ -61,7 +62,24 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("batch", &[], &[]), ("new", &["--size", "--name"], &[]), ("cook", &["--graph", "--set", "--size", "--input", "--preset"], &["--full"]), - ("export", &["--graph", "--set", "--format", "--depth", "--size", "--pattern", "--profile", "--input", "--preset", "--out", "--displacement-scale"], &[]), + ( + "export", + &[ + "--graph", + "--set", + "--format", + "--depth", + "--size", + "--pattern", + "--profile", + "--input", + "--preset", + "--out", + "--displacement-scale", + "--normal-format", + ], + &[], + ), ("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--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"], &[]), @@ -289,6 +307,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { p["depth"] = json!(a.num::("--depth")?); p["pattern"] = json!(a.get("--pattern")); p["profile"] = json!(a.get("--profile")); + p["normalFormat"] = json!(a.get("--normal-format")); p["displacementScale"] = json!(a.num::("--displacement-scale")?); print(&h.export(&p).map_err(|e| e.to_string())?); } diff --git a/apps/materialcraft-cli/tests/published.rs b/apps/materialcraft-cli/tests/published.rs index 997566f3..fc888d4d 100644 --- a/apps/materialcraft-cli/tests/published.rs +++ b/apps/materialcraft-cli/tests/published.rs @@ -47,3 +47,43 @@ fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() { 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(); + 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"); + let added = run(&dir, &["run", "source.sbs", "graph.node.add", r#"{"def":"output","params":{"identifier":"extra"}}"#, "-o", "source.sbs"]); + let wire = json!({"from":1,"to":added["id"],"toPort":"input"}).to_string(); + run(&dir, &["run", "source.sbs", "graph.connect", &wire, "-o", "source.sbs"]); + let next = export("reference", "64"); + let material = dir.join("material"); + let original_files: Vec<_> = first["maps"] + .as_array() + .unwrap() + .iter() + .map(|map| { + let name = map["file"].as_str().unwrap(); + (name, std::fs::read(material.join(name)).unwrap()) + }) + .collect(); + let document = std::fs::read(material.join("material.mtlx")).unwrap(); + let extra = next["maps"].as_array().unwrap().iter().find(|map| map["identifier"] == "extra").unwrap(); + let blocked = material.join(extra["file"].as_str().unwrap()); + std::fs::create_dir(&blocked).unwrap(); + + let failed = Command::new(env!("CARGO_BIN_EXE_materialcraft-cli")) + .current_dir(&dir) + .args(["export", "source.sbs", "material", "--profile", "materialx", "--size", "64"]) + .output() + .unwrap(); + + assert!(!failed.status.success()); + assert_eq!(std::fs::read(material.join("material.mtlx")).unwrap(), document); + 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/src/server/parameter/export_params.rs b/crates/automation/src/server/parameter/export_params.rs index 0a941f65..2ffd6c6d 100644 --- a/crates/automation/src/server/parameter/export_params.rs +++ b/crates/automation/src/server/parameter/export_params.rs @@ -14,9 +14,10 @@ pub struct ExportParams { /// 8, 16 or 32 bits (default: the graph's output format) #[serde(default, skip_serializing_if = "Option::is_none")] pub depth: Option, - /// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size) + /// The larger side or [width, height] in pixels, rounded down to powers of two from 16 to 8192. #[serde(default, skip_serializing_if = "Option::is_none")] - pub size: Option, + #[schemars(schema_with = "size_schema")] + pub size: Option, /// Graph index or full SBS path. Defaults to the open graph. #[serde(default, skip_serializing_if = "Option::is_none")] pub graph: Option, @@ -35,6 +36,9 @@ pub struct ExportParams { /// Height range in scene units for MaterialX displacement. #[serde(default, rename = "displacementScale", skip_serializing_if = "Option::is_none")] pub displacement_scale: Option, + /// Source tangent-space normal convention for baked maps. Omit to use the graph's convention. + #[serde(default, rename = "normalFormat", skip_serializing_if = "Option::is_none")] + pub normal_format: Option, /// Typed exposed parameter overrides for this cook. #[serde(default, skip_serializing_if = "Option::is_none")] #[schemars(schema_with = "values_schema")] @@ -44,6 +48,24 @@ pub struct ExportParams { pub inputs: Option>, } +fn size_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({"anyOf":[{"type":"integer","minimum":0},{"type":"array","minItems":2,"maxItems":2,"items":{"type":"integer","minimum":0}},{"type":"null"}]}) +} + fn values_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { schemars::json_schema!({"type":["object","null"],"additionalProperties":{}}) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn export_forwards_both_dimensions_and_the_source_normal_convention() { + let request = json!({"dir":".", "profile":"materialx", "size":[128,64], "normalFormat":"directx"}); + + let params: ExportParams = serde_json::from_value(request.clone()).unwrap(); + assert_eq!(serde_json::to_value(params).unwrap(), request); + } +} diff --git a/crates/engine/src/export_size.rs b/crates/engine/src/export_size.rs index 5c99a441..883d473e 100644 --- a/crates/engine/src/export_size.rs +++ b/crates/engine/src/export_size.rs @@ -1,5 +1,6 @@ /// The pixel size `file.export` cooks a graph at -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] pub enum ExportSize { /// The larger side in pixels; the other keeps the graph's proportions LargerSide(u32), @@ -13,9 +14,9 @@ impl ExportSize { match self { ExportSize::LargerSide(pixels) => { let target = log2_pixels(pixels); - let bounded = graph_size.map(|side| side.clamp(4, 13)); + let bounded = graph_size.map(|side| side.clamp(materialcraft_core::MIN_SIZE_LOG2, materialcraft_core::MAX_SIZE_LOG2)); let larger = bounded[0].max(bounded[1]); - bounded.map(|side| (side + target).saturating_sub(larger).max(4)) + bounded.map(|side| (side + target).saturating_sub(larger).max(materialcraft_core::MIN_SIZE_LOG2)) } ExportSize::Exact(pixels) => pixels.map(log2_pixels), } @@ -23,5 +24,5 @@ impl ExportSize { } fn log2_pixels(pixels: u32) -> u32 { - 31 - pixels.clamp(16, 8192).leading_zeros() + pixels.clamp(1 << materialcraft_core::MIN_SIZE_LOG2, 1 << materialcraft_core::MAX_SIZE_LOG2).ilog2() } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index b134e27f..501d012b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -38,7 +38,7 @@ pub(crate) fn specs() -> Vec { "Export outputs...", ["File"], Some("Ctrl+Shift+E"), - "{dir, format? (png|jpg|tga|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, or [width, height]; rounded down to powers of two, 16..8192; default the graph's size, keeping its proportions), outputs? ([identifier]: default every connected output), colorSpaces? ({identifier: srgb|linear|raw}: default sRGB for color usages, raw for data; linear and raw write values unchanged), graph?, profile? (maps|materialx), preset?, values? {parameter: value}, inputs? {identifier: image path}, displacementScale?} cooks the selected outputs and writes the requested export", + "{dir, format? (png|jpg|tga|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, or [width, height]; rounded down to powers of two, 16..8192; default the graph's size, keeping its proportions), outputs? ([identifier]: default every connected output), colorSpaces? ({identifier: srgb|linear|raw}: default sRGB for color usages, raw for data; linear and raw write values unchanged), graph?, profile? (maps|materialx), preset?, values? {parameter: value}, inputs? {identifier: image path}, normalFormat? (opengl|directx), displacementScale?} cooks the selected outputs and writes the requested export", has_graph, export ), @@ -326,7 +326,7 @@ fn save(_: &mut Session, _: &J) -> Result { /// Cook the requested graph at full size and encode its requested outputs (`pattern` names files) pub fn export_outputs(s: &Session, request: &ExportRequest) -> Result> { let options = crate::MaterialOptions { size: request.size, ..Default::default() }; - let cooked = options.cook(s, request.graph, None)?; + let cooked = options.cook(s, request.graph, request.outputs.as_deref(), None)?; encode_outputs(s.pkg.graph(request.graph)?, &cooked, request) } @@ -364,7 +364,9 @@ fn export(s: &mut Session, p: &J) -> Result { std::fs::create_dir_all(folder).map_err(|error| bad("file.export", format!("{dir}: {error}")))?; // Check every name first so a rejected export leaves the folder untouched - if let Some(existing) = files.iter().find(|exported| folder.join(&exported.file).exists()) { + if p.get("profile").and_then(J::as_str) != Some("materialx") + && let Some(existing) = files.iter().find(|exported| folder.join(&exported.file).exists()) + { return Err(bad( "file.export", format!("duplicate export filename `{}`: use unique output identifiers or a different filename pattern", existing.file), diff --git a/crates/engine/src/material_bake.rs b/crates/engine/src/material_bake.rs index a612337e..20e30a44 100644 --- a/crates/engine/src/material_bake.rs +++ b/crates/engine/src/material_bake.rs @@ -2,10 +2,11 @@ use std::collections::BTreeSet; use craft_texture::Kind; -use materialcraft_core::Graph; +use materialcraft_core::{Graph, GraphIndex, NodeId}; use materialcraft_eval::{Cooked, outputs}; use materialcraft_formats::{Depth, encode}; use serde_json::{Value as J, json}; +use sha2::{Digest, Sha256}; use crate::commands::{CommandSpec, bad, has_graph}; use crate::{ExportRequest, Exported, MaterialOptions, Result, Session, cmd, graph_cmds::graph_index}; @@ -67,7 +68,7 @@ pub(crate) fn check_publish(s: &Session, index: usize) -> Result<()> { if graph.function.is_some() { return Err(bad("file.exportMaterial", "select a material graph")); } - let cooked = MaterialOptions::default().cook(s, index, Some(16))?; + let cooked = MaterialOptions::default().cook(s, index, None, Some(1 << materialcraft_core::MIN_SIZE_LOG2))?; if !outputs(graph, &cooked).into_iter().any(|(id, _, _, image)| image.is_some() && graph.connections.iter().any(|wire| wire.to == id)) { return Err(bad("file.exportMaterial", format!("graph `{}` has no connected, cookable material outputs", graph.sbs_path()))); } @@ -77,7 +78,7 @@ pub(crate) fn check_publish(s: &Session, index: usize) -> Result<()> { pub fn cook(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Result { let index = graph_index(s, p)?; let graph = s.pkg.graph(index)?; - let cooked = MaterialOptions::from_params(graph, p, read)?.cook(s, index, None)?; + let cooked = MaterialOptions::from_params(graph, p, read)?.cook(s, index, None, None)?; Ok(json!({"graph":graph.sbs_path(),"ms":cooked.ms, "outputs":outputs(graph,&cooked).into_iter().filter_map(|(_,usage,id,image)| { let image = image?; @@ -90,30 +91,43 @@ pub fn export(s: &Session, p: &J, read: impl Fn(&str) -> Result>) -> Res let request = ExportRequest::from_params(s, p)?; let graph = s.pkg.graph(request.graph)?; let options = MaterialOptions::from_params(graph, p, read)?; - let cooked = options.cook(s, request.graph, None)?; - match p.get("profile").filter(|v| !v.is_null()) { - None => Ok((crate::file_cmds::encode_outputs(graph, &cooked, &request)?, json!({}))), - Some(profile) if profile == "maps" || profile == "materialx" => { - let scale = match p.get("displacementScale").filter(|v| !v.is_null()) { - Some(v) => { - v.as_f64().map(|x| x as f32).filter(|x| x.is_finite() && *x >= 0.0).ok_or_else(|| bad("file.export", "invalid displacementScale"))? - } - None => 1.0, - }; - let (files, mut report) = encode_maps(graph, &cooked, &request, profile == "materialx", scale)?; - let mut interface = info(s, p)?; - if let Some(params) = interface["parameters"].as_array_mut() { - for param in params { - if let Some(value) = param["id"].as_str().and_then(|id| options.values.get(id)) { - param["value"] = json!(value); - } - } + let selected = request.outputs.as_deref(); + let materialx = match p.get("profile").filter(|value| !value.is_null()) { + Some(value) if value == "materialx" => true, + Some(value) if value == "maps" => false, + Some(value) => return Err(bad("file.export", format!("unknown export profile {value}"))), + None => { + let cooked = options.cook(s, request.graph, selected, None)?; + return Ok((crate::file_cmds::encode_outputs(graph, &cooked, &request)?, json!({}))); + } + }; + + let scale = match p.get("displacementScale").filter(|value| !value.is_null()) { + Some(value) => { + value.as_f64().map(|x| x as f32).filter(|x| x.is_finite() && *x >= 0.0).ok_or_else(|| bad("file.export", "invalid displacementScale"))? + } + None => 1.0, + }; + let normal_y_down = match p.get("normalFormat").filter(|value| !value.is_null()) { + None => None, + Some(value) if value == "opengl" => Some(false), + Some(value) if value == "directx" => Some(true), + Some(_) => return Err(bad("file.export", "normalFormat must be opengl or directx")), + }; + + 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)?; + 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)) { + parameter["value"] = json!(value); } - report["material"] = interface; - Ok((files, report)) } - Some(value) => Err(bad("file.export", format!("unknown export profile {value}"))), } + + report["material"] = interface; + Ok((files, report)) } fn shader_input(usage: &str) -> Option<&'static str> { @@ -137,7 +151,34 @@ fn shader_input(usage: &str) -> Option<&'static str> { }) } -fn encode_maps(graph: &Graph, cooked: &Cooked, request: &ExportRequest, materialx: bool, scale: f32) -> Result<(Vec, J)> { +/// Direct normal generators expose their evaluated convention. Raw images default to OpenGL. +fn normal_y_down(index: &GraphIndex<'_>, cooked: &Cooked, output: NodeId) -> bool { + let mut source = output; + for _ in 0..cooked.nodes.len() { + let Some(node) = index.input_of(source, "input").and_then(|wire| index.node(wire.from)) else { break }; + if node.def == "normal" && !node.disabled { + return cooked.nodes.get(&node.id).and_then(|result| result.parameters.get("opengl")).and_then(materialcraft_core::Value::as_bool) == Some(false); + } + + if node.def != "dot" { + break; + } + + source = node.id; + } + + false +} + +fn encode_maps( + graph: &Graph, + cooked: &Cooked, + request: &ExportRequest, + materialx: bool, + scale: f32, + source_y_down: Option, +) -> Result<(Vec, J)> { + let index = GraphIndex::new(graph); let mut files = Vec::new(); let mut maps = Vec::new(); let mut textures = Vec::new(); @@ -145,38 +186,54 @@ fn encode_maps(graph: &Graph, cooked: &Cooked, request: &ExportRequest, material let mut names = BTreeSet::new(); let mut shader_inputs = BTreeSet::new(); for (id, usage, identifier, image) in outputs(graph, cooked) { - let Some(image) = image.filter(|_| request.includes(&identifier) && graph.connections.iter().any(|wire| wire.to == id)) else { continue }; + let Some(image) = image.filter(|_| request.includes(&identifier) && !index.incoming(id).is_empty()) else { continue }; + let shader = shader_input(usage); + let color = materialcraft_formats::material::srgb_usage(usage); + let space = request.color_space(&identifier, usage); + if materialx && shader.is_some() && !color && space.encodes_srgb() { + return Err(bad("file.export", format!("OpenPBR requires linear data for `{identifier}`; select raw or linear"))); + } + let height = materialx && usage == "height"; - // The shader's displacement input uses signed scene units; a mid-gray source height is neutral. - let signed; + + // MaterialX takes signed scene-unit displacement and tangent-space Y-up normals + let converted; let image = if height { - signed = image.map(Kind::Gray, |pixel| [(pixel[0] - 0.5) * scale, 0.0, 0.0, 1.0]); - &signed + converted = image.map(Kind::Gray, |pixel| [(pixel[0] - 0.5) * scale, 0.0, 0.0, 1.0]); + &converted + } else if matches!(usage, "normal" | "coatNormal") && source_y_down.unwrap_or_else(|| normal_y_down(&index, cooked, id)) { + converted = image.map(Kind::Color, |[r, g, b, a]| [r, 1.0 - g, b, a]); + &converted } else { image }; + let float = height || request.depth == Some(Depth::F32) || image.data().iter().any(|value| !(0.0..=1.0).contains(value)); let (ext, depth) = if float { ("exr", Depth::F32) } else { - ( - "png", - request.depth.unwrap_or(if matches!(usage, "normal" | "height") || !materialcraft_formats::material::srgb_usage(usage) { - Depth::U16 - } else { - Depth::U8 - }), - ) + let depth = request.depth.unwrap_or(if color { Depth::U8 } else { Depth::U16 }); + ("png", depth) }; - let file = format!("{}.{}", materialcraft_formats::safe_file_name(&identifier), ext); - if !names.insert(file.to_lowercase()) { - return Err(bad("file.export", format!("duplicate output filename `{file}`; give each output a unique identifier"))); + let stem = materialcraft_formats::safe_file_name(&identifier); + if !names.insert(format!("{stem}.{ext}").to_lowercase()) { + return Err(bad("file.export", format!("duplicate output filename `{stem}.{ext}`; give each output a unique identifier"))); } - let srgb = !float && request.color_space(&identifier, usage).encodes_srgb(); + + let srgb = !float && space.encodes_srgb(); let bytes = encode(image, ext, depth, srgb)?; + let file = if materialx { + // An interrupted re-export must leave every texture referenced by the previous document intact + const MAX_STEM_CHARS: usize = 32; + let digest = Sha256::new().chain_update(stem.as_bytes()).chain_update([0]).chain_update(&bytes).finalize(); + let prefix: String = stem.chars().take(MAX_STEM_CHARS).collect(); + format!("{prefix}-{digest:x}.{ext}") + } else { + format!("{stem}.{ext}") + }; maps.push(json!({"identifier":identifier,"usage":usage,"file":file,"size":[image.width(),image.height()],"colorSpace":if srgb {"srgb"}else{"linear"}})); if materialx { - if let Some(input) = shader_input(usage).filter(|i| shader_inputs.insert(*i)) { + if let Some(input) = shader.filter(|i| shader_inputs.insert(*i)) { textures.push(craft_materialx::Texture { input: input.into(), file: file.clone(), @@ -188,15 +245,19 @@ fn encode_maps(graph: &Graph, cooked: &Cooked, request: &ExportRequest, material } files.push(Exported { file, bytes }); } + if files.is_empty() { return Err(bad("file.export", "no connected image outputs were selected")); } + if materialx { if textures.is_empty() { return Err(bad("file.export", format!("no selected output maps to OpenPBR: {}", unmapped.join(", ")))); } + let doc = craft_materialx::write_open_pbr(&graph.name, &textures, None); files.push(Exported { file: "material.mtlx".into(), bytes: doc.into_bytes() }); } + Ok((files, json!({"maps":maps,"unmapped":unmapped,"normalOrientation":"Y+","displacementScale":scale}))) } diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index 8dec0049..248ca69d 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -58,7 +58,8 @@ pub fn image_inputs(g: &Graph) -> Vec { for n in g.nodes.iter().filter(|n| matches!(n.def.as_str(), "input_grayscale" | "input_color")) { let identifier = materialcraft_eval::identifier(n); if !out.iter().any(|i| i.identifier == identifier) { - out.push(ImageInput { identifier, kind: if n.def == "input_grayscale" { "gray" } else { "color" }.into() }); + let usage = if n.params.contains_key("usage") { materialcraft_eval::output_usage(n) } else { "any" }; + out.push(ImageInput { identifier, kind: if n.def == "input_grayscale" { "gray" } else { "color" }.into(), usage: usage.into() }); } } out diff --git a/crates/engine/src/material_cmds.test.rs b/crates/engine/src/material_cmds.test.rs index 9c41b592..dd39fe84 100644 --- a/crates/engine/src/material_cmds.test.rs +++ b/crates/engine/src/material_cmds.test.rs @@ -222,3 +222,117 @@ fn snapshots_transitive_function_calls_and_rejects_recursion_or_missing_assets() std::sync::Arc::make_mut(s.pkg.dependencies.get_mut("a.sbs").unwrap()).resources.clear(); assert!(materialcraft_formats::material::write_material(&s.pkg, s.graph).unwrap_err().to_string().contains("missing resource")); } + +fn export_fixture(source: &str, params: &[(&str, Value)], usage: &str) -> Session { + let mut graph = Graph::new("Surface"); + graph.size = [5, 5]; + let generator = node(&mut graph, source, params); + output(&mut graph, generator, "output", "result", usage); + + let mut package = Package::new("Studio"); + package.graphs.push(graph); + Session::new(package) +} + +#[test] +fn grayscale_base_color_uses_the_transfer_declared_to_materialx() { + let session = export_fixture("uniform", &[("color", Value::Color([0.5; 4])), ("color_mode", Value::Bool(false))], "baseColor"); + + let (files, report) = material_bake::export(&session, &json!({"profile":"materialx"}), material_bake::read_input).unwrap(); + let map = &report["maps"][0]; + let image = image::load_from_memory(&files.iter().find(|file| file.file == map["file"]).unwrap().bytes).unwrap(); + + assert_eq!(map["colorSpace"], "srgb"); + assert_eq!(image.into_rgb8().get_pixel(0, 0).0, [188; 3]); +} + +#[test] +fn an_overridden_color_input_keeps_the_published_transfer() { + let session = + export_fixture("input_color", &[("identifier", Value::Text("swatch".into())), ("usage", Value::Enum(ComponentUsage::index("baseColor")))], "baseColor"); + let png = encode(&Image::filled(32, 32, Kind::Color, [0.21586; 4]), "png", Depth::U8, true).unwrap(); + + let cooked = material_bake::cook(&session, &json!({"inputs":{"swatch":"color.png"}}), |_| Ok(png.clone())).unwrap(); + + assert!((cooked["outputs"][0]["mean"][0].as_f64().unwrap() - 0.21586).abs() < 0.001); +} + +#[test] +fn normal_node_conventions_produce_the_same_published_y_up_map() { + let mut session = export_fixture("normal", &[("intensity", Value::Float(8.0))], "normal"); + let graph = session.graph_mut().unwrap(); + let normal = graph.nodes[0].id; + let input = node(graph, "input_grayscale", &[("identifier", Value::Text("slope".into()))]); + graph.connect(input, "output", normal, "input").unwrap(); + let slope = Image::generate(32, 32, Kind::Gray, |_, y| [if y < 16 { 0.0 } else { 1.0 }; 4]); + let png = encode(&slope, "png", Depth::U8, false).unwrap(); + let mut greens = Vec::new(); + + for open_gl in [None, Some(false), Some(true)] { + if let Some(open_gl) = open_gl { + session.graph_mut().unwrap().node_mut(normal).unwrap().params.insert("opengl".into(), Value::Bool(open_gl)); + } + let (files, report) = material_bake::export(&session, &json!({"profile":"materialx","inputs":{"slope":"input.png"}}), |_| Ok(png.clone())).unwrap(); + let bytes = &files.iter().find(|file| file.file == report["maps"][0]["file"]).unwrap().bytes; + let pixel = materialcraft_formats::decode(bytes, true).unwrap().get(16, 16, false); + + assert_eq!(report["normalOrientation"], "Y+"); + greens.push(pixel[1]); + } + + assert!(greens[2] > 0.8); + assert!(greens.iter().all(|green| (green - greens[2]).abs() < 0.0001), "{greens:?}"); +} + +#[test] +fn raw_normal_inputs_accept_an_explicit_source_convention() { + let session = export_fixture("input_color", &[("identifier", Value::Text("normal".into()))], "normal"); + let png = encode(&Image::filled(32, 32, Kind::Color, [0.5, 0.25, 1.0, 1.0]), "png", Depth::U16, false).unwrap(); + + for (format, expected) in [(J::Null, 0.25), (json!("opengl"), 0.25), (json!("directx"), 0.75)] { + let params = json!({"profile":"maps","inputs":{"normal":"normal.png"},"normalFormat":format}); + let (files, _) = material_bake::export(&session, ¶ms, |_| Ok(png.clone())).unwrap(); + let green = materialcraft_formats::decode(&files[0].bytes, true).unwrap().get(0, 0, false)[1]; + assert!((green - expected).abs() < 0.0001); + } +} + +#[test] +fn selecting_a_healthy_output_excludes_other_cook_failures() { + let mut session = export_fixture("uniform", &[], "baseColor"); + let graph = session.graph_mut().unwrap(); + let missing = node(graph, "bitmap", &[("resource", Value::Text("missing".into()))]); + output(graph, missing, "output", "broken", "roughness"); + + for profile in [J::Null, json!("maps"), json!("materialx")] { + let (files, _) = material_bake::export(&session, &json!({"profile":profile,"outputs":["result"]}), material_bake::read_input).unwrap(); + assert!(!files.is_empty()); + + assert!(material_bake::export(&session, &json!({"profile":profile,"outputs":["broken"]}), material_bake::read_input).is_err()); + } +} + +#[test] +fn requested_bake_dimensions_apply_to_fixed_size_source_nodes() { + let mut session = export_fixture("uniform", &[], "baseColor"); + let id = session.graph().unwrap().nodes[0].id; + execute(&mut session, "graph.node.base", &json!({"id":id,"sizeMode":"absolute","size":[4,4]})).unwrap(); + + let settings = json!({"profile":"materialx","size":[128,64]}); + let (files, report) = material_bake::export(&session, &settings, material_bake::read_input).unwrap(); + let pixels = materialcraft_formats::decode(&files[0].bytes, false).unwrap(); + + assert_eq!([pixels.width(), pixels.height()], [128, 64]); + assert_eq!(report["maps"][0]["size"], json!([128, 64])); + assert_eq!(material_bake::cook(&session, &settings, material_bake::read_input).unwrap()["outputs"][0]["size"], json!([128, 64])); +} + +#[test] +fn an_openpbr_scalar_rejects_an_unrepresentable_srgb_override() { + let session = export_fixture("uniform", &[], "roughness"); + let settings = json!({"profile":"materialx","colorSpaces":{"result":"srgb"}}); + + let result = material_bake::export(&session, &settings, material_bake::read_input); + + assert!(result.err().is_some_and(|error| error.to_string().contains("linear"))); +} diff --git a/crates/engine/src/material_options.rs b/crates/engine/src/material_options.rs index e10715fd..beb1f3d2 100644 --- a/crates/engine/src/material_options.rs +++ b/crates/engine/src/material_options.rs @@ -1,8 +1,8 @@ use craft_texture::Image; -use materialcraft_core::{Graph, Value}; +use materialcraft_core::{BaseParameter, Graph, SizeMode, Value}; use materialcraft_eval::{Cooked, Options}; use serde_json::Value as J; -use std::collections::BTreeMap; +use std::{borrow::Cow, collections::BTreeMap}; use crate::commands::bad; use crate::{ExportSize, Result, Session}; @@ -19,11 +19,13 @@ 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() }; + 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); } + if let Some(value) = p.get("values").filter(|v| !v.is_null()) { for (id, v) in value.as_object().ok_or_else(|| invalid("values must map parameter identifiers to values".into()))? { let param = graph.exposed.iter().find(|e| e.id == *id).ok_or_else(|| invalid(format!("unknown exposed parameter `{id}`")))?; @@ -31,39 +33,64 @@ impl MaterialOptions { options.values.insert(id.clone(), value); } } + if let Some(value) = p.get("inputs").filter(|v| !v.is_null()) { let declared = crate::material_cmds::image_inputs(graph); - let mut remaining = 1usize << 30; + const MAX_DECODED_INPUT_BYTES: usize = 1 << 30; + let mut remaining = MAX_DECODED_INPUT_BYTES; for (id, path) in value.as_object().ok_or_else(|| invalid("inputs must map image identifiers to file paths".into()))? { - if !declared.iter().any(|input| input.identifier == *id) { - return Err(invalid(format!("unknown image input `{id}`"))); - } + let input = declared.iter().find(|input| input.identifier == *id).ok_or_else(|| invalid(format!("unknown image input `{id}`")))?; + let linear = if graph.input_images.contains_key(id) { + graph.input_images_linear.contains(id) + } else { + let usage = if input.usage == "any" { id } else { &input.usage }; + !materialcraft_formats::material::srgb_usage(usage) + }; let path = path.as_str().ok_or_else(|| invalid(format!("inputs.{id} must be an image path")))?; - let image = materialcraft_formats::decode(&read(path)?, !materialcraft_formats::material::srgb_usage(id))?; + let image = materialcraft_formats::decode(&read(path)?, linear)?; remaining = remaining.checked_sub(std::mem::size_of_val(image.data())).ok_or_else(|| invalid("decoded image inputs exceed 1 GiB".into()))?; options.inputs.insert(id.clone(), image); } } + Ok(options) } - pub fn cook(&self, session: &Session, index: usize, max_size: Option) -> Result { - let mut package = session.pkg.clone(); - let graph = package.graph_mut(index)?; + pub(crate) fn cook(&self, session: &Session, index: usize, selected: Option<&[String]>, max_size: Option) -> Result { + let graph = session.pkg.graph(index)?; + let roots = graph + .nodes + .iter() + .filter(|node| node.def == "output") + .filter(|node| selected.is_none_or(|ids| ids.contains(&materialcraft_eval::identifier(node)))) + .map(|node| node.id) + .collect(); + let mut package = Cow::Borrowed(&session.pkg); if let Some(size) = self.size { + let graph = package.to_mut().graph_mut(index)?; graph.size = size.log2_size(graph.size); + + // Fixed-size generators keep their native detail while final output bridges resample to the requested size + for output in graph.nodes.iter_mut().filter(|node| node.def == "output") { + output.base.size_mode = SizeMode::RelativeToParent; + output.base.size = [0, 0]; + output.base.functions.remove(&BaseParameter::OutputSize); + } } + let decoder = session.resource_decoder(); let mut options = Options::new(&decoder); options.environment = session.environment; options.max_size = max_size; - options.only = Some(graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect()); + options.only = Some(roots); options.inputs.clone_from(&self.inputs); options.overrides.clone_from(&self.values); + let cooked = materialcraft_eval::cook(&package, index, &options, &session.cache); if let Some((id, error)) = cooked.nodes.iter().find_map(|(id, r)| Some((id, r.error.as_ref()?))) { - return Err(bad("material.cook", format!("graph `{}`, node {}: {error}", session.pkg.graph(index)?.sbs_path(), id.0))); + return Err(bad("material.cook", format!("graph `{}`, node {}: {error}", graph.sbs_path(), id.0))); } + Ok(cooked) } } diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs index a4db566a..9308666c 100644 --- a/crates/formats/src/image.rs +++ b/crates/formats/src/image.rs @@ -62,7 +62,7 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result { /// Encode `image` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { let ext = ext.trim_start_matches('.').to_ascii_lowercase(); - let encode_channel = |v: f32| if srgb && image.kind() == Kind::Color { linear_to_srgb(v) } else { v }; + let encode_channel = |v: f32| if srgb { linear_to_srgb(v) } else { v }; let (w, h) = (image.width(), image.height()); let color = image.kind() == Kind::Color; let pixel = |i: usize| -> [f32; 4] { @@ -70,7 +70,7 @@ pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result Result> { pub fn read_material(bytes: &[u8]) -> Result<(Package, usize)> { let limits = craft_mcmat::Limits::default(); let material = craft_mcmat::Material::open(bytes, limits).map_err(|err| FormatError::BadPackage(err.to_string()))?; - // Multiple SBS references to one small compressed member must share a decoded-byte budget. + + // Aliases of a compressed member share a single decoded-byte budget let remaining = Cell::new(limits.max_total_bytes); let read = sbs::read_sbs(&material.source, craft_mcmat::SOURCE_ENTRY, &|name| { let data = material.resources.get(name)?; remaining.set(remaining.get().checked_sub(data.len() as u64)?); Some(data.clone()) })?; + drop(material); + if let Some(warning) = read.warnings.first() { return Err(FormatError::BadPackage(format!("source.sbs: {warning}"))); } + let pkg = read.pkg; let entry = super::entry_graph(&pkg)?; if pkg.graphs.iter().flat_map(|g| g.instances()).any(|instance| !instance.package.is_empty()) { return Err(FormatError::BadPackage("source.sbs has an external graph reference; republish with its dependencies".into())); } + + // Reuse the publisher’s dependency checks for third-party archives super::snapshot(&pkg, entry)?; Ok((pkg, entry)) } diff --git a/crates/formats/src/material/image_input.rs b/crates/formats/src/material/image_input.rs index c7706a3d..43578c01 100644 --- a/crates/formats/src/material/image_input.rs +++ b/crates/formats/src/material/image_input.rs @@ -5,4 +5,6 @@ pub struct ImageInput { pub identifier: String, /// `gray` or `color` pub kind: String, + /// The graph-authored usage, independent of the input identifier. + pub usage: String, } diff --git a/crates/formats/src/material/mod.rs b/crates/formats/src/material/mod.rs index 43eccc56..02a1dcd4 100644 --- a/crates/formats/src/material/mod.rs +++ b/crates/formats/src/material/mod.rs @@ -1,7 +1,7 @@ mod archive; mod image_input; -mod snapshot; +mod snapshot_builder; pub use archive::{MATERIAL_EXT, VERSION, is_material, read_material, srgb_usage, write_material}; pub use image_input::ImageInput; -pub use snapshot::{entry_graph, snapshot}; +pub use snapshot_builder::{entry_graph, snapshot}; diff --git a/crates/formats/src/material/snapshot.rs b/crates/formats/src/material/snapshot_builder.rs similarity index 87% rename from crates/formats/src/material/snapshot.rs rename to crates/formats/src/material/snapshot_builder.rs index cce2c977..59bb2b74 100644 --- a/crates/formats/src/material/snapshot.rs +++ b/crates/formats/src/material/snapshot_builder.rs @@ -12,18 +12,19 @@ fn bad(message: impl Into) -> FormatError { /// The location of the entry in the source project is independent of its location in the publication. pub fn snapshot(package: &Package, entry: usize) -> Result { let graph = package.graph(entry).map_err(|e| bad(e.to_string()))?; - if graph.function.is_some() || !graph.nodes.iter().any(|n| n.def == "output" && graph.connections.iter().any(|c| c.to == n.id)) { + if graph.function.is_some() { return Err(bad(format!("select a material graph with connected outputs: `{}`", graph.sbs_path()))); } + let mut result = Package::new(&graph.name); result.format_version.clone_from(&package.format_version); - let mut builder = Builder { root: package, result, paths: BTreeMap::new(), active: BTreeSet::new(), resources: BTreeMap::new(), nodes: 0 }; + let mut builder = SnapshotBuilder { root: package, result, paths: BTreeMap::new(), active: BTreeSet::new(), resources: BTreeMap::new(), nodes: 0 }; builder.copy_graph("", entry)?; Ok(builder.result) } type Key = (String, usize); -struct Builder<'a> { +struct SnapshotBuilder<'a> { root: &'a Package, result: Package, paths: BTreeMap, @@ -32,11 +33,12 @@ struct Builder<'a> { nodes: usize, } -impl<'a> Builder<'a> { +impl<'a> SnapshotBuilder<'a> { fn package(&self, owner: &str) -> Result<&'a Package> { if owner.is_empty() { return Ok(self.root); } + self.root.dependencies.get(owner).map(AsRef::as_ref).ok_or_else(|| bad(format!("missing source package `{owner}`"))) } @@ -51,27 +53,38 @@ impl<'a> Builder<'a> { 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 traversal independently of the cooker's per-function and per-instance limits. - if self.active.len() >= 32 || self.paths.len() >= 4096 { + + // 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")); } + let mut graph = source.clone(); if graph.function.is_none() { let outputs: Vec<_> = graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect(); - let needed = GraphIndex::new(&graph).required_nodes(&outputs); + let index = GraphIndex::new(&graph); + if self.paths.is_empty() && !outputs.iter().any(|id| !index.incoming(*id).is_empty()) { + return Err(bad(format!("select a material graph with connected outputs: `{}`", graph.sbs_path()))); + } + + let needed = index.required_nodes(&outputs); graph.nodes.retain(|node| needed.contains(&node.id) || matches!(node.def.as_str(), "input_color" | "input_grayscale" | "input_value")); graph.connections.retain(|c| needed.contains(&c.from) && needed.contains(&c.to)); if graph.topo_order().len() != graph.nodes.len() { return Err(bad(format!("cycle in graph `{}`", graph.sbs_path()))); } } + self.nodes = self.nodes.saturating_add(graph.nodes.len()); - if self.nodes > 100_000 { + if self.nodes > crate::sbs::MAX_NODES { return Err(bad("published graph exceeds the node count limit")); } + 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()); @@ -85,6 +98,7 @@ impl<'a> Builder<'a> { if node.def == materialcraft_core::MISSING_NODE { return Err(bad(format!("unsupported node `{}` in `{path}`", node.label))); } + if node.def == "graph_instance" { if let Some(instance) = &node.instance { node.params.insert("graph".into(), Value::Text(instance.graph.clone())); @@ -94,6 +108,7 @@ impl<'a> Builder<'a> { return Err(bad(format!("missing graph reference in `{path}`"))); } } + match node.def.as_str() { "bitmap" | "svg" => { let Some(Value::Text(name)) = node.params.get_mut("resource").filter(|v| !matches!(v, Value::Text(s) if s.is_empty())) else { @@ -114,6 +129,7 @@ impl<'a> Builder<'a> { for name in graph.input_images.values_mut() { *name = self.resource(owner, name)?; } + self.active.remove(&key); self.result.graphs.push(graph); Ok(path) @@ -124,10 +140,12 @@ impl<'a> Builder<'a> { if let Some(local) = self.resources.get(&key) { return Ok(local.clone()); } + let mut resource = self.package(owner)?.resource(name).cloned().ok_or_else(|| bad(format!("missing resource `{name}` in `{owner}`")))?; if resource.bytes.is_empty() { return Err(bad(format!("missing resource bytes for `{name}` ({})", resource.source))); } + let local = format!("asset_{}", self.resources.len() + 1); resource.name.clone_from(&local); resource.folder = "Resources".into(); diff --git a/crates/formats/src/sbs/constant.rs b/crates/formats/src/sbs/constant.rs index 94e6ebf6..8828bf27 100644 --- a/crates/formats/src/sbs/constant.rs +++ b/crates/formats/src/sbs/constant.rs @@ -1,8 +1,8 @@ pub(super) const MAX_XML_NODES: u32 = 8_000_000; -pub(super) const MAX_GRAPHS: usize = 4096; +pub(crate) const MAX_GRAPHS: usize = 4096; -pub(super) const MAX_NODES: usize = 100_000; +pub(crate) const MAX_NODES: usize = 100_000; pub(super) const UPDATER_VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index c991cabf..ef52e5c9 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -35,6 +35,7 @@ mod warnings; mod xml; pub use constant::SBS_EXT; +pub(crate) use constant::{MAX_GRAPHS, MAX_NODES}; pub use layout_frame::LayoutFrame; pub use layout_item::LayoutItem; pub use library_layout::read_layout; diff --git a/crates/ui-egui/src/export/material_export_settings.rs b/crates/ui-egui/src/export/material_export_settings.rs index ca045d8a..ae777789 100644 --- a/crates/ui-egui/src/export/material_export_settings.rs +++ b/crates/ui-egui/src/export/material_export_settings.rs @@ -1,3 +1,4 @@ +use super::TextureDepth; use serde::{Deserialize, Serialize}; /// Destinations and bake settings for the selected source graph. @@ -10,6 +11,8 @@ pub struct MaterialExportSettings { pub archive: String, /// Pixels of the larger side; 0 keeps the graph's size pub size: u32, + /// Source tangent convention when the output graph does not identify it + pub normal_y_down: Option, pub texture_depth: TextureDepth, #[serde(skip)] pub root: String, @@ -19,29 +22,14 @@ pub struct MaterialExportSettings { impl Default for MaterialExportSettings { fn default() -> Self { - Self { folder: String::new(), archive: String::new(), size: 0, texture_depth: TextureDepth::default(), root: String::new(), displacement_scale: 1.0 } - } -} - -/// PNG precision of the published textures; HDR and signed data always use lossless EXR -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum TextureDepth { - /// 16 bits for data textures and 8 bits for color - #[default] - Automatic, - Eight, - Sixteen, -} - -impl TextureDepth { - pub const ALL: [TextureDepth; 3] = [TextureDepth::Automatic, TextureDepth::Eight, TextureDepth::Sixteen]; - - pub fn label(self) -> &'static str { - match self { - TextureDepth::Automatic => "Automatic (16-bit data, 8-bit color)", - TextureDepth::Eight => "8 bits", - TextureDepth::Sixteen => "16 bits", + Self { + folder: String::new(), + archive: String::new(), + size: 0, + normal_y_down: None, + texture_depth: TextureDepth::default(), + root: String::new(), + displacement_scale: 1.0, } } } diff --git a/crates/ui-egui/src/export/material_tab.rs b/crates/ui-egui/src/export/material_tab.rs index c0afcfeb..483fe743 100644 --- a/crates/ui-egui/src/export/material_tab.rs +++ b/crates/ui-egui/src/export/material_tab.rs @@ -35,6 +35,15 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut Expor } }); ui.end_row(); + super::form_label(ui, tr("Source normals")); + let conventions = [(None, "Automatic"), (Some(false), "OpenGL (Y+)"), (Some(true), "DirectX (Y-)")]; + let label = conventions.iter().find(|(value, _)| *value == material.normal_y_down).map_or("Automatic", |(_, label)| *label); + super::dropdown(ui, "Source normals", width, tr(label), |ui| { + for (value, label) in conventions { + ui.selectable_value(&mut material.normal_y_down, value, tr(label)); + } + }); + ui.end_row(); super::form_label(ui, tr("Displacement scale")); ui.add(egui::DragValue::new(&mut material.displacement_scale).speed(0.01).range(0.0..=100.0)); ui.end_row(); @@ -45,6 +54,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut Expor outputs::tree(ui, settings, graph.as_slice()); } } + /// A folder for MaterialX, an archive path for MCMAT #[cfg(not(target_arch = "wasm32"))] fn ask_destination(app: &mut MaterialCraftApp, tab: ExportTab, root: &str) { diff --git a/crates/ui-egui/src/export/mod.rs b/crates/ui-egui/src/export/mod.rs index d3b3e93f..aaab9ea6 100644 --- a/crates/ui-egui/src/export/mod.rs +++ b/crates/ui-egui/src/export/mod.rs @@ -7,10 +7,12 @@ mod export_tests; mod material_export_settings; mod material_tab; mod outputs; +mod texture_depth; pub use export_format::ExportFormat; pub use export_settings::{BatchExportSettings, ExportSettings, ExportTab, output_key}; -pub use material_export_settings::{MaterialExportSettings, TextureDepth}; +pub use material_export_settings::MaterialExportSettings; +pub use texture_depth::TextureDepth; use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as icon; @@ -375,7 +377,7 @@ fn publish(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool { ( "file.export", json!({"graph":index,"dir":material.folder,"profile":"materialx","size":material.size,"depth":depth,"outputs":outputs, - "colorSpaces":color_spaces,"displacementScale":material.displacement_scale}), + "colorSpaces":color_spaces,"displacementScale":material.displacement_scale,"normalFormat":material.normal_y_down.map(|down| if down { "directx" } else { "opengl" })}), ) }; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/export/texture_depth.rs b/crates/ui-egui/src/export/texture_depth.rs new file mode 100644 index 00000000..83955be7 --- /dev/null +++ b/crates/ui-egui/src/export/texture_depth.rs @@ -0,0 +1,24 @@ +use serde::{Deserialize, Serialize}; + +/// PNG precision of the published textures; HDR and signed data always use lossless EXR +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TextureDepth { + /// 16 bits for data textures and 8 bits for color + #[default] + Automatic, + Eight, + Sixteen, +} + +impl TextureDepth { + pub const ALL: [TextureDepth; 3] = [TextureDepth::Automatic, TextureDepth::Eight, TextureDepth::Sixteen]; + + pub fn label(self) -> &'static str { + match self { + TextureDepth::Automatic => "Automatic (16-bit data, 8-bit color)", + TextureDepth::Eight => "8 bits", + TextureDepth::Sixteen => "16 bits", + } + } +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index f3f09ad4..a90e69df 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -62,6 +62,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("As JSON", "بصيغة JSON"), ("Atomic nodes", "عقد أولية"), ("Attributes", "السمات"), + ("Automatic", "تلقائي"), ("Automatic (16-bit data, 8-bit color)", "تلقائي (16 بت للبيانات، 8 بت للألوان)"), ("Automatic Clip Planes", "مستويات قطع تلقائية"), ("Automatic export when outputs change", "تصدير تلقائي عند تغيّر المخرجات"), @@ -520,6 +521,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Side", "جانبي"), ("Sine", "جيب الزاوية (Sine)"), ("Size", "الحجم"), + ("Source normals", "اتجاه نواظم المصدر"), ("Specific parameters", "المعلمات المخصصة"), ("Specular", "الانعكاس"), ("Specular Glossiness", "انعكاس ولمعان"), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 76fa25f6..0ee364d8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -38,7 +38,7 @@ to the saving application's release version. Save As and archive packaging retai | `session.inspect` | all | package, graphs, the open graph's nodes (def, params, bindings, base, ports, cook error/size/mean/ms), wires, frames, comments, pins, exposed inputs, views, history | | `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O | | `bitmap.import {path, name?}` | headless | embed an image as a resource | -| `outputs.export {dir, format?, pattern?, depth?, size?, graph?, outputs?, colorSpaces?, profile?, preset?, values?, inputs?, displacementScale?}` | headless | cook at full size and write the outputs: `size` is the larger side or `[width, height]`, `outputs` lists identifiers (default all), `colorSpaces` maps identifiers to `srgb`, `linear` or `raw` (default by usage) | +| `outputs.export {dir, format?, pattern?, depth?, size?, graph?, outputs?, colorSpaces?, profile?, preset?, values?, inputs?, normalFormat?, displacementScale?}` | headless | cook at full size and write the outputs: `size` is the larger side or `[width, height]`, `outputs` lists identifiers (default all), `colorSpaces` maps identifiers to `srgb`, `linear` or `raw` (default by usage) | | `material.export {path, graph?}` | 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 | @@ -362,18 +362,18 @@ materialcraft-cli export Oak.mcmat build/oak --profile materialx --size 2048 \ The ZIP contains a version marker (`material.json` with `{"version":3}`), a DEFLATE-compressed `source.sbs`, and the source assets its graphs reference under `resources/`. The sole graph at the root of the SBS document is the entry. Reachable helper graphs and functions have local paths under `Dependencies/`. Republish v1 and v2 archives from the original authoring project. -`info` reads the entry's path, dimensions, supported resolutions, typed defaults, saved values, presets, image inputs and output usages. A cook starts from the saved values, applies the named preset, then applies each explicit override. `--set` accepts numbers, booleans, JSON vectors, colors and typed values such as `{"t":"float","v":0.7}`. The size is the longer side in pixels. The graph retains its aspect ratio within the supported powers of two from 16 to 8192. Use `--size 1024x512` to choose both sides. An omitted size uses the authored dimensions. +`info` reads the entry's path, dimensions, supported resolutions, typed defaults, saved values, presets, image inputs and output usages. A cook starts from the saved values, applies the named preset, then applies each explicit override. `--set` accepts numbers, booleans, JSON vectors, colors and typed values such as `{"t":"float","v":0.7}`. The size is the longer side in pixels. The graph retains its aspect ratio within the supported powers of two from 16 to 8192. Use `--size 1024x512` to choose both sides. An omitted size uses the authored dimensions. An explicit size also sets the final dimensions of outputs fed by fixed-size nodes. -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`. The JSON report lists each map's identifier, usage, filename, color space and actual dimensions. +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. -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. Normals use tangent-space Y+. Height becomes signed EXR displacement in scene units using `(height - 0.5) × displacementScale`. The CLI accepts `--displacement-scale`. Outputs without an OpenPBR connection are written alongside the document and listed in `unmapped`. +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 | |---|---| | `file.exportMaterial` | `{path, graph?}` publishes the chosen source graph by SBS path or index. The default is the open graph. | | `material.info` | `{graph?}` reads the material interface. | | `material.cook` | `{graph?, size?, preset?, values?, inputs?}` returns output dimensions and mean values. | -| `file.export` | `{dir, graph?, profile?, size?, preset?, values?, inputs?, displacementScale?}` bakes images using the selected profile. | +| `file.export` | `{dir, graph?, profile?, size?, preset?, values?, inputs?, normalFormat?, displacementScale?}` bakes images using the selected profile. | | `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?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package | | `file.open` | `{path}` opens `.sbs` XML or an independent `.mcraft` ZIP. Also opens a `.mcmat`'s source without a save path. Returns `warnings` for unsupported content; also in `session.inspect` as `package.warnings` |