From 0ef6f72f7c7db345dfbdccd264a130c5303319f9 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 02:40:13 -0500 Subject: [PATCH] Cook MCMAT v3 linked fills through MaterialCraft --- Cargo.lock | 15 +- Cargo.toml | 2 +- crates/engine/Cargo.toml | 3 + crates/engine/src/link_cmds.rs | 248 +++++++------------ crates/engine/src/link_cook.rs | 130 ++++++++++ crates/engine/src/materials.rs | 2 +- crates/engine/src/resource_cmds.rs | 3 +- crates/engine/tests/it/materialcraft_link.rs | 128 +++++----- crates/formats/src/mcmat.rs | 206 ++------------- crates/ui-egui/src/lib.rs | 22 +- crates/ui-egui/src/link_import.rs | 68 +++++ docs/architecture.md | 6 +- docs/control-protocol.md | 11 +- 13 files changed, 416 insertions(+), 428 deletions(-) create mode 100644 crates/engine/src/link_cook.rs create mode 100644 crates/ui-egui/src/link_import.rs diff --git a/Cargo.lock b/Cargo.lock index 1befa39f..c9539ecf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -827,9 +827,9 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +source = "git+https://github.com/storytold/craft-libs?rev=b0f25d641840bea1dda99c1e5e0c8db9221bcf28#b0f25d641840bea1dda99c1e5e0c8db9221bcf28" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b0f25d641840bea1dda99c1e5e0c8db9221bcf28)", "serde", "serde_json", "thiserror 2.0.21", @@ -967,6 +967,16 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b0f25d641840bea1dda99c1e5e0c8db9221bcf28#b0f25d641840bea1dda99c1e5e0c8db9221bcf28" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -4462,6 +4472,7 @@ dependencies = [ "rustix 1.1.5", "serde", "serde_json", + "tempfile", "texturecraft-bake", "texturecraft-compose", "texturecraft-core", diff --git a/Cargo.toml b/Cargo.toml index 2f7e212e..afe863cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,7 +74,7 @@ craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774 craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b0f25d641840bea1dda99c1e5e0c8db9221bcf28" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3d66b9df..5d1d5487 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -22,6 +22,9 @@ serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tempfile = "3" + [target.'cfg(unix)'.dependencies] rustix = { workspace = true } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 603cd0fa..738fc72c 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -2,15 +2,13 @@ //! channel sources are its cooked maps (image resources) and whose [`MaterialLink`] keeps the //! graph's exposed parameters. Changing one re-cooks the maps through `materialcraft-cli` at the //! texture set's resolution, with the set's baked mesh maps feeding graph inputs of the same name. -//! The apps share the file format and the command line, not code. +//! Both apps use the shared craft-mcmat container and the public CLI. use std::sync::Arc; use serde_json::{Map, Value, json}; use texturecraft_core::{BakedMap, Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source}; -#[cfg(not(target_arch = "wasm32"))] -use texturecraft_formats::mcmat::MCMAT_EXT; -use texturecraft_formats::mcmat::{MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; +use texturecraft_formats::mcmat::{MCRAFT_EXT, is_mcraft, validate_mcmat}; use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp}; use crate::materials::Place; @@ -56,7 +54,7 @@ pub fn specs() -> Vec { "Save MaterialCraft package", [], None, - "{layer?, path} — writes the MaterialCraft source (.mcraft or .sbs) behind a material layer", + "{layer?, path} — writes the MaterialCraft source (.mcmat, .mcraft or .sbs) behind a material layer", has_layer, save_source ), @@ -200,7 +198,7 @@ fn save_source(_: &mut Session, _: &Value) -> Result { pub struct LinkJob { pub layer: LayerId, pub package: Arc>, - /// The source package extension (`mcraft` or `sbs`). + /// The source package extension (`mcmat`, `mcraft` or `sbs`). pub source_ext: &'static str, /// The named graph in a linked material; direct package imports use its default. pub graph: Option, @@ -212,9 +210,6 @@ pub struct LinkJob { pub inputs: Vec<(String, Vec)>, } -#[cfg(not(target_arch = "wasm32"))] -static NEXT_JOB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - /// A MaterialCraft executable: `$`, else next to this program, else `name` on `PATH`. #[cfg(not(target_arch = "wasm32"))] pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { @@ -235,7 +230,7 @@ fn quiet(program: &std::path::Path) -> std::process::Command { c } -/// Open `package` (a `.mcraft` or `.sbs` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this +/// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this /// program, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { @@ -247,73 +242,70 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { /// Source file extensions are chosen from the linked resource name, never an untrusted path. pub fn source_extension(name: &str) -> &'static str { - if name.to_ascii_lowercase().ends_with(".sbs") { "sbs" } else { MCRAFT_EXT } + if name.to_ascii_lowercase().ends_with(".mcmat") { + "mcmat" + } else if name.to_ascii_lowercase().ends_with(".sbs") { + "sbs" + } else { + MCRAFT_EXT + } } +#[derive(Clone, Debug, serde::Deserialize)] +pub struct MaterialInterface { + pub name: String, + pub graph: String, + pub parameters: Vec, + pub inputs: Vec, + pub presets: Vec, +} + +#[derive(Clone, Debug, serde::Deserialize)] +pub struct ImageInput { + pub identifier: String, +} + +#[derive(Clone, Debug)] +pub struct CookedMaterial { + pub interface: MaterialInterface, + pub maps: Vec<(String, Vec)>, + pub size: u32, +} + +#[cfg(not(target_arch = "wasm32"))] +#[path = "link_cook.rs"] +mod link_cook; + +#[cfg(target_arch = "wasm32")] impl LinkJob { - /// Cook through `materialcraft-cli` (`$MATERIALCRAFT_CLI`, next to this program, or on - /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). - #[cfg(not(target_arch = "wasm32"))] - pub fn run(&self) -> Result> { - self.run_with_cli(&materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI")) + pub fn run_for_import(&self, _: Option<&texturecraft_compose::BakedMaps>) -> Result { + self.run() } + pub fn run(&self) -> Result { + Err(EngineError::Other("cooking a procedural material requires materialcraft-cli on a desktop".into())) + } +} - #[cfg(not(target_arch = "wasm32"))] - fn run_with_cli(&self, cli: &std::path::Path) -> Result> { - let other = |e: String| EngineError::Other(e); - let n = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("texturecraft-link-{}-{n}", std::process::id())); - std::fs::create_dir_all(&dir).map_err(|e| other(format!("{}: {e}", dir.display())))?; - let result = (|| { - let utf8 = |p: &std::path::Path| p.to_str().map(str::to_string).ok_or_else(|| other(format!("{} is not a UTF-8 path", p.display()))); - let write = |name: &str, bytes: &[u8]| { - let p = dir.join(name); - std::fs::write(&p, bytes).map_err(|e| other(format!("{name}: {e}")))?; - utf8(&p) - }; - let ext = if self.source_ext == "sbs" { "sbs" } else { MCRAFT_EXT }; - let src = write(&format!("source.{ext}"), &self.package)?; - let mut inputs = Map::new(); - for (i, (id, png)) in self.inputs.iter().enumerate() { - inputs.insert(id.clone(), json!(write(&format!("input{i}.png"), png)?)); - } - let out = dir.join(format!("out.{MCMAT_EXT}")); - let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); - let mut command = quiet(cli); - if let Some(graph) = &self.graph { - // Opening the source starts on its first graph; select the graph saved in the link. - let script = json!({"open": src, "steps": [ - {"id": "graph.open", "params": {"graph": graph}}, - {"id": "file.exportMaterial", "params": params}, - ]}); - let script_path = write("cook.json", script.to_string().as_bytes())?; - command.arg("batch").arg(script_path); - } else { - command.arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()); - } - let run = command.output().map_err(|e| { - other(format!( - "MaterialCraft's command line ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT_CLI", - cli.display() - )) - })?; - if !run.status.success() { - return Err(other(format!("MaterialCraft could not cook the material: {}", String::from_utf8_lossy(&run.stderr).trim()))); - } - std::fs::read(&out).map_err(|e| other(format!("{}: {e}", out.display()))) - })(); - let _ = std::fs::remove_dir_all(&dir); - result - } +/// Prepare the first bake without borrowing the paint document. Its original archive is kept for future cooks. +fn cook_source(bytes: Vec, size: u32, baked: Option<&texturecraft_compose::BakedMaps>) -> Result<(LinkJob, CookedMaterial)> { + let source_ext = if is_mcraft(&bytes) { + MCRAFT_EXT + } else { + validate_mcmat(&bytes).map_err(|e| EngineError::Other(e.to_string()))?; + "mcmat" + }; + let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes), source_ext, graph: None, size, values: Map::new(), inputs: Vec::new() }; + let material = job.run_for_import(baked)?; + Ok((job, material)) +} - #[cfg(target_arch = "wasm32")] - pub fn run(&self) -> Result> { - Err(EngineError::Other("re-cooking a MaterialCraft material needs its command line, which the browser can't run".into())) - } +#[cfg(not(target_arch = "wasm32"))] +pub fn cook_link_file(path: &std::path::Path, size: u32, baked: Option<&texturecraft_compose::BakedMaps>) -> Result<(LinkJob, CookedMaterial)> { + cook_source(link_cook::read_bounded(path, 1 << 30)?, size, baked) } /// Decode every map of `m` (validating them) with the channel it feeds. -fn decoded_maps(m: &PortableMaterial) -> Result, texturecraft_formats::DecodedImage)>> { +fn decoded_maps(m: &CookedMaterial) -> Result, texturecraft_formats::DecodedImage)>> { m.maps .iter() .filter_map(|(usage, bytes)| Some((Channel::ALL.into_iter().find(|c| c.id() == usage)?, bytes))) @@ -328,43 +320,36 @@ impl Session { /// Add a MaterialCraft material (`.mcmat` bytes, or a `.mcraft` package cooked first) as a /// fill layer at `place` (one undo step). Returns the new layer. pub fn add_linked_material_bytes_at(&mut self, bytes: &[u8], place: Place) -> Result { - let cooked; - let bytes = if is_mcraft(bytes) { - let ts = self.ts(); - let size = self.doc.project.texture_set(ts)?.resolution; - let job = LinkJob { - layer: LayerId(0), - package: Arc::new(bytes.to_vec()), - source_ext: MCRAFT_EXT, - graph: None, - size, - values: Map::new(), - inputs: Vec::new(), - }; - cooked = job.run()?; - cooked.as_slice() - } else { - bytes - }; - let m = read_mcmat(bytes).map_err(|e| EngineError::Other(e.to_string()))?; - let maps = decoded_maps(&m)?; + let ts = self.ts(); + let size = self.doc.project.texture_set(ts)?.resolution; + let (job, material) = cook_source(bytes.to_vec(), size, self.doc.baked.get(&ts))?; + self.add_cooked_material(&material, job.package, job.source_ext, place) + } + + /// Install validated CLI output in one undo step. Keep the original source for future variations. + pub fn add_cooked_material(&mut self, m: &CookedMaterial, source: Arc>, source_ext: &str, place: Place) -> Result { + let maps = decoded_maps(m)?; if maps.is_empty() { - return Err(EngineError::Other(format!("{} has no maps TextureCraft can paint with", m.manifest.name))); + return Err(EngineError::Other(format!("{} has no maps TextureCraft can paint with", m.interface.name))); } - let label = format!("Add {}", m.manifest.name); + let label = format!("Add {}", m.interface.name); let (id, names) = self.edit(&label, |s| { let ts = s.ts(); - let stem = texturecraft_formats::sanitize_resource_name(&m.manifest.name); - let package = unique(s, &format!("{stem}.{}", source_extension(&m.manifest.source))); - s.doc.resources.insert(package.clone(), Arc::new(m.source.clone())); + let stem = texturecraft_formats::sanitize_resource_name(&m.interface.name); + let ext = match source_ext { + "mcmat" | "sbs" | "mcraft" => source_ext, + _ => return Err(EngineError::Other("unknown linked source format".into())), + }; + let package = unique(s, &format!("{stem}.{ext}")); + s.doc.resources.insert(package.clone(), source); let link = MaterialLink { - name: m.manifest.name.clone(), + name: m.interface.name.clone(), package, - graph: m.manifest.graph.clone(), - params: m.manifest.parameters.iter().filter(|p| components(type_of(&p.default)).is_some()).cloned().collect(), - presets: m.manifest.presets.clone(), - inputs: m.manifest.inputs.iter().map(|i| i.identifier.clone()).collect(), - size: m.manifest.size[0], + graph: m.interface.graph.clone(), + params: m.interface.parameters.iter().filter(|p| components(type_of(&p.default)).is_some()).cloned().collect(), + presets: m.interface.presets.clone(), + inputs: m.interface.inputs.iter().map(|i| i.identifier.clone()).collect(), + size: m.size, }; let mut fill = Fill { link: Some(Box::new(link)), ..Fill::default() }; let names = put_maps(s, &stem, &maps, &mut fill); @@ -373,7 +358,7 @@ impl Session { } let channels: Vec = fill.sources.keys().copied().collect(); let lid = s.doc.project.alloc_id(); - let name = s.doc.project.next_layer_name(ts, &m.manifest.name); + let name = s.doc.project.next_layer_name(ts, &m.interface.name); let lid = crate::layer_cmds::insert_selected(s, Layer::new(lid, name, LayerKind::Fill(fill), &channels))?; place.apply(s, lid)?; s.selected.insert(ts, lid); @@ -429,9 +414,8 @@ impl Session { /// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with. /// With `merge`, this folds into the previous undo step when that was an edit of the same kind /// (a parameter set while the cook ran). - pub fn apply_link_cook(&mut self, id: LayerId, bytes: &[u8], merge: bool) -> Result<()> { - let material = read_mcmat(bytes).map_err(|error| EngineError::Other(error.to_string()))?; - let maps = decoded_maps(&material)?; + pub fn apply_link_cook(&mut self, id: LayerId, material: &CookedMaterial, merge: bool) -> Result<()> { + let maps = decoded_maps(material)?; let names = self.edit_merging(EDIT, merge, |session| { let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else { @@ -440,11 +424,11 @@ impl Session { let link = fill.link.as_mut().ok_or_else(|| EngineError::Other(format!("layer {} is not a MaterialCraft material", id.0)))?; for parameter in &mut link.params { - if let Some(cooked) = material.manifest.parameters.iter().find(|candidate| candidate.id == parameter.id) { + if let Some(cooked) = material.interface.parameters.iter().find(|candidate| candidate.id == parameter.id) { parameter.value = cooked.value.clone(); } } - link.size = material.manifest.size[0]; + link.size = material.size; let stem = texturecraft_formats::sanitize_resource_name(&link.name); let old_names: Vec = fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect(); @@ -491,7 +475,8 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft let cook = s.doc.project.alloc_id().0; let mut names = Vec::new(); for (c, bytes, _) in maps { - let name = unique(s, &format!("{stem}_{}_{cook}.png", c.id())); + let extension = if bytes.starts_with(&[0x76, 0x2f, 0x31, 0x01]) { "exr" } else { "png" }; + let name = unique(s, &format!("{stem}_{}_{cook}.{extension}", c.id())); s.doc.resources.insert(name.clone(), Arc::new(bytes.clone())); // A normal map the user marked DirectX stays marked through re-cooks. let normal_format = match fill.sources.get(c) { @@ -504,57 +489,6 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft names } -#[cfg(all(test, unix))] -mod subprocess_tests { - use super::*; - use std::os::unix::fs::PermissionsExt; - - #[test] - fn cook_uses_the_saved_graph_and_source_type_without_global_environment() { - let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("texturecraft-cook-test-{}-{id}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let cli = dir.join("materialcraft-cli"); - let script = r#"#!/bin/sh -set -eu -case "$1" in - batch) - grep -F '"graph":"Second"' "$2" >/dev/null - grep -F '"id":"file.exportMaterial"' "$2" >/dev/null - test -f "$(dirname "$2")/source.sbs" - test -f "$(dirname "$2")/input0.png" - cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" - ;; - run) - test "$(basename "$2")" = "source.mcraft" - cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" - ;; - *) exit 1 ;; -esac -"#; - std::fs::write(&cli, script).unwrap(); - std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap(); - std::fs::write(dir.join("result.mcmat"), b"cooked").unwrap(); - let mut job = LinkJob { - layer: LayerId(1), - package: Arc::new(b"source".to_vec()), - source_ext: "sbs", - graph: Some("Second".into()), - size: 64, - values: Map::new(), - inputs: vec![("curvature".into(), b"png".to_vec())], - }; - assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); - job.graph = None; - job.source_ext = "mcraft"; - assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); - job.graph = Some("wrong".into()); - assert!(job.run_with_cli(&cli).is_err()); - assert!(job.run_with_cli(&dir.join("missing")).is_err()); - let _ = std::fs::remove_dir_all(dir); - } -} - #[cfg(test)] mod tests { use super::typed; diff --git a/crates/engine/src/link_cook.rs b/crates/engine/src/link_cook.rs new file mode 100644 index 00000000..6e2cbba2 --- /dev/null +++ b/crates/engine/src/link_cook.rs @@ -0,0 +1,130 @@ +//! Cook a procedural source in a private directory. Only declared map files enter the paint document. +use super::{CookedMaterial, EngineError, LinkJob, MaterialInterface, Result, materialcraft_tool, quiet}; +use serde::Deserialize; +use std::io::Read; +use std::path::Path; +use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakedMap, Channel}; + +fn io(error: impl std::fmt::Display) -> EngineError { + EngineError::Other(error.to_string()) +} + +pub(super) fn read_bounded(path: &Path, limit: u64) -> Result> { + let metadata = std::fs::symlink_metadata(path).map_err(io)?; + if !metadata.is_file() || metadata.len() > limit { + return Err(io(format!("invalid or oversized cook output: {}", path.display()))); + } + let mut bytes = Vec::new(); + std::fs::File::open(path).map_err(io)?.take(limit + 1).read_to_end(&mut bytes).map_err(io)?; + if bytes.len() as u64 > limit { + return Err(io("cook output exceeds the remaining budget")); + } + Ok(bytes) +} + +fn invoke(mut command: std::process::Command, dir: &Path) -> Result> { + let stdout = dir.join("reply.json"); + let stderr = dir.join("diagnostic.txt"); + let status = command + .stdout(std::fs::File::create(&stdout).map_err(io)?) + .stderr(std::fs::File::create(&stderr).map_err(io)?) + .status() + .map_err(|e| io(format!("could not start materialcraft-cli: {e}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?; + if !status.success() { + return Err(io(format!("MaterialCraft could not cook the material: {}", String::from_utf8_lossy(&read_bounded(&stderr, 1 << 20)?).trim()))); + } + read_bounded(&stdout, 8 << 20) +} + +#[derive(Deserialize)] +struct Reply { + material: MaterialInterface, + maps: Vec, +} +#[derive(Deserialize)] +struct MapFile { + usage: String, + file: String, + size: [u32; 2], +} + +impl LinkJob { + pub fn run(&self) -> Result { + self.run_for_import(None) + } + + pub(super) fn run_for_import(&self, baked: Option<&BakedMaps>) -> Result { + let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); + self.run_with_cli(&cli, baked) + } + + fn run_with_cli(&self, cli: &Path, baked: Option<&BakedMaps>) -> Result { + let temp = tempfile::Builder::new().prefix("texturecraft-material-").tempdir().map_err(io)?; + let dir = temp.path(); + let ext = match self.source_ext { + "mcmat" | "sbs" | "mcraft" => self.source_ext, + _ => return Err(io("unknown linked source format")), + }; + let source = dir.join(format!("source.{ext}")); + std::fs::write(&source, &*self.package).map_err(io)?; + let out = dir.join("maps"); + let mut export = quiet(cli); + export.arg("export").arg(&source).arg(&out).args(["--profile", "maps", "--size"]).arg(self.size.to_string()); + if self.source_ext != "mcmat" + && let Some(graph) = &self.graph + { + export.arg("--graph").arg(graph); + } + for (id, value) in &self.values { + export.arg("--set").arg(format!("{id}={value}")); + } + let add_input = |export: &mut std::process::Command, index: usize, id: &str, data: &[u8]| -> Result<()> { + let file = dir.join(format!("input{index}.png")); + std::fs::write(&file, data).map_err(io)?; + export.arg("--input").arg(format!("{id}={}", file.display())); + Ok(()) + }; + for (i, (id, bytes)) in self.inputs.iter().enumerate() { + add_input(&mut export, i, id, bytes)?; + } + if let Some(bakes) = baked { + let mut inspect = quiet(cli); + if self.source_ext == "mcmat" { + inspect.arg("info").arg(&source); + } else { + inspect.arg("run").arg(&source).arg("material.info"); + } + let interface: MaterialInterface = serde_json::from_slice(&invoke(inspect, dir)?).map_err(io)?; + for (i, input) in interface.inputs.iter().enumerate() { + if let Some(map) = BakedMap::parse(&input.identifier) + && let Some(data) = bakes.maps.get(&map) + { + let png = texturecraft_formats::mcmat::mesh_map_png(bakes.resolution, map.components(), data).map_err(io)?; + add_input(&mut export, self.inputs.len() + i, &input.identifier, &png)?; + } + } + } + let reply: Reply = serde_json::from_slice(&invoke(export, dir)?).map_err(io)?; + let mut budget = 1u64 << 30; + let mut maps = Vec::new(); + let mut size = 0; + for map in reply.maps { + if !Channel::ALL.iter().any(|c| c.id() == map.usage) || maps.iter().any(|(usage, _)| usage == &map.usage) { + continue; + } + let path = Path::new(&map.file); + if path.file_name().and_then(|p| p.to_str()) != Some(&map.file) || map.file.contains(['\\', ':']) { + return Err(io("invalid map filename in MaterialCraft's export report")); + } + let data = read_bounded(&out.join(path), budget.min(512 << 20))?; + budget -= data.len() as u64; + size = size.max(map.size[0]).max(map.size[1]); + maps.push((map.usage, data)); + } + if maps.is_empty() { + return Err(io("MaterialCraft returned no paintable map usages")); + } + Ok(CookedMaterial { interface: reply.material, maps, size }) + } +} diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 1d4e717a..12d7f2be 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -769,7 +769,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { impl Place { /// From `above` (+ `inside`) or `index` params; the selection by default. - pub(crate) fn from_params(p: &serde_json::Value) -> Place { + pub fn from_params(p: &serde_json::Value) -> Place { match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "index")) { (Some(above), _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)), (None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)), diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 2c973280..397f403a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -68,9 +68,8 @@ impl Session { self.images.retain(|name, _| self.doc.resources.contains_key(name)); // Linked material packages are resources but cannot be decoded as images - let package_suffix = format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT); for (name, bytes) in &self.doc.resources { - if self.images.contains_key(name) || name.ends_with(&package_suffix) { + if self.images.contains_key(name) || name.ends_with(".mcraft") || name.ends_with(".mcmat") || name.ends_with(".sbs") { continue; } diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index cbe75532..c0b36be3 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -10,6 +10,7 @@ use texturecraft_engine::compose::BakedMaps; use texturecraft_engine::core::{BakedMap, Channel, LayerId, LayerKind, NormalFormat, Source}; use texturecraft_engine::formats::mcmat::mesh_map_png; use texturecraft_engine::geom::primitives; +use texturecraft_engine::link_cmds::CookedMaterial; use texturecraft_engine::materials::Place; use texturecraft_engine::{Session, execute}; @@ -19,21 +20,11 @@ fn session() -> Session { s } -/// A `.mcmat` as MaterialCraft writes it: uniform maps, one float input `wear` cooked at `wear`. -fn mcmat(roughness: f32, wear: f32) -> Vec { - mcmat_version(roughness, wear, 1) -} - -fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec { - let source = if version == 2 { "source.sbs" } else { "source.mcraft" }; +/// A CLI bake with known pixels for testing the linked layer independently of the subprocess. +fn cooked(roughness: f32, wear: f32) -> CookedMaterial { let gray = |v: f32| mesh_map_png(4, 1, &[v; 16]).unwrap(); - let manifest = json!({ - "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], - "maps": [ - {"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}, - {"usage": "roughness", "file": "maps/roughness.png", "colorSpace": "linear"}, - {"usage": "ambientOcclusion", "file": "maps/ambientOcclusion.png", "colorSpace": "linear"} - ], + let interface = json!({ + "name": "Brick wall", "graph": "Brick_wall", "parameters": [ {"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": wear}}, {"id": "tint", "label": "Tint", "default": {"t": "color", "v": [1.0, 1.0, 1.0, 1.0]}, "value": {"t": "color", "v": [1.0, 1.0, 1.0, 1.0]}}, @@ -47,21 +38,20 @@ fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec { {"identifier": "bentNormal", "kind": "color"} ], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}], - "source": source }); - let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let o = zip::write::SimpleFileOptions::default(); - for (name, bytes) in [ - ("material.json", manifest.to_string().into_bytes()), - ("maps/baseColor.png", mesh_map_png(4, 3, &[0.5; 48]).unwrap()), - ("maps/roughness.png", gray(roughness)), - ("maps/ambientOcclusion.png", gray(1.0)), - (source, b"package bytes".to_vec()), - ] { - z.start_file(name, o).unwrap(); - z.write_all(&bytes).unwrap(); + CookedMaterial { + interface: serde_json::from_value(interface).unwrap(), + size: 4, + maps: vec![ + ("baseColor".into(), mesh_map_png(4, 3, &[0.5; 48]).unwrap()), + ("roughness".into(), gray(roughness)), + ("ambientOcclusion".into(), gray(1.0)), + ], } - z.finish().unwrap().into_inner() +} + +fn install(session: &mut Session) -> LayerId { + session.add_cooked_material(&cooked(0.25, 0.5), Arc::new(b"package bytes".to_vec()), "mcmat", Place::Selection).unwrap() } fn roughness(s: &mut Session) -> f32 { @@ -87,27 +77,19 @@ fn map_name(s: &Session, id: LayerId, c: Channel) -> String { } #[test] -fn version_two_preserves_the_sbs_source_for_future_cooks() { +fn version_two_requires_republishing_before_install() { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("material.json", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(br#"{"version":2,"format":"craft-material"}"#).unwrap(); + let bytes = zip.finish().unwrap().into_inner(); let mut session = session(); - let id = session.add_linked_material_bytes_at(&mcmat_version(0.25, 0.5, 2), Place::Selection).unwrap(); - let linked = link(&session, id); - assert!(linked.package.ends_with(".sbs")); - let job = session.link_job(id, &serde_json::Map::new()).unwrap(); - assert_eq!(job.source_ext, "sbs"); - assert_eq!(job.graph.as_deref(), Some("Brick_wall")); - assert_eq!(job.package.as_slice(), b"package bytes"); - let base = std::env::temp_dir().join(format!("texturecraft-sbs-source-{}", std::process::id())); - let saved = execute(&mut session, "material.link.saveSource", &json!({"layer": id.0, "path": base.to_str().unwrap()})).unwrap(); - let path = saved["path"].as_str().unwrap(); - assert!(path.ends_with(".sbs")); - assert_eq!(std::fs::read(path).unwrap(), b"package bytes"); - let _ = std::fs::remove_file(path); + assert!(session.add_linked_material_bytes_at(&bytes, Place::Selection).unwrap_err().to_string().contains("Republish")); } #[test] fn imports_as_a_linked_fill_with_its_maps() { let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let id = install(&mut s); assert_eq!(s.selected_layer(), Some(id)); assert!((roughness(&mut s) - 0.25).abs() < 2e-3); // The material's channels join the texture set; text inputs are not editable here. @@ -132,10 +114,10 @@ fn imports_as_a_linked_fill_with_its_maps() { #[test] fn recooks_keep_the_normal_format_of_a_map() { let mut session = session(); - let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let id = install(&mut session); execute(&mut session, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap(); - session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); + session.apply_link_cook(id, &cooked(0.75, 0.5), false).unwrap(); let LayerKind::Fill(fill) = &session.doc.project.layer(id).unwrap().kind else { panic!("a fill") }; @@ -145,7 +127,7 @@ fn recooks_keep_the_normal_format_of_a_map() { #[test] fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { let mut session = session(); - let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let id = install(&mut session); let set = |session: &mut Session, params: Value| execute(session, "material.link.set", ¶ms); assert!(set(&mut session, json!({"id": "nope", "value": 1, "cook": false})).is_err()); @@ -164,7 +146,7 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { // Merge the cooked maps into the parameter edit let old = map_name(&session, id, Channel::Roughness); - session.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap(); + session.apply_link_cook(id, &cooked(0.75, 0.9), true).unwrap(); assert!((roughness(&mut session) - 0.75).abs() < 2e-3); assert!(!session.doc.resources.contains_key(&old), "old maps are dropped"); @@ -185,10 +167,10 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { #[test] fn duplicates_keep_their_maps_and_mesh_maps_feed_inputs() { let mut session = session(); - let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let id = install(&mut session); let duplicate = LayerId(execute(&mut session, "layer.duplicate", &json!({"layer": id.0})).unwrap()["layer"].as_u64().unwrap()); let shared = map_name(&session, duplicate, Channel::Roughness); - session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); + session.apply_link_cook(id, &cooked(0.75, 0.5), false).unwrap(); assert!(session.doc.resources.contains_key(&shared), "the duplicate still shows the first cook"); let maps = [BakedMap::Curvature, BakedMap::Normal, BakedMap::WorldNormal, BakedMap::AmbientOcclusion, BakedMap::BentNormal]; @@ -201,7 +183,7 @@ fn duplicates_keep_their_maps_and_mesh_maps_feed_inputs() { #[test] fn projects_save_the_link_and_its_package() { let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let id = install(&mut s); let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); assert_eq!(link(&back, id), link(&s, id)); assert!(back.doc.resources.contains_key(&link(&s, id).package)); @@ -219,8 +201,8 @@ fn cooks_through_materialcraft_cli_when_available() { eprintln!("MATERIALCRAFT_CLI is not set: skipping the materialcraft-cli round trip"); return; }; - let dir = std::env::temp_dir().join(format!("tc-mc-link-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); let pkg = dir.join("bricks.mcraft"); let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); assert!(ok.success()); @@ -229,35 +211,59 @@ fn cooks_through_materialcraft_cli_when_available() { .arg("run") .arg(&pkg) .arg("graph.exposed.add") - .arg(r#"{"id": "wear", "default": 0.5}"#) + .arg(r#"{"id":"wear","bind":{"node":5,"param":"color"}}"#) .arg("-o") .arg(&exposed) .status() .unwrap(); assert!(ok.success()); + // This input feeds the metallic output from the texture set's baked curvature. + let with_input = dir.join("with_input.mcraft"); + let add = std::process::Command::new(&cli) + .arg("run") + .arg(&exposed) + .arg("graph.node.add") + .arg(r#"{"def":"input_grayscale","params":{"identifier":"curvature"}}"#) + .arg("-o") + .arg(&with_input) + .output() + .unwrap(); + assert!(add.status.success(), "{}", String::from_utf8_lossy(&add.stderr)); + let new_node: Value = serde_json::from_slice(&add.stdout).unwrap(); + let connect = json!({"from":new_node["id"],"to":8,"toPort":"input"}); + let ok = + std::process::Command::new(&cli).arg("run").arg(&with_input).arg("graph.connect").arg(connect.to_string()).arg("-o").arg(&exposed).status().unwrap(); + assert!(ok.success()); let mut s = session(); + s.doc.baked.insert(0, BakedMaps { resolution: 16, maps: [(BakedMap::Curvature, Arc::new(vec![0.35; 256]))].into() }); let id = s.add_linked_material_bytes_at(&std::fs::read(&exposed).unwrap(), Place::Selection).unwrap(); assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution"); assert!(link(&s, id).params.iter().any(|p| p.id == "wear")); - execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": 0.8})).unwrap(); - let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"].as_f64().unwrap(); + assert!((roughness(&mut s) - 0.5).abs() < 0.01); + assert!((s.caches[0].composite.value(Channel::Metallic, 64, 64)[0] - 0.35).abs() < 0.01); + execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": [0.8,0.8,0.8,1.0]})).unwrap(); + let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"][0].as_f64().unwrap(); assert!((wear - 0.8).abs() < 1e-6); - let out = dir.join("back.sbs"); + assert!((roughness(&mut s) - 0.8).abs() < 0.01); + let out = dir.join("back.mcraft"); execute(&mut s, "material.link.saveSource", &json!({"layer": id.0, "path": out.to_str().unwrap()})).unwrap(); - assert!(std::fs::metadata(&out).unwrap().len() > 0); + assert_eq!(std::fs::read(&out).unwrap(), std::fs::read(&exposed).unwrap()); // The portable material can name a graph other than the first in the embedded source. let multi = dir.join("multi.mcraft"); let ok = std::process::Command::new(&cli).arg("run").arg(&exposed).arg("graph.duplicate").arg("{}").arg("-o").arg(&multi).status().unwrap(); assert!(ok.success()); let portable = dir.join("second.mcmat"); - let params = json!({"graph": 1, "size": 64, "path": portable.to_str().unwrap()}); - let ok = std::process::Command::new(&cli).arg("run").arg(&multi).arg("file.exportMaterial").arg(params.to_string()).status().unwrap(); + let ok = std::process::Command::new(&cli).arg("publish").arg(&multi).arg(&portable).args(["--graph", "1"]).status().unwrap(); assert!(ok.success()); let second = s.add_linked_material_bytes_at(&std::fs::read(&portable).unwrap(), Place::Selection).unwrap(); let expected_graph = link(&s, second).graph; + s.update(); + assert!((s.caches[0].composite.value(Channel::Metallic, 64, 64)[0] - 0.35).abs() < 0.01); let job = s.link_job(second, &serde_json::Map::new()).unwrap(); - let result = texturecraft_engine::formats::mcmat::read_mcmat(&job.run().unwrap()).unwrap(); - assert_eq!(result.manifest.graph, expected_graph); - let _ = std::fs::remove_dir_all(&dir); + assert_eq!(job.source_ext, "mcmat"); + assert_eq!(job.package.as_slice(), std::fs::read(&portable).unwrap()); + let result = job.run().unwrap(); + assert_eq!(result.interface.graph, expected_graph); + assert_eq!(result.size, 128); } diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 5040f320..c49bf46a 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -1,127 +1,17 @@ -//! MaterialCraft portable materials (`.mcmat`, read only): a zip with `material.json` (the -//! manifest: maps by usage, exposed parameters, image inputs, presets), `maps/.png` -//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the -//! source package. The shared reader handles the portable container and manifest. -//! -//! Also the 16-bit PNG encoder that hands baked mesh maps to MaterialCraft as graph inputs. - +//! Validate a procedural MCMAT and encode caller-supplied mesh maps for MaterialCraft. +use crate::{FormatError, Result}; use std::io::Cursor; -use serde::Deserialize; -use texturecraft_core::{LinkParam, LinkPreset}; - -use crate::{FormatError, Result}; - -/// The portable material extension. pub const MCMAT_EXT: &str = "mcmat"; -/// MaterialCraft's package extension. pub const MCRAFT_EXT: &str = "mcraft"; -const VERSION: u32 = 2; -/// Largest entry read (maps are at most 8192² × 16 bits, compressed). -const MAX_ENTRY: u64 = 512 << 20; -/// Most map entries one manifest may name (a material has at most nine usages). -const MAX_MAPS: usize = 64; -/// Largest total payload read from one `.mcmat`: maps and source together (audit: TextureCraft #4). -const MAX_TOTAL: u64 = 1 << 30; -const KIND: &str = "MaterialCraft material"; -#[derive(Clone, Debug, PartialEq, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Manifest { - pub format: String, - pub version: u32, - pub name: String, - pub graph: String, - pub size: [u32; 2], - pub maps: Vec, - #[serde(default)] - pub parameters: Vec, - #[serde(default)] - pub inputs: Vec, - #[serde(default)] - pub presets: Vec, - pub source: String, -} - -#[derive(Clone, Debug, PartialEq, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MapEntry { - /// `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive`, - /// `opacity` or `specular`. - pub usage: String, - pub file: String, -} - -#[derive(Clone, Debug, PartialEq, Deserialize)] -pub struct ImageInput { - pub identifier: String, -} - -/// A read `.mcmat`: the manifest, each map's PNG bytes by usage, the source package. -#[derive(Clone, Debug)] -pub struct PortableMaterial { - pub manifest: Manifest, - pub maps: Vec<(String, Vec)>, - pub source: Vec, -} - -fn malformed(msg: impl Into) -> FormatError { - FormatError::Malformed { kind: KIND, msg: msg.into() } -} - -fn shared_error(error: craft_mcmat::Error) -> FormatError { - match error { - craft_mcmat::Error::Version(version) => FormatError::Unsupported(format!("{KIND} version {version} (this version reads up to {VERSION})")), - craft_mcmat::Error::Limit(message) => malformed(message), - craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(error.to_string()), - other => malformed(other.to_string()), - } -} - -/// Read `.mcmat` bytes within TextureCraft's existing per-entry and total payload limits. -pub fn read_mcmat(bytes: &[u8]) -> Result { - let limits = craft_mcmat::Limits { - min_version: 0, - max_version: VERSION, - max_entries: 100_000, - max_maps: MAX_MAPS, - max_manifest_bytes: MAX_ENTRY, - max_entry_bytes: MAX_ENTRY, - max_total_bytes: MAX_TOTAL, - }; - let mut archive = craft_mcmat::Material::open(bytes, limits).map_err(shared_error)?; - // Consume the JSON values rather than cloning the entire untrusted manifest into a second tree. - let parameters = std::mem::take(&mut archive.manifest.parameters) - .into_iter() - .map(serde_json::from_value) - .collect::>() - .map_err(|e| malformed(format!("material.json: {e}")))?; - let inputs = std::mem::take(&mut archive.manifest.inputs) - .into_iter() - .map(serde_json::from_value) - .collect::>() - .map_err(|e| malformed(format!("material.json: {e}")))?; - let presets = std::mem::take(&mut archive.manifest.presets) - .into_iter() - .map(serde_json::from_value) - .collect::>() - .map_err(|e| malformed(format!("material.json: {e}")))?; - let shared = &archive.manifest; - let manifest = Manifest { - format: shared.format.clone(), - version: shared.version, - name: shared.name.clone(), - graph: shared.graph.clone(), - size: shared.size, - maps: shared.maps.iter().map(|m| MapEntry { usage: m.usage.clone(), file: m.file.clone() }).collect(), - parameters, - inputs, - presets, - source: shared.source.clone(), - }; - let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), archive.read(&map.file).map_err(shared_error)?))).collect::>>()?; - let source = archive.read_source().map_err(shared_error)?; - Ok(PortableMaterial { manifest, maps, source }) +/// Check the v3 envelope before passing the original bytes to the CLI. SBS evaluation belongs to MaterialCraft. +pub fn validate_mcmat(bytes: &[u8]) -> Result<()> { + craft_mcmat::Material::open(bytes, craft_mcmat::Limits::default()).map(drop).map_err(|err| match err { + craft_mcmat::Error::Version(_) => FormatError::Unsupported(err.to_string()), + craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(err.to_string()), + _ => FormatError::Malformed { kind: "MaterialCraft material", msg: err.to_string() }, + }) } /// Whether `bytes` contain a portable material manifest within the ZIP entry limit. @@ -166,78 +56,18 @@ mod tests { use super::*; use std::io::Write; - /// A `.mcmat` as MaterialCraft writes it (see its `formats/src/material.rs`). - pub(crate) fn sample(version: u32) -> Vec { - let source = if version >= 2 { "source.sbs" } else { "source.mcraft" }; - let manifest = serde_json::json!({ - "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], - "maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}], - "parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": 0.25}}], - "inputs": [{"identifier": "curvature", "kind": "gray"}], - "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}], - "source": source, "futureField": true - }); - let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); - let o = zip::write::SimpleFileOptions::default(); - z.start_file("material.json", o).unwrap(); - z.write_all(manifest.to_string().as_bytes()).unwrap(); - z.start_file("maps/baseColor.png", o).unwrap(); - z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); - z.start_file(source, o).unwrap(); - z.write_all(b"pkg").unwrap(); - z.finish().unwrap().into_inner() - } - #[test] - fn reads_manifest_maps_and_source() { - let bytes = sample(1); - - assert!(is_mcmat(&bytes) && !is_mcraft(&bytes)); - let material = read_mcmat(&bytes).unwrap(); - - assert_eq!(material.manifest.graph, "Brick_wall"); - assert_eq!(material.manifest.parameters[0].id, "wear"); - assert_eq!(material.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25})); - assert_eq!(material.manifest.presets[0].name, "Worn"); - assert_eq!(material.manifest.inputs[0].identifier, "curvature"); - assert_eq!(material.maps[0].0, "baseColor"); - assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4); - assert_eq!(material.source, b"pkg"); - let current = read_mcmat(&sample(2)).unwrap(); - assert_eq!(current.manifest.source, "source.sbs"); - assert_eq!(current.source, b"pkg"); - assert!(matches!(read_mcmat(&sample(3)), Err(FormatError::Unsupported(_)))); - assert!(read_mcmat(b"junk").is_err()); - } - - #[test] - fn recognizes_both_generations_of_source_archive_without_confusing_portable_materials() { - for entry in ["package.json", "package.sbs"] { + fn recognizes_v3_and_directs_older_authors_to_republish() { + let source = craft_mcmat::write(b"", []).unwrap(); + assert!(is_mcmat(&source) && !is_mcraft(&source)); + validate_mcmat(&source).unwrap(); + for version in [1, 2] { let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); - zip.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); - zip.write_all(b"source").unwrap(); - let bytes = zip.finish().unwrap().into_inner(); - assert!(is_mcraft(&bytes), "{entry}"); + zip.start_file("material.json", zip::write::SimpleFileOptions::default()).unwrap(); + write!(zip, r#"{{"version":{version}}}"#).unwrap(); + let err = validate_mcmat(&zip.finish().unwrap().into_inner()).unwrap_err(); + assert!(err.to_string().contains("Republish")); } - assert!(!is_mcraft(&sample(2)), "a portable material contains source.sbs too"); - } - - #[test] - fn an_unbounded_map_list_is_refused() { - let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); - let manifest = serde_json::json!({"format": craft_mcmat::FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); - let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); - let options = zip::write::SimpleFileOptions::default(); - archive.start_file("material.json", options).unwrap(); - archive.write_all(manifest.to_string().as_bytes()).unwrap(); - archive.start_file("maps/baseColor.png", options).unwrap(); - archive.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); - archive.start_file("source.mcraft", options).unwrap(); - archive.write_all(b"pkg").unwrap(); - - let result = read_mcmat(&archive.finish().unwrap().into_inner()); - - assert!(matches!(result, Err(FormatError::Malformed { .. }))); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 28d8b44f..9f045a4c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -104,12 +104,15 @@ pub struct ResizeJob { pub rx: std::sync::mpsc::Receiver>, } +#[cfg(not(target_arch = "wasm32"))] +mod link_import; + /// A MaterialCraft material re-cooking on a worker thread (one per layer at a time). pub struct LinkCook { pub layer: texturecraft_engine::core::LayerId, /// The parameter values it cooks: a result whose values are no longer the layer's is redone. pub values: serde_json::Map, - pub rx: std::sync::mpsc::Receiver>>, + pub rx: std::sync::mpsc::Receiver>, } /// The engine's refusal to paint while a bake shows (translated where it is toasted). @@ -143,6 +146,8 @@ pub struct TextureCraftApp { pub pbr_import: Option, pub resize: Option, pub link_cooks: Vec, + #[cfg(not(target_arch = "wasm32"))] + link_imports: Vec, pub thumbs: thumbs::Thumbs, /// The Layers panel's thumbnails and folded groups. pub layer_panel: layer_panel::LayerPanel, @@ -232,6 +237,8 @@ impl TextureCraftApp { pbr_import: None, resize: None, link_cooks: Vec::new(), + #[cfg(not(target_arch = "wasm32"))] + link_imports: Vec::new(), thumbs: thumbs::Thumbs::default(), layer_panel: layer_panel::LayerPanel::default(), viewport_rect: egui::Rect::NOTHING, @@ -294,6 +301,13 @@ impl TextureCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { self.ui.prefs.apply_resource_limits(); + #[cfg(not(target_arch = "wasm32"))] + if id == "material.load" + && let Some(path) = params.get("path").and_then(Value::as_str) + && link_import::is_procedural(path) + { + return self.start_link_import(path, ¶ms); + } // Going to a saved camera glides there; the control channel and CLI jump straight away let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); @@ -397,8 +411,8 @@ impl TextureCraftApp { // The layer is gone (undone, deleted): nothing to show. (_, Err(_)) => {} (Ok(_), Ok(now)) if now != values => self.cook_link(layer), - (Ok(bytes), Ok(_)) => { - if let Err(e) = self.session.apply_link_cook(layer, &bytes, true) { + (Ok(material), Ok(_)) => { + if let Err(e) = self.session.apply_link_cook(layer, &material, true) { self.toast(e.to_string(), true); } } @@ -723,6 +737,8 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.poll_resize(ctx); self.poll_link_cooks(ctx); + #[cfg(not(target_arch = "wasm32"))] + self.poll_link_imports(ctx); self.thumbs.sync_images(&self.session.images, self.session.revision); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) diff --git a/crates/ui-egui/src/link_import.rs b/crates/ui-egui/src/link_import.rs new file mode 100644 index 00000000..fd5b0144 --- /dev/null +++ b/crates/ui-egui/src/link_import.rs @@ -0,0 +1,68 @@ +//! The first procedural bake can take as long as a re-cook. Keep the native UI responsive. +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use crate::TextureCraftApp; +use serde_json::{Value, json}; +use texturecraft_engine::link_cmds::{CookedMaterial, LinkJob, cook_link_file}; +use texturecraft_engine::materials::Place; + +pub(super) struct Import { + mesh: u64, + set: usize, + resolution: u32, + place: Place, + result: Receiver>, +} + +pub(super) fn is_procedural(path: &str) -> bool { + Path::new(path).extension().and_then(|s| s.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("mcmat") || ext.eq_ignore_ascii_case("mcraft")) +} + +impl TextureCraftApp { + pub(super) fn start_link_import(&mut self, path: &str, params: &Value) -> Option { + let set = self.session.ts(); + let resolution = match self.session.doc.project.texture_set(set) { + Ok(set) => set.resolution, + Err(error) => { + self.toast(error.to_string(), true); + return None; + } + }; + let baked = self.session.baked(set).cloned(); + let path = PathBuf::from(path); + let rx = super::spawn_worker("texturecraft-material-import", move || cook_link_file(&path, resolution, baked.as_ref())); + self.link_imports.push(Import { mesh: self.session.mesh_id, set, resolution, place: Place::from_params(params), result: rx }); + self.toast("Cooking MaterialCraft material", false); + Some(json!({"pending":true})) + } + + pub(super) fn poll_link_imports(&mut self, ctx: &egui::Context) { + if self.link_imports.is_empty() { + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + for job in std::mem::take(&mut self.link_imports) { + let result = match job.result.try_recv() { + Err(TryRecvError::Empty) => { + self.link_imports.push(job); + continue; + } + Err(TryRecvError::Disconnected) => Err(texturecraft_engine::EngineError::Other("the material import stopped".into())), + Ok(result) => result, + }; + // Replacing a project or resizing its texture set invalidates the target captured at drop time. + if job.mesh != self.session.mesh_id + || job.set != self.session.ts() + || !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.resolution == job.resolution) + { + self.toast("Material import canceled because the target texture set changed", true); + continue; + } + match result.and_then(|(source, cooked)| self.session.add_cooked_material(&cooked, source.package, source.source_ext, job.place)) { + Ok(_) => self.toast("Material imported", false), + Err(error) => self.toast(error.to_string(), true), + } + } + } +} diff --git a/docs/architecture.md b/docs/architecture.md index ff4e04df..97262d68 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -122,11 +122,7 @@ on the CPU by `render::displace` from the composited height. ## MaterialCraft materials A fill can carry a `MaterialLink` (`core::layer`): a MaterialCraft graph whose cooked maps are the -fill's image sources. `engine::link_cmds` imports `.mcmat` files (`formats::mcmat`), keeps the -`.mcraft` or `.sbs` source as a resource, and re-cooks its named graph by running `materialcraft-cli` with the link's -values, the texture set's resolution and its baked mesh maps (`LinkJob::run`, on a worker thread -in the UI). Every cook stores its maps under fresh resource names, so undo, redo and the decoded -image cache never disagree. The apps share the `craft-mcmat` format library and the command line; neither depends on the other app. +fill's image sources. `engine::link_cmds` imports a procedural MCMAT v3 by asking MaterialCraft to bake the entry graph. It keeps the archive and the interface reported by the CLI with the layer. Parameter edits and mesh-map changes re-cook at the texture set's resolution. Each bake installs fresh map resources so duplicates, undo and redo preserve their own results. Both apps use the shared `craft-mcmat` library and communicate through the CLI. ## Commands and automation diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1ebe01d2..af7c9e52 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -392,12 +392,7 @@ of a second. ## MaterialCraft materials -A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is -documented in MaterialCraft's `docs/control-protocol.md` § Portable materials) becomes a fill layer -whose channel sources are its cooked maps and whose `link` (shown by `project.inspect`) holds the -graph's exposed inputs, presets and image inputs. Both apps use the shared `craft-mcmat` container. -Versions 1 and 2 are accepted; version 1 contains a legacy JSON `.mcraft` source that current -MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking needs a compatible older version. +A v3 `.mcmat` holds a published SBS graph and its source assets. TextureCraft uses the shared `craft-mcmat` reader and cooks the archive through `materialcraft-cli`. The resulting fill stores its channel textures and the original archive in the project. Its exposed values, presets and mesh-map inputs appear in `project.inspect`. Republish older MCMAT files from their original authoring project. | Command | Params | |---|---| @@ -405,9 +400,9 @@ MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking nee | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | | `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | -| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` or `.sbs` source, to open in MaterialCraft | +| `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension | -Re-cooks use `materialcraft-cli batch` to open the saved graph by name and run `file.exportMaterial` with its size, values and inputs: +TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size ` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The executable is resolved from `$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`,