mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-25 17:01:07 +01:00
Auto: Pin workspace saves and preserve material export choices
Hold the resolved save directory across SBS serialization and writes. Only clean up owned staging files and compare existing assets incrementally. Bound source assets before archive serialization, limit discarded SBS inflation, and account for shared graph depth. Decode preview inputs on demand and release failed browser downloads. Distinguish automatic and explicit output colors, borrow graphs while drawing export tabs, and preserve numeric export selectors and MCP option validation.
This commit is contained in:
1 parent
9ff2b18f08
commit
a1be44cfa1
47 files changed
+963
-438
No files matched your search
Generated
+12
-2
@@ -999,6 +999,16 @@ dependencies = [
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
@@ -2874,6 +2884,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -2954,6 +2965,7 @@ dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-dialogs",
|
||||
"craft-keymap",
|
||||
"craft-platform",
|
||||
"craft-quit",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -2963,7 +2975,6 @@ dependencies = [
|
||||
"egui-phosphor",
|
||||
"egui_kittest",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
"materialcraft-engine",
|
||||
"materialcraft-render",
|
||||
@@ -2973,7 +2984,6 @@ dependencies = [
|
||||
"sha2",
|
||||
"sys-locale",
|
||||
"tempfile",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"zip 2.6.1",
|
||||
|
||||
+3
-1
@@ -83,15 +83,17 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"]
|
||||
cap-std = "4"
|
||||
getrandom = "0.3"
|
||||
# Shared Craft egui components from storytold/craft-libs
|
||||
# MIT OR Apache-2.0; all shared dependencies use one reviewed revision
|
||||
# MIT OR Apache-2.0
|
||||
egui_kittest = "0.37"
|
||||
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# MCMAT v3 uses its merged archive revision and the matching ZIP crate
|
||||
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
|
||||
# Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
# Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0
|
||||
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-platform = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
|
||||
@@ -145,13 +145,12 @@ cargo run --release -p materialcraft # desktop app
|
||||
cargo run --release -p materialcraft -- package.sbs # open an SBS package
|
||||
cargo run --release -p materialcraft -- --control 7878 # + JSON control channel
|
||||
cargo run --release -p materialcraft-cli -- mcp # MCP server (stdio)
|
||||
cargo run --release -p materialcraft-cli -- new wood wood.sbs
|
||||
cargo run --release -p materialcraft-cli -- render wood.sbs wood.png --scene sphere --full --hq
|
||||
cargo run --release -p materialcraft-cli -- export wood.sbs textures --format png --depth 16
|
||||
# Given a separate my.sbs with Materials/Oak and an exposed wear parameter:
|
||||
cargo run --release -p materialcraft-cli -- new pbr surface.sbs --name Surface
|
||||
cargo run --release -p materialcraft-cli -- render surface.sbs surface.png --scene sphere --full --hq
|
||||
cargo run --release -p materialcraft-cli -- export surface.sbs textures --format png --depth 16
|
||||
cargo run --release -p materialcraft-cli -- export my.sbs out --set wear=0.7 # with a graph input "wear" set first
|
||||
cargo run --release -p materialcraft-cli -- publish my.sbs my.mcmat --graph Materials/Oak
|
||||
cargo run --release -p materialcraft-cli -- export my.mcmat build/oak --profile materialx --size 2048 --set wear=0.7
|
||||
cargo run --release -p materialcraft-cli -- publish surface.sbs surface.mcmat --graph Surface
|
||||
cargo run --release -p materialcraft-cli -- export surface.mcmat build/surface --profile materialx --size 512
|
||||
cd apps/materialcraft-web && trunk serve # web build
|
||||
cargo xtask ci # fmt, clippy, tests, layering, wasm
|
||||
```
|
||||
|
||||
@@ -187,9 +187,9 @@ fn graph_selector(selector: &str) -> Value {
|
||||
}
|
||||
|
||||
fn output_size(size: &str) -> Result<Value, String> {
|
||||
let pixels = |n: &str| n.parse::<u32>().map_err(|_| "--size expects pixels or WIDTHxHEIGHT".to_string());
|
||||
let pixels = |side: &str| side.parse::<u32>().map_err(|_| "--size expects pixels or WIDTHxHEIGHT".to_string());
|
||||
match size.split_once('x') {
|
||||
Some((w, h)) => Ok(json!([pixels(w)?, pixels(h)?])),
|
||||
Some((width, height)) => Ok(json!([pixels(width)?, pixels(height)?])),
|
||||
None => Ok(json!(pixels(size)?)),
|
||||
}
|
||||
}
|
||||
@@ -201,6 +201,7 @@ fn cook_parameters(a: &Args) -> Result<Value, String> {
|
||||
if flag != "--set" && flag != "--input" {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (id, value) =
|
||||
value.as_deref().and_then(|v| v.split_once('=')).filter(|(id, _)| !id.is_empty()).ok_or_else(|| format!("{flag} expects identifier=value"))?;
|
||||
if flag == "--set" {
|
||||
@@ -285,6 +286,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
|
||||
if !r["failed"].is_null() {
|
||||
return Err("the batch stopped at an error".into());
|
||||
}
|
||||
|
||||
if let Some(out) = save {
|
||||
h.save(Some(out)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
@@ -323,7 +325,10 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
|
||||
p["pattern"] = json!(a.get("--pattern"));
|
||||
p["profile"] = json!(a.get("--profile"));
|
||||
p["normalFormat"] = json!(a.get("--normal-format"));
|
||||
p["displacementScale"] = json!(a.num::<f64>("--displacement-scale")?);
|
||||
if let Some(scale) = a.num::<f64>("--displacement-scale")? {
|
||||
p["displacementScale"] = serde_json::Number::from_f64(scale).ok_or("--displacement-scale must be finite")?.into();
|
||||
}
|
||||
|
||||
print(&h.export(&p).map_err(|e| e.to_string())?);
|
||||
}
|
||||
"render" => {
|
||||
|
||||
@@ -13,19 +13,31 @@ fn run(dir: &Path, args: &[&str]) -> Value {
|
||||
|
||||
#[test]
|
||||
fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let dir = temporary.path().to_path_buf();
|
||||
run(&dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]);
|
||||
run(&dir, &["run", "source.sbs", "graph.exposed.add", r#"{"id":"tint","bind":{"node":1,"param":"color"}}"#, "-o", "studio.mcraft"]);
|
||||
run(&dir, &["publish", "studio.mcraft", "oak.mcmat", "--graph", "Oak"]);
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
run(dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]);
|
||||
run(dir, &["run", "source.sbs", "graph.exposed.add", r#"{"id":"tint","bind":{"node":1,"param":"color"}}"#, "-o", "studio.mcraft"]);
|
||||
run(dir, &["publish", "studio.mcraft", "oak.mcmat", "--graph", "Oak"]);
|
||||
std::fs::remove_file(dir.join("studio.mcraft")).unwrap();
|
||||
std::fs::remove_file(dir.join("source.sbs")).unwrap();
|
||||
let initial = run(&dir, &["info", "oak.mcmat"]);
|
||||
|
||||
let invalid_scale = Command::new(env!("CARGO_BIN_EXE_materialcraft-cli"))
|
||||
.current_dir(dir)
|
||||
.args(["export", "oak.mcmat", "invalid", "--profile", "materialx", "--displacement-scale", "NaN"])
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
assert!(!invalid_scale.status.success(), "an invalid displacement scale produced a material");
|
||||
assert!(String::from_utf8_lossy(&invalid_scale.stderr).contains("displacement-scale"));
|
||||
assert!(!dir.join("invalid").exists());
|
||||
|
||||
let initial = run(dir, &["info", "oak.mcmat"]);
|
||||
assert_eq!(initial["parameters"][0]["id"], "tint");
|
||||
for (folder, size, tint) in [("small", 32, "#ff0000"), ("large", 64, "#0000ff")] {
|
||||
let report =
|
||||
run(&dir, &["export", "oak.mcmat", "--out", folder, "--profile", "materialx", "--size", &size.to_string(), "--set", &format!("tint={tint}")]);
|
||||
run(dir, &["export", "oak.mcmat", "--out", folder, "--profile", "materialx", "--size", &size.to_string(), "--set", &format!("tint={tint}")]);
|
||||
let maps = report["maps"].as_array().unwrap();
|
||||
assert_eq!(maps.len(), 6, "every output of the material template is exported");
|
||||
let base = maps.iter().find(|m| m["usage"] == "baseColor").unwrap();
|
||||
let relative = base["file"].as_str().unwrap();
|
||||
assert_eq!(base["size"], json!([size, size]));
|
||||
@@ -42,21 +54,21 @@ fn a_published_graph_bakes_openpbr_variations_after_the_project_is_removed() {
|
||||
assert!((displacement.get(0, 0, false)[0] + 0.5).abs() < 1e-5);
|
||||
assert!(report["unmapped"].as_array().unwrap().iter().any(|id| id == "ambientocclusion"));
|
||||
}
|
||||
let rectangular = run(&dir, &["cook", "oak.mcmat", "--size", "64x32"]);
|
||||
let rectangular = run(dir, &["cook", "oak.mcmat", "--size", "64x32"]);
|
||||
assert_eq!(rectangular["outputs"][0]["size"], json!([64, 32]));
|
||||
assert_eq!(run(&dir, &["info", "oak.mcmat"]), initial);
|
||||
assert_eq!(run(dir, &["info", "oak.mcmat"]), initial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_materialx_reexport_preserves_the_last_complete_material() {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let dir = temporary.path().to_path_buf();
|
||||
run(&dir, &["new", "pbr", "source.sbs", "--name", "Oak", "--size", "32"]);
|
||||
let export = |folder, size| run(&dir, &["export", "source.sbs", folder, "--profile", "materialx", "--size", size]);
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
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 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"]);
|
||||
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"]
|
||||
@@ -74,12 +86,14 @@ fn failed_materialx_reexport_preserves_the_last_complete_material() {
|
||||
std::fs::create_dir(&blocked).unwrap();
|
||||
|
||||
let failed = Command::new(env!("CARGO_BIN_EXE_materialcraft-cli"))
|
||||
.current_dir(&dir)
|
||||
.current_dir(dir)
|
||||
.args(["export", "source.sbs", "material", "--profile", "materialx", "--size", "64"])
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
assert!(!failed.status.success());
|
||||
let error = String::from_utf8_lossy(&failed.stderr);
|
||||
assert!(error.contains(blocked.file_name().unwrap().to_str().unwrap()), "{error}");
|
||||
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}");
|
||||
|
||||
@@ -173,29 +173,32 @@ impl Headless {
|
||||
None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet (new, or opened from another program): give a `path`"))?,
|
||||
};
|
||||
|
||||
let destination = match &self.fs {
|
||||
Filesystem::Workspace(workspace) => workspace.save_document_path(&path)?.to_string_lossy().into_owned(),
|
||||
Filesystem::TrustedLocal => path.clone(),
|
||||
let (destination, workspace_write) = match &self.fs {
|
||||
Filesystem::Workspace(workspace) => {
|
||||
let (destination, writer, save_path) = workspace.save_destination(&path)?;
|
||||
(destination.to_string_lossy().into_owned(), Some((writer, save_path)))
|
||||
}
|
||||
Filesystem::TrustedLocal => (path.clone(), None),
|
||||
Filesystem::Denied => return Err(bad("file access is not granted")),
|
||||
};
|
||||
let files = file_cmds::save_files_at(&self.session, &destination)?;
|
||||
let bytes = if file_cmds::is_mcraft(&path) {
|
||||
let bytes = files.zip().map_err(|error| bad(error.to_string()))?;
|
||||
self.write(&path, &bytes)?;
|
||||
if let Some((writer, save_path)) = &workspace_write {
|
||||
writer.write(save_path, &bytes)?;
|
||||
} else {
|
||||
self.write(&path, &bytes)?;
|
||||
}
|
||||
bytes.len()
|
||||
} else {
|
||||
match &self.fs {
|
||||
Filesystem::Denied => return Err(bad("file access is not granted")),
|
||||
Filesystem::TrustedLocal => {
|
||||
materialcraft_engine::formats::project::write_files(Path::new(&path), &files).map_err(|error| bad(error.to_string()))?
|
||||
}
|
||||
Filesystem::Workspace(workspace) => {
|
||||
workspace.check_write(&path)?;
|
||||
let parent = path.rsplit_once('/').map_or(String::new(), |(parent, _)| format!("{parent}/"));
|
||||
match &workspace_write {
|
||||
None => materialcraft_engine::formats::project::write_files(Path::new(&path), &files).map_err(|error| bad(error.to_string()))?,
|
||||
Some((writer, save_path)) => {
|
||||
let parent = save_path.rsplit_once('/').map_or(String::new(), |(parent, _)| format!("{parent}/"));
|
||||
for name in files.files.keys().filter(|name| *name != &files.entry) {
|
||||
workspace.check_write(&format!("{parent}{name}"))?;
|
||||
writer.check_write(&format!("{parent}{name}"))?;
|
||||
}
|
||||
workspace.create_dir_all(&format!("{parent}resources"))?;
|
||||
writer.create_dir_all(&format!("{parent}resources"))?;
|
||||
for (name, bytes) in &files.files {
|
||||
if name == &files.entry {
|
||||
continue;
|
||||
@@ -203,11 +206,11 @@ impl Headless {
|
||||
|
||||
let target = format!("{parent}{name}");
|
||||
if let Some((directory, _)) = target.rsplit_once('/') {
|
||||
workspace.create_dir_all(directory)?;
|
||||
writer.create_dir_all(directory)?;
|
||||
}
|
||||
workspace.write_resource(&target, bytes.as_slice())?;
|
||||
writer.write_resource(&target, bytes.as_slice())?;
|
||||
}
|
||||
workspace.write(&path, files.xml().map_err(|error| bad(error.to_string()))?)?;
|
||||
writer.write(save_path, files.xml().map_err(|error| bad(error.to_string()))?)?;
|
||||
}
|
||||
}
|
||||
files.xml().map_err(|error| bad(error.to_string()))?.len()
|
||||
@@ -254,7 +257,11 @@ impl Headless {
|
||||
}
|
||||
|
||||
let gi = material_cmds::publish_graph(&self.session, p)?;
|
||||
let bytes = material_cmds::material_bytes(&self.session, gi)?;
|
||||
let bytes = if self.trusted() {
|
||||
material_cmds::material_bytes(&self.session, gi)?
|
||||
} else {
|
||||
material_cmds::material_bytes_with_resource_limit(&self.session, gi, MAX_EXPORTED_MATERIAL_BYTES)?
|
||||
};
|
||||
if bytes.len() as u64 > MAX_EXPORTED_MATERIAL_BYTES {
|
||||
return Err(bad(format!("the material is {} bytes (limit {MAX_EXPORTED_MATERIAL_BYTES}); reduce source asset sizes", bytes.len())));
|
||||
}
|
||||
|
||||
@@ -272,9 +272,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A workspace session rooted at a fresh `inside` folder, with an `outside` sibling.
|
||||
fn workspace_session(name: &str, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex<Headless>) {
|
||||
let base = std::env::temp_dir().join(format!("mc-rpc-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
fn workspace_session(base: &std::path::Path, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex<Headless>) {
|
||||
let (inside, outside) = (base.join("inside"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
@@ -289,24 +287,29 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn material_export_writes_a_portable_material_below_the_write_root() {
|
||||
let (inside, _, h) = workspace_session("mat-ok", true);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, h) = workspace_session(directory.path(), true);
|
||||
std::fs::create_dir(inside.join("out")).unwrap();
|
||||
let r = call(&h, "material.export", json!({"path": "out/brick"})).unwrap();
|
||||
assert_eq!(r["path"], "out/brick.mcmat");
|
||||
|
||||
let published = call(&h, "material.export", json!({"path": "out/brick"})).unwrap();
|
||||
|
||||
assert_eq!(published["path"], "out/brick.mcmat");
|
||||
let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap();
|
||||
assert_eq!(r["bytes"], bytes.len());
|
||||
assert_eq!(published["bytes"], bytes.len());
|
||||
let (package, entry) = materialcraft_engine::formats::material::read_material(&bytes).unwrap();
|
||||
assert!(package.graph(entry).unwrap().nodes.iter().any(|node| node.def == "output"));
|
||||
assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind");
|
||||
// An explicit extension is kept (case-insensitively) and the file can be opened again.
|
||||
let r = call(&h, "material.export", json!({"path": "again.MCMAT"})).unwrap();
|
||||
assert_eq!(r["path"], "again.MCMAT");
|
||||
|
||||
// Preserve the caller’s extension spelling when reopening the archive
|
||||
let published = call(&h, "material.export", json!({"path": "again.MCMAT"})).unwrap();
|
||||
assert_eq!(published["path"], "again.MCMAT");
|
||||
assert!(call(&h, "package.open", json!({"path": "again.MCMAT"})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_export_reports_bad_requests() {
|
||||
let (inside, _, h) = workspace_session("mat-bad", true);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, h) = workspace_session(directory.path(), true);
|
||||
for bad in [json!({}), json!({"path": "m", "graph": 99}), json!({"path": "m", "values": {"no_such_input": 1}})] {
|
||||
assert!(call(&h, "material.export", bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
@@ -319,7 +322,8 @@ mod tests {
|
||||
let denied = session();
|
||||
let e = call(&denied, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
|
||||
assert!(e.contains("not granted"), "{e}");
|
||||
let (inside, _, read_only) = workspace_session("mat-readonly", false);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, read_only) = workspace_session(directory.path(), false);
|
||||
let e = call(&read_only, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
|
||||
assert!(e.contains("no write root"), "{e}");
|
||||
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0);
|
||||
@@ -327,7 +331,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn material_export_cannot_escape_the_write_root() {
|
||||
let (_inside, outside, h) = workspace_session("mat-escape", true);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (_inside, outside, h) = workspace_session(directory.path(), true);
|
||||
let abs = outside.join("abs.mcmat").display().to_string();
|
||||
for p in ["../outside/m.mcmat", "a/../../outside/m.mcmat", "/tmp/m.mcmat", "a\\b.mcmat", "C:/m.mcmat", "./m.mcmat", abs.as_str()] {
|
||||
let e = call(&h, "material.export", json!({"path": p}));
|
||||
@@ -339,7 +344,8 @@ mod tests {
|
||||
assert!(call(&h, "material.export", json!({"path": "link/m.mcmat"})).is_err());
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "nothing written outside the root");
|
||||
// The generic command path stays closed too: host paths are still refused.
|
||||
|
||||
// The generic command must enforce the same file access boundary
|
||||
let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err();
|
||||
assert!(e.contains("disabled for automation"), "{e}");
|
||||
}
|
||||
|
||||
@@ -299,21 +299,22 @@ mod tests {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn material_export_tool_writes_through_the_workspace_only() {
|
||||
let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let write_root = directory.path().join("workspace");
|
||||
std::fs::create_dir(&write_root).unwrap();
|
||||
let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None });
|
||||
|
||||
let denied = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
|
||||
assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true));
|
||||
|
||||
let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap();
|
||||
let ws = crate::AuthorizedWorkspace::new(None, Some(&write_root)).unwrap();
|
||||
let mcp = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
|
||||
assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false));
|
||||
assert!(base.join("m.mcmat").is_file());
|
||||
assert!(write_root.join("m.mcmat").is_file());
|
||||
|
||||
let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None });
|
||||
assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true));
|
||||
assert!(!base.parent().unwrap().join("m.mcmat").exists());
|
||||
assert!(!directory.path().join("m.mcmat").exists());
|
||||
}
|
||||
|
||||
/// Every sub-schema must be a JSON object. Claude Desktop's proxy rejects a boolean schema
|
||||
|
||||
@@ -4,6 +4,8 @@ use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
// Some MCP clients reject boolean sub-schemas
|
||||
#[schemars(extend("additionalProperties" = {"not": {}}))]
|
||||
pub struct MaterialExportParams {
|
||||
/// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The
|
||||
/// parent folder must exist
|
||||
@@ -19,11 +21,16 @@ mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn material_publication_rejects_legacy_bake_size() {
|
||||
for size in [json!(256), json!(null)] {
|
||||
let error = serde_json::from_value::<MaterialExportParams>(json!({"path":"material", "size":size})).unwrap_err();
|
||||
assert!(error.to_string().contains("unknown field `size`"));
|
||||
fn material_publication_rejects_bake_options() {
|
||||
for (option, value) in [("size", json!(256)), ("size", json!(null)), ("values", json!({})), ("inputs", json!({})), ("preset", json!("Worn"))] {
|
||||
let mut request = json!({"path":"material"});
|
||||
request[option] = value;
|
||||
|
||||
let error = serde_json::from_value::<MaterialExportParams>(request).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains(&format!("unknown field `{option}`")));
|
||||
}
|
||||
|
||||
let params = serde_json::from_value::<MaterialExportParams>(json!({"path":"material", "graph":"Materials/Oak"})).unwrap();
|
||||
assert_eq!(params.graph, Some(json!("Materials/Oak")));
|
||||
}
|
||||
|
||||
@@ -36,21 +36,21 @@ impl AuthorizedWorkspace {
|
||||
Ok(self.read_path.as_ref().ok_or_else(|| denied("read"))?.join(relative_path(path)?))
|
||||
}
|
||||
|
||||
/// Absolute destination identity for rebasing links; writes still use the capability.
|
||||
pub(crate) fn save_document_path(&self, path: &str) -> Result<PathBuf, AutomationError> {
|
||||
/// Resolve a save once and keep its destination capability through serialization and writes.
|
||||
pub(crate) fn save_destination(&self, path: &str) -> Result<(PathBuf, Self, String), AutomationError> {
|
||||
let relative = relative_path(path)?;
|
||||
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
|
||||
let parent = relative.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
// A permitted directory symlink can change the number of parent traversals
|
||||
// needed by saved links. Resolve it inside the same write capability.
|
||||
|
||||
// Resolve directory symlinks inside the capability so rebased links use the correct depth
|
||||
let mut ancestor = parent;
|
||||
let mut suffix = PathBuf::new();
|
||||
let parent = loop {
|
||||
let resolved_ancestor = loop {
|
||||
match root.canonicalize(ancestor) {
|
||||
Ok(resolved) => break resolved.join(&suffix),
|
||||
Ok(resolved) => break resolved,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
// Preserve save-to-new-directory behavior without creating anything
|
||||
// before serialization. Do not treat a dangling symlink as missing.
|
||||
// Defer directory creation until after serialization
|
||||
// Reject dangling symlinks
|
||||
match root.symlink_metadata(ancestor) {
|
||||
Err(missing) if missing.kind() == std::io::ErrorKind::NotFound => {}
|
||||
_ => return Err(file_error("resolve destination", path, error)),
|
||||
@@ -62,14 +62,24 @@ impl AuthorizedWorkspace {
|
||||
Err(error) => return Err(file_error("resolve destination", path, error)),
|
||||
}
|
||||
};
|
||||
|
||||
let leaf = relative.file_name().ok_or_else(|| bad("missing destination filename"))?;
|
||||
Ok(self.write_path.as_ref().ok_or_else(|| denied("write"))?.join(parent).join(leaf))
|
||||
let relative = suffix.join(leaf);
|
||||
let save_path = relative.to_str().ok_or_else(|| bad("the save path must be UTF-8"))?.replace('\\', "/");
|
||||
let write_path = self.write_path.as_ref().ok_or_else(|| denied("write"))?.join(&resolved_ancestor);
|
||||
|
||||
// Writes through this handle no longer traverse the original directory alias
|
||||
let dir = root.open_dir(&resolved_ancestor).map_err(|error| file_error("resolve destination", path, error))?;
|
||||
let destination = write_path.join(relative);
|
||||
let workspace = Self { write: Some(Arc::new(dir)), write_path: Some(write_path), ..Self::default() };
|
||||
Ok((destination, workspace, save_path))
|
||||
}
|
||||
|
||||
pub(crate) fn read_dependency(&self, path: &str) -> Option<Vec<u8>> {
|
||||
if path.starts_with("sbs://") {
|
||||
return materialcraft_engine::formats::sbs::library::read(path).ok();
|
||||
}
|
||||
|
||||
let relative = Path::new(path).strip_prefix(self.read_path.as_ref()?).ok()?;
|
||||
self.read(&relative.to_str()?.replace('\\', "/")).ok()
|
||||
}
|
||||
@@ -87,11 +97,13 @@ impl AuthorizedWorkspace {
|
||||
if metadata.len() > MAX_READ_BYTES {
|
||||
return Err(bad(format!("file too large: `{path}` is {} bytes (limit {MAX_READ_BYTES})", metadata.len())));
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_READ_BYTES + 1).read_to_end(&mut bytes).map_err(|e| file_error("read", path, e))?;
|
||||
if bytes.len() as u64 > MAX_READ_BYTES {
|
||||
return Err(bad(format!("file too large: `{path}` exceeds the {MAX_READ_BYTES}-byte limit")));
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
@@ -103,17 +115,17 @@ impl AuthorizedWorkspace {
|
||||
let tmp = rel.with_file_name(format!(".{leaf}.{}.tmp", std::process::id()));
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
let res = root
|
||||
.open_with(&tmp, &options)
|
||||
.and_then(|mut f| {
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()
|
||||
})
|
||||
.and_then(|()| root.rename(&tmp, root, &rel));
|
||||
if let Err(e) = res {
|
||||
|
||||
// Only the writer that acquired the staging file may remove it
|
||||
let mut file = root.open_with(&tmp, &options).map_err(|error| file_error("write", path, error))?;
|
||||
let written = file.write_all(bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
|
||||
if let Err(error) = written.and_then(|()| root.rename(&tmp, root, &rel)) {
|
||||
let _ = root.remove_file(&tmp);
|
||||
return Err(file_error("write", path, e));
|
||||
return Err(file_error("write", path, error));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -150,9 +162,7 @@ impl AuthorizedWorkspace {
|
||||
return Err(bad(format!("Resource filename collision: `{path}`")));
|
||||
}
|
||||
|
||||
let mut existing = Vec::new();
|
||||
file.take(bytes.len() as u64 + 1).read_to_end(&mut existing).map_err(|error| file_error("read", path, error))?;
|
||||
if existing != bytes {
|
||||
if !resource_matches(file, bytes).map_err(|error| file_error("read", path, error))? {
|
||||
return Err(bad(format!("Resource filename collision: `{path}`")));
|
||||
}
|
||||
}
|
||||
@@ -162,7 +172,28 @@ impl AuthorizedWorkspace {
|
||||
}
|
||||
}
|
||||
|
||||
// Keep capability-based resolution while preventing FIFO opens from waiting for a writer.
|
||||
// A repeated save compares immutable assets without buffering a second copy
|
||||
fn resource_matches(mut file: cap_std::fs::File, mut expected: &[u8]) -> std::io::Result<bool> {
|
||||
const COMPARISON_BUFFER_BYTES: usize = 8 * 1024;
|
||||
let mut buffer = [0; COMPARISON_BUFFER_BYTES];
|
||||
loop {
|
||||
let count = match file.read(&mut buffer) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
result => result?,
|
||||
};
|
||||
if count == 0 {
|
||||
return Ok(expected.is_empty());
|
||||
}
|
||||
|
||||
let Some(rest) = expected.strip_prefix(&buffer[..count]) else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
expected = rest;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep capability-based resolution while preventing FIFO opens from waiting for a writer
|
||||
fn regular_read_options() -> OpenOptions {
|
||||
let mut options = OpenOptions::new();
|
||||
options.read(true);
|
||||
@@ -179,6 +210,7 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<Arc<Dir>>, A
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err(bad(format!("the automation {authority} root is empty")));
|
||||
}
|
||||
|
||||
let dir =
|
||||
Dir::open_ambient_dir(path, ambient_authority()).map_err(|e| AutomationError::Io(format!("cannot open {authority} root `{}`: {e}", path.display())))?;
|
||||
Ok(Some(Arc::new(dir)))
|
||||
@@ -190,29 +222,36 @@ pub fn relative_path(raw: &str) -> Result<PathBuf, AutomationError> {
|
||||
if raw.is_empty() {
|
||||
return Err(reject("empty"));
|
||||
}
|
||||
|
||||
if raw.contains('\\') {
|
||||
return Err(reject("backslash"));
|
||||
}
|
||||
|
||||
if raw.starts_with('/') {
|
||||
return Err(reject("absolute"));
|
||||
}
|
||||
|
||||
if raw.contains(':') {
|
||||
return Err(reject("drive, scheme or stream prefix"));
|
||||
}
|
||||
for c in raw.split('/') {
|
||||
if c.is_empty() || c == "." || c == ".." {
|
||||
|
||||
for component in raw.split('/') {
|
||||
if component.is_empty() || component == "." || component == ".." {
|
||||
return Err(reject("empty, `.` or `..` component"));
|
||||
}
|
||||
if c.ends_with(['.', ' ']) || c.chars().any(char::is_control) {
|
||||
|
||||
if component.ends_with(['.', ' ']) || component.chars().any(char::is_control) {
|
||||
return Err(reject("component ends in a dot or space, or has control characters"));
|
||||
}
|
||||
let stem = c.split('.').next().unwrap_or(c).to_ascii_uppercase();
|
||||
|
||||
let stem = component.split('.').next().unwrap_or(component).to_ascii_uppercase();
|
||||
let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|
||||
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.ends_with(|ch: char| ch.is_ascii_digit()));
|
||||
if device {
|
||||
return Err(reject("reserved device name"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(PathBuf::from(raw))
|
||||
}
|
||||
|
||||
@@ -245,9 +284,7 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) {
|
||||
let base = std::env::temp_dir().join(format!("mc-ws-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
fn roots(base: &Path) -> (PathBuf, PathBuf, AuthorizedWorkspace) {
|
||||
let (inside, outside) = (base.join("inside"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
@@ -261,7 +298,8 @@ mod tests {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::time::Duration;
|
||||
for collision in [false, true] {
|
||||
let (inside, _, ws) = roots(if collision { "fifo-collision" } else { "fifo-read" });
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, ws) = roots(directory.path());
|
||||
let path = inside.join("pipe");
|
||||
assert!(std::process::Command::new("mkfifo").arg(&path).status().unwrap().success());
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
@@ -271,19 +309,20 @@ mod tests {
|
||||
});
|
||||
let result = receiver.recv_timeout(Duration::from_secs(2));
|
||||
if result.is_err() {
|
||||
// Release the regression's blocked read before failing the test.
|
||||
// Release the regression's blocked read before failing the test
|
||||
let writer = std::fs::OpenOptions::new().write(true).custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32).open(&path).unwrap();
|
||||
drop(writer);
|
||||
}
|
||||
|
||||
worker.join().unwrap();
|
||||
std::fs::remove_dir_all(inside.parent().unwrap()).unwrap();
|
||||
assert!(result.expect("FIFO open must not wait for a writer").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_and_writes_stay_in_the_root() {
|
||||
let (inside, _, ws) = roots("valid");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, ws) = roots(directory.path());
|
||||
std::fs::write(inside.join("a.txt"), b"canary").unwrap();
|
||||
assert_eq!(ws.read("a.txt").unwrap(), b"canary");
|
||||
ws.create_dir_all("out/deep").unwrap();
|
||||
@@ -295,9 +334,39 @@ mod tests {
|
||||
assert!(ws.write("missing/c.txt", b"x").is_err(), "parent must exist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immutable_resources_compare_the_last_byte_of_a_partial_buffer() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, workspace) = roots(directory.path());
|
||||
let mut bytes = vec![17; 32 * 1024 + 1];
|
||||
workspace.write_resource("asset.bin", &bytes).unwrap();
|
||||
workspace.write_resource("asset.bin", &bytes).unwrap();
|
||||
|
||||
*bytes.last_mut().unwrap() = 42;
|
||||
let collision = workspace.write_resource("asset.bin", &bytes).unwrap_err();
|
||||
|
||||
assert!(collision.to_string().contains("collision"));
|
||||
assert_eq!(std::fs::read(inside.join("asset.bin")).unwrap().last(), Some(&17));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_busy_save_preserves_the_existing_staging_file() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, workspace) = roots(directory.path());
|
||||
let staging = inside.join(format!(".scene.sbs.{}.tmp", std::process::id()));
|
||||
std::fs::write(&staging, b"pending save").unwrap();
|
||||
|
||||
let result = workspace.write("scene.sbs", b"second save");
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read(staging).unwrap(), b"pending save");
|
||||
assert!(!inside.join("scene.sbs").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes_and_malformed_paths_are_rejected() {
|
||||
let (_, outside, ws) = roots("reject");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (_, outside, ws) = roots(directory.path());
|
||||
let abs = outside.join("x.txt").display().to_string();
|
||||
for p in ["", "/abs", "../x", "a/../../x", "a\\b", "C:/x", "a//b", "./a", "a:b", "NUL", "con.txt", "x/COM1.log", "dot.", abs.as_str()] {
|
||||
assert!(ws.read(p).is_err(), "read accepted {p:?}");
|
||||
@@ -308,7 +377,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn authorities_are_separate_and_fail_closed() {
|
||||
let (inside, _, _) = roots("separate");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, _) = roots(directory.path());
|
||||
std::fs::write(inside.join("r.txt"), b"r").unwrap();
|
||||
let ro = AuthorizedWorkspace::new(Some(&inside), None).unwrap();
|
||||
assert!(ro.read("r.txt").is_ok());
|
||||
@@ -320,7 +390,8 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn oversized_reads_are_rejected_without_allocating() {
|
||||
let (inside, _, ws) = roots("oversized");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, ws) = roots(directory.path());
|
||||
let file = std::fs::File::create(inside.join("huge.bin")).unwrap();
|
||||
file.set_len(MAX_READ_BYTES + 1).unwrap();
|
||||
let err = ws.read("huge.bin").unwrap_err().to_string();
|
||||
@@ -330,7 +401,8 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_escape_is_rejected() {
|
||||
let (inside, outside, ws) = roots("symlink");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, outside, ws) = roots(directory.path());
|
||||
std::fs::write(outside.join("secret.txt"), b"s").unwrap();
|
||||
std::os::unix::fs::symlink(&outside, inside.join("link")).unwrap();
|
||||
assert!(ws.read("link/secret.txt").is_err());
|
||||
@@ -338,10 +410,37 @@ mod tests {
|
||||
assert!(!outside.join("new.txt").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_keeps_the_resolved_destination_when_an_alias_is_retargeted() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, _, workspace) = roots(directory.path());
|
||||
std::fs::create_dir(inside.join("original")).unwrap();
|
||||
std::fs::create_dir_all(inside.join("alternate/deep")).unwrap();
|
||||
let alias = inside.join("alias");
|
||||
symlink("original", &alias).unwrap();
|
||||
let (destination, writer, save_path) = workspace.save_destination("alias/scene.sbs").unwrap();
|
||||
|
||||
std::fs::remove_file(&alias).unwrap();
|
||||
symlink("alternate/deep", &alias).unwrap();
|
||||
let parent = save_path.rsplit_once('/').map_or(String::new(), |(parent, _)| format!("{parent}/"));
|
||||
writer.create_dir_all(&format!("{parent}resources")).unwrap();
|
||||
writer.write_resource(&format!("{parent}resources/asset.bin"), b"asset").unwrap();
|
||||
writer.write(&save_path, b"source").unwrap();
|
||||
|
||||
assert_eq!(destination, inside.join("original/scene.sbs"));
|
||||
assert_eq!(std::fs::read(destination).unwrap(), b"source");
|
||||
assert_eq!(std::fs::read(inside.join("original/resources/asset.bin")).unwrap(), b"asset");
|
||||
assert_eq!(std::fs::read_dir(inside.join("alternate/deep")).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn junction_escape_is_rejected() {
|
||||
let (inside, outside, ws) = roots("junction");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let (inside, outside, ws) = roots(directory.path());
|
||||
std::fs::write(outside.join("secret.txt"), b"s").unwrap();
|
||||
let link = inside.join("junction");
|
||||
let made = std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).output();
|
||||
@@ -349,6 +448,7 @@ mod tests {
|
||||
eprintln!("skipping: cannot create a junction");
|
||||
return;
|
||||
}
|
||||
|
||||
assert!(ws.read("junction/secret.txt").is_err());
|
||||
assert!(ws.write("junction/new.txt", b"x").is_err());
|
||||
assert!(!outside.join("new.txt").exists());
|
||||
|
||||
@@ -87,19 +87,31 @@ fn both_formats_save_and_reopen_using_separate_workspace_capabilities() {
|
||||
|
||||
#[test]
|
||||
fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_root() {
|
||||
use materialcraft_engine::core::{Graph, GraphInstance, GraphPort, Value};
|
||||
use materialcraft_engine::{formats, samples};
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let dir = temporary.path().to_path_buf();
|
||||
use materialcraft_engine::core::{Graph, GraphInstance, GraphPort, Resource, ResourceBytes, Value};
|
||||
use materialcraft_engine::{formats, image};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let dir = directory.path();
|
||||
let input = dir.join("input");
|
||||
let output = dir.join("published");
|
||||
std::fs::create_dir_all(input.join("parts")).unwrap();
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
|
||||
let image = image::Image::filled(2, 2, image::Kind::Color, [0.25, 0.5, 0.75, 1.0]);
|
||||
let pixels = formats::encode(&image, "png", formats::Depth::U8, false).unwrap();
|
||||
let mut helpers = Package::new("Helpers");
|
||||
helpers.graphs.push(samples::template("pbr", "Finish", 4).unwrap());
|
||||
let helper = formats::sbs::write_sbs(&helpers).unwrap();
|
||||
std::fs::write(input.join("parts/finish.sbs"), &helper).unwrap();
|
||||
std::fs::write(dir.join("outside.sbs"), &helper).unwrap();
|
||||
helpers.resources.push(Resource::new("finish", "finish.png", ResourceBytes::new(pixels.clone())));
|
||||
let mut finish = Graph::new("Finish");
|
||||
let bitmap = finish.add_node("bitmap", [0.0; 2]);
|
||||
finish.node_mut(bitmap).unwrap().params.insert("resource".into(), Value::Text("finish".into()));
|
||||
let finish_output = finish.add_node("output", [0.0; 2]);
|
||||
finish.node_mut(finish_output).unwrap().params.insert("identifier".into(), Value::Text("basecolor".into()));
|
||||
finish.connect(bitmap, "output", finish_output, "input").unwrap();
|
||||
helpers.graphs.push(finish);
|
||||
let helper = formats::project::ProjectFiles::build(&helpers, "finish.sbs", false).unwrap();
|
||||
formats::project::write_files(&input.join("parts/finish.sbs"), &helper).unwrap();
|
||||
std::fs::write(dir.join("outside.sbs"), helper.xml().unwrap()).unwrap();
|
||||
|
||||
for (project, dependency) in [("surface.sbs", "parts/finish.sbs"), ("missing.sbs", "../outside.sbs")] {
|
||||
let mut graph = Graph::new("Oak");
|
||||
let call = graph.add_node("graph_instance", [0.; 2]);
|
||||
@@ -124,21 +136,22 @@ fn scoped_publication_resolves_linked_graphs_and_images_using_the_granted_read_r
|
||||
if project == "surface.sbs" {
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
let (pkg, entry) = formats::material::read_material(&std::fs::read(output.join("surface.sbs.mcmat")).unwrap()).unwrap();
|
||||
assert_eq!(pkg.graph(entry).unwrap().name, "Oak");
|
||||
let entry = pkg.graph(entry).unwrap();
|
||||
assert_eq!(entry.name, "Oak");
|
||||
assert_eq!(pkg.graphs.len(), 2);
|
||||
assert!(pkg.graphs.iter().any(|graph| graph.name == "Finish"));
|
||||
let calls: Vec<_> = pkg.graph(entry).unwrap().instances().collect();
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert!(calls[0].package.is_empty());
|
||||
assert!(pkg.graph_by_name(&calls[0].graph).is_some());
|
||||
let instance = entry.instances().next().unwrap();
|
||||
assert!(instance.package.is_empty());
|
||||
assert_eq!(entry.instances().count(), 1);
|
||||
assert_eq!(pkg.graph_by_name(&instance.graph).unwrap().1.name, "Finish");
|
||||
assert_eq!(pkg.resources.len(), 1);
|
||||
assert_eq!(pkg.resources[0].bytes.as_slice(), pixels);
|
||||
|
||||
// Saving under a different granted root rebases links from that actual
|
||||
// destination, not from the process working directory or a relative path.
|
||||
// Rebase links from the actual destination under the granted write root
|
||||
app.save(Some("saved.sbs")).unwrap();
|
||||
let xml = std::fs::read_to_string(output.join("saved.sbs")).unwrap();
|
||||
assert!(xml.contains("../input/parts/finish.sbs"), "{xml}");
|
||||
assert_eq!(app.session.path.as_deref(), Some("saved.sbs"));
|
||||
let workspace = AuthorizedWorkspace::new(Some(&dir), Some(&output)).unwrap();
|
||||
let workspace = AuthorizedWorkspace::new(Some(dir), Some(&output)).unwrap();
|
||||
let mut reopened = Headless::new(Session::new(Package::new("Empty")), Filesystem::Workspace(workspace));
|
||||
reopened.load("published/saved.sbs").unwrap();
|
||||
let helper_path = input.join("parts/finish.sbs").canonicalize().unwrap().to_string_lossy().into_owned();
|
||||
|
||||
@@ -24,3 +24,6 @@ thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix.workspace = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -36,8 +36,7 @@ impl ExportRequest {
|
||||
|
||||
/// Read `file.export` params, checking them against the session's package
|
||||
pub fn from_params(s: &Session, p: &J) -> Result<Self> {
|
||||
// Keep file.export's historical numeric selector coercion (including JSON 1.0)
|
||||
// while allowing the new exact SBS path selector without changing other commands.
|
||||
// Preserve historical numeric selectors alongside exact SBS paths
|
||||
let graph_index = if p.get("graph").is_some_and(J::is_number) {
|
||||
u64p(p, "graph").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(CMD, "`graph` must be a nonnegative index"))?
|
||||
} else {
|
||||
@@ -50,12 +49,14 @@ impl ExportRequest {
|
||||
return Err(bad(CMD, format!("unknown format `{format}`")));
|
||||
}
|
||||
|
||||
let depth = match u64p(p, "depth") {
|
||||
None => None,
|
||||
Some(8) => Some(Depth::U8),
|
||||
Some(16) => Some(Depth::U16),
|
||||
Some(32) => Some(Depth::F32),
|
||||
Some(depth) => return Err(bad(CMD, format!("depth must be 8, 16 or 32, not {depth}"))),
|
||||
let depth = match p.get("depth") {
|
||||
None | Some(J::Null) => None,
|
||||
Some(value) => Some(match value.as_f64() {
|
||||
Some(8.0) => Depth::U8,
|
||||
Some(16.0) => Depth::U16,
|
||||
Some(32.0) => Depth::F32,
|
||||
_ => return Err(bad(CMD, format!("depth must be 8, 16 or 32, not {value}"))),
|
||||
}),
|
||||
};
|
||||
|
||||
let identifiers = output_identifiers(graph);
|
||||
@@ -70,7 +71,7 @@ impl ExportRequest {
|
||||
format,
|
||||
pattern: strp(p, "pattern").unwrap_or("$(graph)_$(identifier)").to_string(),
|
||||
depth,
|
||||
size: export_size(p.get("size"))?,
|
||||
size: export_size(CMD, p.get("size"))?,
|
||||
outputs,
|
||||
color_spaces: color_spaces(p.get("colorSpaces"), &identifiers, &graph.name)?,
|
||||
})
|
||||
@@ -127,7 +128,7 @@ fn known_output<'a>(identifier: &'a str, identifiers: &[String], graph: &str) ->
|
||||
}
|
||||
|
||||
/// `size`: the larger side in pixels (0 = the graph's size) or `[width, height]`
|
||||
pub(crate) fn export_size(value: Option<&J>) -> Result<Option<ExportSize>> {
|
||||
pub(crate) fn export_size(command: &str, value: Option<&J>) -> Result<Option<ExportSize>> {
|
||||
let pixels = |value: &J| value.as_u64().or_else(|| value.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64));
|
||||
let clamp = |pixels: u64| pixels.min(u64::from(u32::MAX)) as u32;
|
||||
|
||||
@@ -136,14 +137,14 @@ pub(crate) fn export_size(value: Option<&J>) -> Result<Option<ExportSize>> {
|
||||
Some(J::Array(sides)) => match sides.as_slice() {
|
||||
[width, height] => match (pixels(width), pixels(height)) {
|
||||
(Some(width), Some(height)) => Ok(Some(ExportSize::Exact([clamp(width), clamp(height)]))),
|
||||
_ => Err(bad(CMD, "`size` [width, height] takes two pixel counts")),
|
||||
_ => Err(bad(command, "`size` [width, height] takes two pixel counts")),
|
||||
},
|
||||
_ => Err(bad(CMD, "`size` [width, height] takes two pixel counts")),
|
||||
_ => Err(bad(command, "`size` [width, height] takes two pixel counts")),
|
||||
},
|
||||
Some(value) => match pixels(value) {
|
||||
Some(0) => Ok(None),
|
||||
Some(side) => Ok(Some(ExportSize::LargerSide(clamp(side)))),
|
||||
None => Err(bad(CMD, "`size` is a pixel count or [width, height]")),
|
||||
None => Err(bad(command, "`size` is a pixel count or [width, height]")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,8 +344,8 @@ pub(crate) fn encode_outputs(graph: &materialcraft_core::Graph, cooked: &materia
|
||||
let node = graph.node(id)?;
|
||||
let output_format = if node.base.format == materialcraft_core::OutputFormat::Inherit { graph.format } else { node.base.format };
|
||||
let depth = request.depth.unwrap_or_else(|| Depth::from_format(output_format));
|
||||
// Grayscale floating-point exports historically stored scene-linear samples, even
|
||||
// for color usages. Keep that default; an explicit color-space choice still wins.
|
||||
|
||||
// Keep grayscale float exports scene-linear unless the caller picks a color space
|
||||
let srgb = request.color_space(&identifier, usage).encodes_srgb()
|
||||
&& !(image.kind() == craft_texture::Kind::Gray
|
||||
&& matches!(request.format.as_str(), "exr" | "hdr")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
use materialcraft_core::{MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value};
|
||||
use materialcraft_core::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_selection, i64p, ids_param, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
@@ -235,16 +235,19 @@ fn preset_apply(s: &mut Session, p: &J) -> Result<J> {
|
||||
s.edit("Apply preset", |s| {
|
||||
let g = s.graph_mut()?;
|
||||
let preset = g.presets.iter().find(|x| x.name == name).cloned().ok_or_else(|| bad("graph.preset.apply", format!("no preset `{name}`")))?;
|
||||
for (k, v) in preset.values {
|
||||
// Only inputs that still exist, with their current type
|
||||
if g.exposed.iter().any(|e| e.id == k && e.default.type_name() == v.type_name()) {
|
||||
g.inputs.insert(k, v);
|
||||
for (identifier, value) in preset.values {
|
||||
if preset_value_matches(g, &identifier, &value) {
|
||||
g.inputs.insert(identifier, value);
|
||||
}
|
||||
}
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn preset_value_matches(graph: &Graph, identifier: &str, value: &Value) -> bool {
|
||||
graph.exposed.iter().any(|input| input.id == identifier && input.default.type_name() == value.type_name())
|
||||
}
|
||||
|
||||
fn preset_delete(s: &mut Session, p: &J) -> Result<J> {
|
||||
let name = preset_name(p, "graph.preset.delete")?;
|
||||
s.edit("Delete preset", |s| {
|
||||
|
||||
@@ -60,6 +60,7 @@ pub(crate) fn load_scoped(package: &mut Package, read: &dyn Fn(&str) -> Option<V
|
||||
if path.starts_with("sbs://") {
|
||||
return load_file(path);
|
||||
}
|
||||
|
||||
let bytes = read(path).ok_or_else(|| format!("missing or inaccessible dependency `{path}`"))?;
|
||||
let assets = |reference: &str| read(&document_path::resolve(path, reference));
|
||||
crate::file_cmds::read_package_bytes(&bytes, path, &assets).map_err(|error| error.to_string())
|
||||
@@ -78,11 +79,14 @@ fn load_file(path: &str) -> Result<materialcraft_formats::sbs::SbsRead, String>
|
||||
crate::file_cmds::read_package_bytes(&bytes, path, &crate::file_cmds::linked_files(path)).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
const MAX_DEPENDENCY_READS: usize = 4096;
|
||||
|
||||
fn resolve(package: &mut Package, mut pending: Vec<String>, read: &dyn Fn(&str) -> Result<materialcraft_formats::sbs::SbsRead, String>) -> Vec<String> {
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut warnings = Vec::new();
|
||||
let mut reads = 0;
|
||||
let mut read_attempts = 0;
|
||||
while let Some(path) = pending.pop() {
|
||||
if !visited.insert(path.clone()) {
|
||||
continue;
|
||||
@@ -93,13 +97,13 @@ fn resolve(package: &mut Package, mut pending: Vec<String>, read: &dyn Fn(&str)
|
||||
continue;
|
||||
}
|
||||
|
||||
// Cached snapshots need traversal, but must not consume the new-read budget.
|
||||
// Count failed attempts too; visited still prevents repeated reads and cycles.
|
||||
if reads >= 4096 {
|
||||
warnings.push("linked material exceeds the package dependency limit".into());
|
||||
// Cached snapshots only need traversal, while failed reads still spend the allowance
|
||||
if read_attempts == MAX_DEPENDENCY_READS {
|
||||
warnings.push("linked material exceeds the package dependency read limit".into());
|
||||
break;
|
||||
}
|
||||
reads += 1;
|
||||
|
||||
read_attempts += 1;
|
||||
match read(&path) {
|
||||
Ok(read) => {
|
||||
warnings.extend(read.warnings);
|
||||
@@ -127,7 +131,7 @@ mod tests {
|
||||
for cached_first in [true, false] {
|
||||
let mut package = Package::new("root");
|
||||
let mut pending = vec!["new".to_string()];
|
||||
for i in 0..4096 {
|
||||
for i in 0..MAX_DEPENDENCY_READS {
|
||||
let name = format!("cached{i}");
|
||||
package.dependencies.insert(name.clone(), Arc::new(Package::new(&name)));
|
||||
pending.push(name);
|
||||
@@ -150,12 +154,12 @@ mod tests {
|
||||
#[test]
|
||||
fn failed_new_reads_still_spend_the_budget_and_duplicates_do_not() {
|
||||
let calls = Cell::new(0);
|
||||
let pending = (0..4097).flat_map(|i| [format!("missing{i}"), format!("missing{i}")]).collect();
|
||||
let pending = (0..=MAX_DEPENDENCY_READS).flat_map(|i| [format!("missing{i}"), format!("missing{i}")]).collect();
|
||||
let warnings = resolve(&mut Package::new("root"), pending, &|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err("missing".into())
|
||||
});
|
||||
assert_eq!(calls.get(), 4096);
|
||||
assert!(warnings.last().unwrap().contains("dependency limit"));
|
||||
assert_eq!(calls.get(), MAX_DEPENDENCY_READS);
|
||||
assert!(warnings.last().unwrap().contains("dependency read limit"));
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,8 @@ pub(crate) fn read_regular(path: &std::path::Path) -> std::io::Result<Vec<u8>> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
// A named pipe must reach the regular-file check without waiting for a writer.
|
||||
|
||||
// A named pipe must reach the regular-file check without waiting for a writer
|
||||
open.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32);
|
||||
}
|
||||
let file = open.open(path)?;
|
||||
@@ -22,13 +23,16 @@ pub(crate) fn read_regular(path: &std::path::Path) -> std::io::Result<Vec<u8>> {
|
||||
if !metadata.is_file() || metadata.len() > MAX_LINKED_RESOURCE_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
let mut data = Vec::new();
|
||||
file.take(MAX_LINKED_RESOURCE_BYTES + 1).read_to_end(&mut data)?;
|
||||
if data.len() as u64 > MAX_LINKED_RESOURCE_BYTES {
|
||||
return Err(invalid());
|
||||
}
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Read resource paths relative to an SBS package, including portable library aliases.
|
||||
pub fn reader(path: &str) -> impl Fn(&str) -> Option<Vec<u8>> + use<> {
|
||||
let owner = path.to_string();
|
||||
|
||||
@@ -68,10 +68,12 @@ 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, 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())));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -88,45 +90,48 @@ pub fn cook(s: &Session, p: &J, read: impl Fn(&str) -> Result<Vec<u8>>) -> Resul
|
||||
|
||||
/// Encode every file before the caller writes to its destination. Paths in the report are relative.
|
||||
pub fn export(s: &Session, p: &J, read: impl Fn(&str) -> Result<Vec<u8>>) -> Result<(Vec<Exported>, J)> {
|
||||
let option = |key| p.get(key).filter(|value| !value.is_null());
|
||||
let request = ExportRequest::from_params(s, p)?;
|
||||
let has = |key| p.get(key).is_some_and(|value| !value.is_null());
|
||||
if has("profile") {
|
||||
if has("format") || has("pattern") {
|
||||
return Err(bad("file.export", "named profiles choose their own format and filenames; omit format and pattern"));
|
||||
}
|
||||
} else if has("normalFormat") || has("displacementScale") {
|
||||
return Err(bad("file.export", "normalFormat and displacementScale require an explicit export profile"));
|
||||
}
|
||||
|
||||
let graph = s.pkg.graph(request.graph)?;
|
||||
let options = MaterialOptions::from_params(graph, p, read)?;
|
||||
let selected = request.outputs.as_deref();
|
||||
let materialx = match p.get("profile").filter(|value| !value.is_null()) {
|
||||
let materialx = match option("profile") {
|
||||
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 => {
|
||||
if option("normalFormat").is_some() || option("displacementScale").is_some() {
|
||||
return Err(bad("file.export", "normalFormat and displacementScale require an explicit export profile"));
|
||||
}
|
||||
|
||||
let options = MaterialOptions::from_params(graph, p, read)?;
|
||||
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()) {
|
||||
if option("format").is_some() || option("pattern").is_some() {
|
||||
return Err(bad("file.export", "named profiles choose their own format and filenames; omit format and pattern"));
|
||||
}
|
||||
|
||||
let scale = match option("displacementScale") {
|
||||
Some(_) if !materialx => return Err(bad("file.export", "`displacementScale` requires the materialx profile")),
|
||||
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()) {
|
||||
let normal_y_down = match option("normalFormat") {
|
||||
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 options = MaterialOptions::from_params(graph, p, read)?;
|
||||
let cooked = options.cook(s, request.graph, selected, None)?;
|
||||
let (files, mut report) = encode_maps(graph, &cooked, &request, materialx, scale, normal_y_down)?;
|
||||
// Use the graph already selected by file.export, including its legacy numeric coercion.
|
||||
|
||||
// Report the same graph selected by the legacy numeric coercion
|
||||
let mut interface = info(s, &json!({"graph": request.graph}))?;
|
||||
if let Some(params) = interface["parameters"].as_array_mut() {
|
||||
for parameter in params {
|
||||
@@ -197,6 +202,7 @@ fn encode_maps(
|
||||
let mut shader_inputs = BTreeSet::new();
|
||||
for (id, usage, identifier, image) in outputs(graph, cooked) {
|
||||
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);
|
||||
@@ -222,6 +228,7 @@ fn encode_maps(
|
||||
if float && request.color_spaces.get(&identifier).is_some_and(|space| space.encodes_srgb()) {
|
||||
return Err(bad("file.export", format!("EXR output `{identifier}` requires linear values; omit the sRGB override or select raw or linear")));
|
||||
}
|
||||
|
||||
let (ext, depth) = if float {
|
||||
("exr", Depth::F32)
|
||||
} else {
|
||||
@@ -236,7 +243,7 @@ fn encode_maps(
|
||||
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
|
||||
// Keep every texture referenced by the last complete document until the new write succeeds
|
||||
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();
|
||||
|
||||
@@ -45,10 +45,17 @@ pub fn material_bytes(session: &Session, graph: usize) -> Result<Vec<u8>> {
|
||||
Ok(materialcraft_formats::material::write_material(&session.pkg, graph)?)
|
||||
}
|
||||
|
||||
/// Publish with an additional budget for the combined uncompressed source assets.
|
||||
pub fn material_bytes_with_resource_limit(session: &Session, graph: usize, maximum_resource_bytes: u64) -> Result<Vec<u8>> {
|
||||
crate::material_bake::check_publish(session, graph)?;
|
||||
Ok(materialcraft_formats::material::write_material_with_resource_limit(&session.pkg, graph, maximum_resource_bytes)?)
|
||||
}
|
||||
|
||||
pub fn publish_graph(s: &Session, p: &J) -> Result<usize> {
|
||||
if ["size", "values", "inputs", "preset"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad("file.exportMaterial", "pass size, values, preset and image inputs when cooking or exporting outputs"));
|
||||
}
|
||||
|
||||
crate::graph_cmds::graph_index(s, p)
|
||||
}
|
||||
|
||||
|
||||
@@ -87,6 +87,7 @@ fn published_entry_cooks_independently_with_values_sizes_and_image_inputs() {
|
||||
let (original, _) = bake(&source);
|
||||
let (packed, report) = bake(&opened);
|
||||
assert_eq!(original.len(), 4);
|
||||
assert_eq!(packed.len(), original.len());
|
||||
assert_eq!(report["maps"][0]["size"], json!([size, size / 2]));
|
||||
for (a, b) in original.iter().zip(&packed) {
|
||||
assert_eq!(a.file, b.file);
|
||||
@@ -107,10 +108,8 @@ fn published_entry_cooks_independently_with_values_sizes_and_image_inputs() {
|
||||
assert!(
|
||||
material_bake::cook(&opened, &json!({"values":{"missing":0}}), |path| Err(crate::EngineError::Other(format!("unexpected file read: {path}")))).is_err()
|
||||
);
|
||||
assert!(
|
||||
material_bake::cook(&opened, &json!({"inputs":{"missing":"x"}}), |path| Err(crate::EngineError::Other(format!("unexpected file read: {path}"))))
|
||||
.is_err()
|
||||
);
|
||||
let error = material_bake::cook(&opened, &json!({"inputs":{"missing":"x"}}), |path| panic!("unexpected file read: {path}")).unwrap_err();
|
||||
assert!(error.to_string().contains("unknown image input `missing`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -138,7 +137,8 @@ fn preset_values_apply_before_explicit_overrides() {
|
||||
|
||||
#[test]
|
||||
fn publishing_sbs_and_project_archives_survives_removing_the_entire_source_tree() {
|
||||
let dir = std::env::temp_dir().join(format!("materialcraft-source-closure-{}", std::process::id()));
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let dir = directory.path();
|
||||
let authored = dir.join("authored");
|
||||
std::fs::create_dir_all(&authored).unwrap();
|
||||
let source = fixture();
|
||||
@@ -149,7 +149,8 @@ fn publishing_sbs_and_project_archives_survives_removing_the_entire_source_tree(
|
||||
}
|
||||
for ext in ["sbs", "mcraft"] {
|
||||
let path = authored.join(format!("studio.{ext}"));
|
||||
// Save the independent project beside its library packages and their original bitmaps.
|
||||
|
||||
// Save the independent project beside its library packages and their original bitmaps
|
||||
let files = materialcraft_formats::project::ProjectFiles::build(&source.pkg, &format!("studio.{ext}"), ext == "mcraft").unwrap();
|
||||
if ext == "mcraft" {
|
||||
std::fs::write(&path, files.zip().unwrap()).unwrap();
|
||||
@@ -175,7 +176,6 @@ fn publishing_sbs_and_project_archives_survives_removing_the_entire_source_tree(
|
||||
};
|
||||
assert_eq!(bake(&source), bake(&viewer));
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -337,6 +337,35 @@ fn an_openpbr_scalar_rejects_an_unrepresentable_srgb_override() {
|
||||
assert!(result.err().is_some_and(|error| error.to_string().contains("linear")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_srgb_is_rejected_when_the_profile_requires_float_textures() {
|
||||
let session = export_fixture("uniform", &[], "baseColor");
|
||||
let automatic = json!({"profile":"materialx","depth":32});
|
||||
let explicit_srgb = json!({"profile":"materialx","depth":32,"colorSpaces":{"result":"srgb"}});
|
||||
|
||||
let (_, report) = material_bake::export(&session, &automatic, material_bake::read_input).unwrap();
|
||||
let error = material_bake::export(&session, &explicit_srgb, material_bake::read_input).err().expect("an explicit sRGB override cannot produce linear EXR");
|
||||
|
||||
assert_eq!(report["maps"][0]["colorSpace"], "linear");
|
||||
assert!(report["maps"][0]["file"].as_str().unwrap().ends_with(".exr"));
|
||||
assert!(error.to_string().contains("requires linear values"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_controls_fail_when_the_requested_export_cannot_apply_them() {
|
||||
let session = export_fixture("uniform", &[], "baseColor");
|
||||
|
||||
for (params, option) in [
|
||||
(json!({"profile":"maps","displacementScale":2}), "displacementScale"),
|
||||
(json!({"profile":"maps","depth":8.4}), "depth"),
|
||||
(json!({"profile":"maps","depth":"mistyped"}), "depth"),
|
||||
] {
|
||||
let error = material_bake::export(&session, ¶ms, material_bake::read_input).err().expect("an unused option must be rejected");
|
||||
|
||||
assert!(error.to_string().contains(option), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_grayscale_float_exports_keep_linear_defaults_and_explicit_overrides() {
|
||||
let session = export_fixture("uniform", &[("color", Value::Color([0.25; 4])), ("color_mode", Value::Bool(false))], "baseColor");
|
||||
@@ -388,7 +417,7 @@ fn published_disabled_and_typed_instance_cooks_match_source() {
|
||||
let bytes = materialcraft_formats::material::write_material(&package, 0).unwrap();
|
||||
let (opened, entry) = materialcraft_formats::material::read_material(&bytes).unwrap();
|
||||
let cook = |pkg: Package, entry| {
|
||||
// Cook the decoded package directly: Session::new refreshes interfaces and could mask a serialization defect.
|
||||
// Cook without Session::new because it can reconstruct a missing interface
|
||||
let options = materialcraft_eval::Options::new(&|_| None);
|
||||
let cache = std::sync::Mutex::new(materialcraft_eval::Cache::default());
|
||||
let cooked = materialcraft_eval::cook(&pkg, entry, &options, &cache);
|
||||
@@ -431,7 +460,7 @@ fn material_options_size_errors_name_the_material_command() {
|
||||
let error =
|
||||
MaterialOptions::from_params(session.graph().unwrap(), ¶meters, |_| Err(crate::EngineError::Other("unexpected image read".into()))).unwrap_err();
|
||||
assert!(matches!(error, crate::EngineError::BadParams { cmd, msg } if cmd == "material.cook" && msg.contains("size")));
|
||||
let error = crate::export_request::export_size(parameters.get("size")).unwrap_err();
|
||||
let error = crate::export_request::export_size("file.export", parameters.get("size")).unwrap_err();
|
||||
assert!(matches!(error, crate::EngineError::BadParams { cmd, msg } if cmd == "file.export" && msg.contains("size")));
|
||||
}
|
||||
|
||||
|
||||
@@ -18,21 +18,16 @@ pub struct MaterialOptions {
|
||||
impl MaterialOptions {
|
||||
pub fn from_params(graph: &Graph, p: &J, read: impl Fn(&str) -> Result<Vec<u8>>) -> Result<Self> {
|
||||
let invalid = |msg| bad("material.cook", msg);
|
||||
let size = crate::export_request::export_size(p.get("size")).map_err(|error| match error {
|
||||
crate::EngineError::BadParams { msg, .. } => invalid(msg),
|
||||
other => other,
|
||||
})?;
|
||||
let mut options = Self { size, ..Default::default() };
|
||||
let mut options = Self { size: crate::export_request::export_size("material.cook", 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}`")))?;
|
||||
// Match preset.apply: stale identifiers and changed parameter types are ignored.
|
||||
options.values.extend(
|
||||
preset
|
||||
.values
|
||||
.iter()
|
||||
.filter(|(id, value)| graph.exposed.iter().any(|parameter| parameter.id == **id && parameter.default.type_name() == value.type_name()))
|
||||
.filter(|(id, value)| crate::graph_cmds::preset_value_matches(graph, id, value))
|
||||
.map(|(id, value)| (id.clone(), value.clone())),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{Cache, Cooked, Options, now_ms};
|
||||
use crate::{node_execution::cook_node, prepared_graph::PreparedGraph};
|
||||
use craft_texture::Image;
|
||||
use materialcraft_core::{Package, Value};
|
||||
use materialcraft_core::{Graph, Node, Package, Value};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{Mutex, atomic::Ordering},
|
||||
@@ -12,23 +12,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
|
||||
let mut cooked = Cooked::default();
|
||||
let Some(graph) = package.graphs.get(graph_index) else { return cooked };
|
||||
|
||||
// Input nodes show their bound preview images; the caller's images win
|
||||
let bound;
|
||||
let options = if !graph.input_images.is_empty() {
|
||||
let mut inputs: BTreeMap<String, Image> = graph
|
||||
.input_images
|
||||
.iter()
|
||||
.filter_map(|(id, resource)| {
|
||||
Some((id.clone(), (options.resource)(&craft_texture::resource_key(resource, graph.input_images_linear.contains(id)))?))
|
||||
})
|
||||
.collect();
|
||||
inputs.extend(options.inputs.iter().map(|(name, value)| (name.clone(), value.clone())));
|
||||
bound = Options { only: options.only.clone(), inputs, overrides: options.overrides.clone(), graph_stack: options.graph_stack.clone(), ..*options };
|
||||
&bound
|
||||
} else {
|
||||
options
|
||||
};
|
||||
|
||||
let mut previews = BTreeMap::new();
|
||||
let prepared = PreparedGraph::new(package, graph, options);
|
||||
|
||||
// Exposed parameter values: the graph's own, then the caller's overrides
|
||||
@@ -50,9 +34,28 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
|
||||
|
||||
let Some(node) = prepared.index.node(id) else { continue };
|
||||
|
||||
let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache);
|
||||
let input = input_image(graph, node, options, &mut previews);
|
||||
let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, input, cache);
|
||||
cooked.nodes.insert(id, result);
|
||||
}
|
||||
|
||||
cooked.ms = (now_ms() - started_ms) as f32;
|
||||
cooked
|
||||
}
|
||||
|
||||
fn input_image<'a>(graph: &Graph, node: &Node, options: &'a Options<'_>, previews: &'a mut BTreeMap<String, Option<Image>>) -> Option<&'a Image> {
|
||||
if !node.def.starts_with("input_") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let identifier = crate::identifier(node);
|
||||
if let Some(image) = options.inputs.get(&identifier) {
|
||||
return Some(image);
|
||||
}
|
||||
|
||||
let resource = graph.input_images.get(&identifier)?;
|
||||
let linear = graph.input_images_linear.contains(&identifier);
|
||||
|
||||
// Nodes sharing an input also share its first lookup, including a missing preview
|
||||
previews.entry(identifier).or_insert_with(|| (options.resource)(&craft_texture::resource_key(resource, linear))).as_ref()
|
||||
}
|
||||
@@ -32,6 +32,7 @@ pub(crate) fn cook_node(
|
||||
cooked: &Cooked,
|
||||
graph_variables: &BTreeMap<String, Value>,
|
||||
options: &Options,
|
||||
input_image: Option<&Image>,
|
||||
cache: &Mutex<Cache>,
|
||||
) -> NodeResult {
|
||||
let (input_ports, output_ports) = prepared.ports(node.id);
|
||||
@@ -129,8 +130,6 @@ pub(crate) fn cook_node(
|
||||
|
||||
let tile = base.tiling[0] && base.tiling[1];
|
||||
|
||||
// Input nodes read the caller's image for their identifier
|
||||
let input_image = node.def.starts_with("input_").then(|| options.inputs.get(&identifier(node))).flatten();
|
||||
let resource_hash = match parameters.get("resource") {
|
||||
Some(Value::Text(name)) => package.resource(name).map_or(0, |r| r.bytes.content_hash()),
|
||||
_ => 0,
|
||||
|
||||
@@ -47,6 +47,111 @@ fn cooks_and_caches() {
|
||||
assert_eq!(outputs(&p.graphs[0], &c).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_overrides_skip_bound_preview_decodes_and_release_buffers() {
|
||||
let mut graph = Graph::new("Bound inputs");
|
||||
graph.size = [4; 2];
|
||||
let identifiers = ["height", "curvature", "thickness"];
|
||||
let mut outputs = Vec::new();
|
||||
for identifier in identifiers {
|
||||
let input = graph.add_node("input_grayscale", [0.0; 2]);
|
||||
graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(identifier.into()));
|
||||
let output = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(input, "output", output, "input").unwrap();
|
||||
graph.input_images.insert(identifier.into(), format!("preview_{identifier}"));
|
||||
outputs.push(output);
|
||||
}
|
||||
let mut package = Package::new("Bound inputs");
|
||||
package.graphs.push(graph);
|
||||
let preview_buffers = Mutex::new(Vec::new());
|
||||
let read_preview = |_: &str| {
|
||||
let image = Image::filled(1024, 1024, Kind::Gray, [0.25; 4]);
|
||||
preview_buffers.lock().unwrap().push(std::sync::Arc::downgrade(image.shared_data()));
|
||||
Some(image)
|
||||
};
|
||||
let cache = Mutex::new(Cache::new(0));
|
||||
|
||||
for value in [0.125, 0.5, 0.875] {
|
||||
let mut options = Options::new(&read_preview);
|
||||
let mut supplied_buffers = Vec::new();
|
||||
for identifier in &identifiers[..2] {
|
||||
let image = Image::filled(16, 16, Kind::Gray, [value; 4]);
|
||||
supplied_buffers.push(std::sync::Arc::downgrade(image.shared_data()));
|
||||
options.inputs.insert((*identifier).into(), image);
|
||||
}
|
||||
|
||||
let result = cook(&package, 0, &options, &cache);
|
||||
for (output, expected) in outputs.iter().zip([value, value, 0.25]) {
|
||||
let image = result.image(*output, 0).unwrap();
|
||||
assert!((image.mean()[0] - expected).abs() < 0.005);
|
||||
}
|
||||
drop(result);
|
||||
drop(options);
|
||||
|
||||
assert!(supplied_buffers.iter().all(|buffer| buffer.upgrade().is_none()));
|
||||
}
|
||||
|
||||
let previews = preview_buffers.into_inner().unwrap();
|
||||
assert!(previews.iter().all(|buffer| buffer.upgrade().is_none()));
|
||||
eprintln!("Decoded preview planes: {} ({} bytes of grayscale payload)", previews.len(), previews.len() * 1024 * 1024 * size_of::<f32>());
|
||||
assert_eq!(previews.len(), 3, "one fallback preview decode per cook");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_outputs_decode_only_reachable_input_previews() {
|
||||
let mut graph = Graph::new("Preview selection");
|
||||
graph.size = [4; 2];
|
||||
let mut outputs = Vec::new();
|
||||
for identifier in ["height", "roughness", "normal", "height"] {
|
||||
let input = graph.add_node("input_grayscale", [0.0; 2]);
|
||||
graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(identifier.into()));
|
||||
graph.input_images.insert(identifier.into(), identifier.into());
|
||||
let output = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(input, "output", output, "input").unwrap();
|
||||
outputs.push(output);
|
||||
}
|
||||
|
||||
let mut package = Package::new("Preview selection");
|
||||
package.graphs.push(graph);
|
||||
let mut counts = Vec::new();
|
||||
for (selected, expected) in [(vec![outputs[0], outputs[3]], 0.25), (vec![outputs[1]], 0.5), (vec![outputs[2]], 0.75)] {
|
||||
let buffers = Mutex::new(Vec::new());
|
||||
let peak_planes = std::sync::atomic::AtomicUsize::new(0);
|
||||
let read_preview = |name: &str| {
|
||||
let value = match craft_texture::split_resource_key(name).0 {
|
||||
"height" => 0.25,
|
||||
"roughness" => 0.5,
|
||||
"normal" => 0.75,
|
||||
other => panic!("unexpected preview {other}"),
|
||||
};
|
||||
let image = Image::filled(1024, 1024, Kind::Gray, [value; 4]);
|
||||
let mut buffers = buffers.lock().unwrap();
|
||||
buffers.push(std::sync::Arc::downgrade(image.shared_data()));
|
||||
peak_planes.fetch_max(buffers.iter().filter(|plane| plane.strong_count() > 0).count(), std::sync::atomic::Ordering::Relaxed);
|
||||
Some(image)
|
||||
};
|
||||
let mut options = Options::new(&read_preview);
|
||||
options.only = Some(selected.clone());
|
||||
let cache = Mutex::new(Cache::new(0));
|
||||
|
||||
let result = cook(&package, 0, &options, &cache);
|
||||
|
||||
for output in &outputs {
|
||||
if selected.contains(output) {
|
||||
assert!((result.image(*output, 0).unwrap().mean()[0] - expected).abs() < 0.005);
|
||||
} else {
|
||||
assert!(result.image(*output, 0).is_none());
|
||||
}
|
||||
}
|
||||
let buffers = buffers.into_inner().unwrap();
|
||||
assert!(buffers.iter().all(|buffer| buffer.upgrade().is_none()));
|
||||
counts.push((buffers.len(), peak_planes.into_inner()));
|
||||
}
|
||||
|
||||
eprintln!("Decoded and peak live 1024-square grayscale previews per selection: {counts:?}");
|
||||
assert_eq!(counts, [(1, 1); 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_tiling_variable_tracks_both_axes_and_invalidates_cached_values() {
|
||||
let mut function = materialcraft_core::FunctionGraph::default();
|
||||
|
||||
@@ -64,8 +64,9 @@ pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let encode_channel = |v: f32| if srgb { linear_to_srgb(v) } else { v };
|
||||
let (w, h) = (image.width(), image.height());
|
||||
// Grayscale files are imported as raw data for compatibility. Color-valued
|
||||
// grayscale exports need RGB storage so the decoder applies their sRGB transfer.
|
||||
|
||||
// Store sRGB grayscale colors as RGB so readers apply the transfer
|
||||
// Preserve single-channel storage for raw grayscale data
|
||||
let source_color = image.kind() == Kind::Color;
|
||||
let color = source_color || srgb;
|
||||
let pixel = |i: usize| -> [f32; 4] {
|
||||
@@ -146,7 +147,7 @@ mod transfer_tests {
|
||||
assert_eq!(decoded.kind(), if srgb { Kind::Color } else { Kind::Gray });
|
||||
assert!((decoded.data()[0] - 0.25).abs() < 0.003);
|
||||
if !srgb {
|
||||
// Existing grayscale data imports stay linear even at the default setting.
|
||||
// Existing grayscale data imports stay linear even at the default setting
|
||||
assert!((decode(&bytes, false).unwrap().data()[0] - 0.25).abs() < 0.003);
|
||||
}
|
||||
let stored = decode(&bytes, true).unwrap();
|
||||
|
||||
@@ -10,7 +10,19 @@ pub fn is_material(bytes: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
pub fn write_material(package: &Package, entry: usize) -> Result<Vec<u8>> {
|
||||
write_material_with_resource_limit(package, entry, craft_mcmat::Limits::default().max_total_bytes)
|
||||
}
|
||||
|
||||
/// Limit the aggregate source assets before generating the output archive.
|
||||
pub fn write_material_with_resource_limit(package: &Package, entry: usize, maximum_resource_bytes: u64) -> Result<Vec<u8>> {
|
||||
let snapshot = super::snapshot(package, entry)?;
|
||||
let mut remaining = maximum_resource_bytes;
|
||||
for resource in &snapshot.resources {
|
||||
remaining = remaining.checked_sub(resource.bytes.len() as u64).ok_or_else(|| {
|
||||
FormatError::BadPackage(format!("material source assets exceed the {maximum_resource_bytes}-byte limit; reduce source asset sizes"))
|
||||
})?;
|
||||
}
|
||||
|
||||
let files = ProjectFiles::build(&snapshot, craft_mcmat::SOURCE_ENTRY, false)?;
|
||||
let resources = files.files.iter().filter(|(name, _)| **name != files.entry).map(|(name, bytes)| (name.as_str(), bytes.as_slice()));
|
||||
craft_mcmat::write(files.xml()?, resources).map_err(|err| FormatError::BadPackage(err.to_string()))
|
||||
@@ -38,18 +50,30 @@ pub fn read_material(bytes: &[u8]) -> Result<(Package, usize)> {
|
||||
Ok((pkg, entry))
|
||||
}
|
||||
|
||||
// Linked aliases and inline SBS assets must share the same decoded-byte budget.
|
||||
// Linked aliases and inline SBS assets share one decoded-byte budget
|
||||
fn read_source(material: &craft_mcmat::Material, budget: u64) -> Result<sbs::SbsRead> {
|
||||
let remaining = Cell::new(budget);
|
||||
sbs::SbsDocument::parse(&material.source)?.read_with_resource_budget(
|
||||
let over_budget = Cell::new(false);
|
||||
let mut read = sbs::SbsDocument::parse(&material.source)?.read_with_resource_budget(
|
||||
craft_mcmat::SOURCE_ENTRY,
|
||||
&|name| {
|
||||
let data = material.resources.get(name)?;
|
||||
remaining.set(remaining.get().checked_sub(data.len() as u64)?);
|
||||
let Some(bytes_left) = remaining.get().checked_sub(data.len() as u64) else {
|
||||
over_budget.set(true);
|
||||
return None;
|
||||
};
|
||||
|
||||
remaining.set(bytes_left);
|
||||
Some(data.clone())
|
||||
},
|
||||
&remaining,
|
||||
)
|
||||
)?;
|
||||
|
||||
if over_budget.get() {
|
||||
read.warnings.insert(0, "archive member exceeds the remaining material resource budget".into());
|
||||
}
|
||||
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
/// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear)
|
||||
@@ -74,6 +98,7 @@ pub fn srgb_usage(usage: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use base64::Engine as _;
|
||||
use materialcraft_core::{Graph, Resource, ResourceBytes, Value};
|
||||
use std::io::Write;
|
||||
|
||||
fn inline(bytes: &[u8]) -> String {
|
||||
@@ -93,6 +118,30 @@ mod tests {
|
||||
craft_mcmat::Material::open(&bytes, craft_mcmat::Limits::default()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publication_checks_the_combined_bytes_of_distinct_source_assets() {
|
||||
const ASSET_BYTES: usize = 4096;
|
||||
let mut package = Package::new("Assets");
|
||||
let mut graph = Graph::new("Root");
|
||||
for (index, name) in ["a", "b"].into_iter().enumerate() {
|
||||
package.resources.push(Resource::new(name, format!("{name}.bin"), ResourceBytes::new(vec![index as u8; ASSET_BYTES])));
|
||||
let bitmap = graph.add_node("bitmap", [0.0; 2]);
|
||||
graph.node_mut(bitmap).unwrap().params.insert("resource".into(), Value::Text(name.into()));
|
||||
let output = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(bitmap, "output", output, "input").unwrap();
|
||||
}
|
||||
package.graphs.push(graph);
|
||||
let total = (2 * ASSET_BYTES) as u64;
|
||||
|
||||
let error = write_material_with_resource_limit(&package, 0, total - 1).unwrap_err();
|
||||
let archive = write_material_with_resource_limit(&package, 0, total).unwrap();
|
||||
let (reopened, _) = read_material(&archive).unwrap();
|
||||
|
||||
assert!(error.to_string().contains("material source assets exceed"));
|
||||
assert!(archive.len() < ASSET_BYTES);
|
||||
assert_eq!(reopened.resources.iter().map(|resource| resource.bytes.len()).sum::<usize>(), total as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_budget_failure_does_not_substitute_a_different_linked_asset() {
|
||||
let content = inline(b"four").replace("</resource>", "<filepath v=\"resources/member.png\"/></resource>");
|
||||
@@ -119,6 +168,7 @@ mod tests {
|
||||
"<resource><identifier v=\"inline\"/><filepath v=\"resources/member.png\"/><source><binembedded><strdata v=\"{encoded}\"/></binembedded></source></resource>"
|
||||
);
|
||||
let read = read_source(&make_material(&content), 3).unwrap();
|
||||
|
||||
assert!(read.warnings.is_empty());
|
||||
assert_eq!(read.pkg.resources[0].bytes.as_slice(), b"abc");
|
||||
}
|
||||
@@ -133,6 +183,7 @@ mod tests {
|
||||
"<resource><identifier v=\"inline\"/><filepath v=\"resources/member.png\"/><source><binembedded><strdata v=\"{encoded}\"/></binembedded></source></resource>"
|
||||
);
|
||||
let read = read_source(&make_material(&content), 3).unwrap();
|
||||
|
||||
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
|
||||
assert_eq!(read.pkg.resources[0].bytes.as_slice(), b"abc");
|
||||
}
|
||||
@@ -141,6 +192,7 @@ mod tests {
|
||||
fn repeated_oversized_inline_probes_exhaust_document_work() {
|
||||
let content = format!("{}{}{}", inline(b"four"), inline(b"four"), inline(b""));
|
||||
let read = read_source(&make_material(&content), 3).unwrap();
|
||||
|
||||
assert!(read.pkg.resources.is_empty());
|
||||
assert!(read.warnings.iter().any(|warning| warning.contains("inflation work budget")));
|
||||
}
|
||||
@@ -169,6 +221,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_budget_errors_name_the_budget_rather_than_a_missing_member() {
|
||||
let material = make_material(&format!("{}{}", linked("a"), linked("b")));
|
||||
|
||||
let read = read_source(&material, 5).unwrap();
|
||||
|
||||
assert!(read.warnings.first().unwrap().contains("resource budget"));
|
||||
assert_eq!(read.pkg.resources.iter().map(|resource| resource.bytes.len()).sum::<usize>(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_sbs_keeps_inline_compatibility_and_zero_length_is_free() {
|
||||
let material = make_material(&format!("{}{}", inline(b""), linked("member")));
|
||||
|
||||
@@ -2,6 +2,6 @@ mod archive;
|
||||
mod image_input;
|
||||
mod snapshot_builder;
|
||||
|
||||
pub use archive::{MATERIAL_EXT, VERSION, is_material, read_material, srgb_usage, write_material};
|
||||
pub use archive::{MATERIAL_EXT, VERSION, is_material, read_material, srgb_usage, write_material, write_material_with_resource_limit};
|
||||
pub use image_input::ImageInput;
|
||||
pub use snapshot_builder::{entry_graph, snapshot};
|
||||
@@ -5,6 +5,9 @@ use materialcraft_core::{Graph, GraphIndex, Package, Value};
|
||||
|
||||
use crate::{FormatError, Result};
|
||||
|
||||
// Bound the combined graph and function traversal independently of cooking
|
||||
const MAX_DEPENDENCY_DEPTH: usize = 32;
|
||||
|
||||
fn bad(message: impl Into<String>) -> FormatError {
|
||||
FormatError::BadPackage(message.into())
|
||||
}
|
||||
@@ -18,17 +21,18 @@ pub fn snapshot(package: &Package, entry: usize) -> Result<Package> {
|
||||
|
||||
let mut result = Package::new(&graph.name);
|
||||
result.format_version.clone_from(&package.format_version);
|
||||
let mut builder = SnapshotBuilder { root: package, result, paths: BTreeMap::new(), active: BTreeSet::new(), resources: BTreeMap::new(), nodes: 0 };
|
||||
let mut builder = SnapshotBuilder { root: package, result, completed: BTreeMap::new(), active: BTreeSet::new(), resources: BTreeMap::new(), nodes: 0 };
|
||||
builder.copy_graph("", entry)?;
|
||||
Ok(builder.result)
|
||||
}
|
||||
|
||||
type Key = (String, usize);
|
||||
type GraphKey = (String, usize);
|
||||
|
||||
struct SnapshotBuilder<'a> {
|
||||
root: &'a Package,
|
||||
result: Package,
|
||||
paths: BTreeMap<Key, (String, usize)>,
|
||||
active: BTreeSet<Key>,
|
||||
completed: BTreeMap<GraphKey, (String, usize)>,
|
||||
active: BTreeSet<GraphKey>,
|
||||
resources: BTreeMap<(String, String), String>,
|
||||
nodes: usize,
|
||||
}
|
||||
@@ -42,11 +46,9 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
self.root.dependencies.get(owner).map(AsRef::as_ref).ok_or_else(|| bad(format!("missing source package `{owner}`")))
|
||||
}
|
||||
|
||||
fn reference(&mut self, owner: &str, name: &str, height: &mut usize) -> Result<String> {
|
||||
fn reference(&mut self, owner: &str, name: &str) -> Result<(String, usize)> {
|
||||
let (index, _) = self.package(owner)?.graph_by_name(name).ok_or_else(|| bad(format!("missing or ambiguous graph `{name}` in `{owner}`")))?;
|
||||
let (path, child_height) = self.copy_graph(owner, index)?;
|
||||
*height = (*height).max(child_height + 1);
|
||||
Ok(path)
|
||||
self.copy_graph(owner, index)
|
||||
}
|
||||
|
||||
fn copy_graph(&mut self, owner: &str, index: usize) -> Result<(String, usize)> {
|
||||
@@ -56,18 +58,17 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
return Err(bad(format!("cyclic graph reference at `{}`", source.sbs_path())));
|
||||
}
|
||||
|
||||
// Bound the complete path, including a shared tail copied on an earlier branch.
|
||||
// Active entries are rejected above, so cached heights here are complete.
|
||||
const MAX_DEPENDENCY_DEPTH: usize = 32;
|
||||
if let Some((path, height)) = self.paths.get(&key) {
|
||||
if self.active.len() + height > MAX_DEPENDENCY_DEPTH {
|
||||
return Err(bad("published graph dependencies exceed the depth or graph count limit"));
|
||||
if let Some((path, depth)) = self.completed.get(&key) {
|
||||
// A shared subtree can be reached from a longer path than its first visit
|
||||
if self.active.len() + depth > MAX_DEPENDENCY_DEPTH {
|
||||
return Err(bad("published graph dependencies exceed the depth limit"));
|
||||
}
|
||||
return Ok((path.clone(), *height));
|
||||
|
||||
return Ok((path.clone(), *depth));
|
||||
}
|
||||
|
||||
// Bound publishing independently of the cooker's per-function and per-instance limits
|
||||
if self.active.len() >= MAX_DEPENDENCY_DEPTH || self.paths.len() >= crate::sbs::MAX_GRAPHS {
|
||||
let graph_count = self.completed.len() + self.active.len();
|
||||
if self.active.len() >= MAX_DEPENDENCY_DEPTH || graph_count >= crate::sbs::MAX_GRAPHS {
|
||||
return Err(bad("published graph dependencies exceed the depth or graph count limit"));
|
||||
}
|
||||
|
||||
@@ -75,7 +76,7 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
if graph.function.is_none() {
|
||||
let outputs: Vec<_> = graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect();
|
||||
let index = GraphIndex::new(&graph);
|
||||
if self.paths.is_empty() && !outputs.iter().any(|id| !index.incoming(*id).is_empty()) {
|
||||
if graph_count == 0 && !outputs.iter().any(|id| !index.incoming(*id).is_empty()) {
|
||||
return Err(bad(format!("select a material graph with connected outputs: `{}`", graph.sbs_path())));
|
||||
}
|
||||
|
||||
@@ -92,14 +93,15 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
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()) };
|
||||
graph.folder = if graph_count == 0 { String::new() } else { format!("Dependencies/g{graph_count}") };
|
||||
let path = graph.sbs_path();
|
||||
self.paths.insert(key.clone(), (path.clone(), 0));
|
||||
let mut height = 1;
|
||||
self.active.insert(key.clone());
|
||||
let mut max_child_depth = 0;
|
||||
for instance in graph.instances_mut() {
|
||||
let package = if instance.package.is_empty() { owner } else { &instance.package };
|
||||
instance.graph = self.reference(package, &instance.graph, &mut height)?;
|
||||
let (local_path, depth) = self.reference(package, &instance.graph)?;
|
||||
instance.graph = local_path;
|
||||
max_child_depth = max_child_depth.max(depth);
|
||||
instance.package.clear();
|
||||
}
|
||||
for node in &mut graph.nodes {
|
||||
@@ -111,7 +113,9 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
if let Some(instance) = &node.instance {
|
||||
node.params.insert("graph".into(), Value::Text(instance.graph.clone()));
|
||||
} else if let Some(Value::Text(target)) = node.params.get_mut("graph") {
|
||||
*target = self.reference(owner, target, &mut height)?;
|
||||
let (local_path, depth) = self.reference(owner, target)?;
|
||||
*target = local_path;
|
||||
max_child_depth = max_child_depth.max(depth);
|
||||
} else {
|
||||
return Err(bad(format!("missing graph reference in `{path}`")));
|
||||
}
|
||||
@@ -122,6 +126,7 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
let Some(Value::Text(name)) = node.params.get_mut("resource").filter(|v| !matches!(v, Value::Text(s) if s.is_empty())) else {
|
||||
return Err(bad(format!("missing resource for {} node {} in `{path}`", node.def, node.id.0)));
|
||||
};
|
||||
|
||||
*name = self.resource(owner, name)?;
|
||||
}
|
||||
"text" => {
|
||||
@@ -138,10 +143,11 @@ impl<'a> SnapshotBuilder<'a> {
|
||||
*name = self.resource(owner, name)?;
|
||||
}
|
||||
|
||||
let depth = max_child_depth + 1;
|
||||
self.active.remove(&key);
|
||||
self.paths.insert(key, (path.clone(), height));
|
||||
self.completed.insert(key, (path.clone(), depth));
|
||||
self.result.graphs.push(graph);
|
||||
Ok((path, height))
|
||||
Ok((path, depth))
|
||||
}
|
||||
|
||||
fn resource(&mut self, owner: &str, name: &str) -> Result<String> {
|
||||
@@ -177,48 +183,44 @@ pub fn entry_graph(pkg: &Package) -> Result<usize> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn graph(name: &str, children: &[String]) -> Graph {
|
||||
let mut graph = Graph::new(name);
|
||||
if children.is_empty() {
|
||||
let source = graph.add_node("uniform", [0.0; 2]);
|
||||
let output = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(source, "output", output, "input").unwrap();
|
||||
}
|
||||
for child in children {
|
||||
let source = graph.add_node("graph_instance", [0.0; 2]);
|
||||
graph.node_mut(source).unwrap().params.insert("graph".into(), Value::Text(child.clone()));
|
||||
let output = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(source, "output", output, "input").unwrap();
|
||||
}
|
||||
graph
|
||||
}
|
||||
|
||||
fn shared_tail(chain: usize, tail: usize, cached_first: bool) -> Package {
|
||||
let mut package = Package::new("depth");
|
||||
let mut children = vec!["tail0".into(), "chain0".into()];
|
||||
if !cached_first {
|
||||
children.reverse();
|
||||
}
|
||||
package.graphs.push(graph("root", &children));
|
||||
for i in 0..chain {
|
||||
let next = if i + 1 == chain { "tail0".into() } else { format!("chain{}", i + 1) };
|
||||
package.graphs.push(graph(&format!("chain{i}"), &[next]));
|
||||
}
|
||||
for i in 0..tail {
|
||||
let children = if i + 1 == tail { vec![] } else { vec![format!("tail{}", i + 1)] };
|
||||
package.graphs.push(graph(&format!("tail{i}"), &children));
|
||||
}
|
||||
package
|
||||
fn connect_reference(graph: &mut Graph, target: &str) {
|
||||
let instance = graph.add_node("graph_instance", [0.0; 2]);
|
||||
graph.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text(target.into()));
|
||||
let output = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(instance, "output", output, "input").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_graph_depth_is_independent_of_reference_order() {
|
||||
for cached_first in [true, false] {
|
||||
// Root + chain + shared tail: 32 is valid, 33 is not. The cached
|
||||
// tail can itself contain dependencies, not just a leaf.
|
||||
for tail in [1, 5] {
|
||||
assert!(snapshot(&shared_tail(31 - tail, tail, cached_first), 0).is_ok());
|
||||
assert!(snapshot(&shared_tail(32 - tail, tail, cached_first), 0).is_err());
|
||||
fn depth_limit_applies_to_both_paths_through_a_shared_subtree() {
|
||||
for depth in [MAX_DEPENDENCY_DEPTH, MAX_DEPENDENCY_DEPTH + 1] {
|
||||
for cached_first in [true, false] {
|
||||
let mut package = Package::new("Shared subtree");
|
||||
let mut root = Graph::new("Root");
|
||||
let targets = if cached_first { ["Shared", "Link0"] } else { ["Link0", "Shared"] };
|
||||
for target in targets {
|
||||
connect_reference(&mut root, target);
|
||||
}
|
||||
|
||||
package.graphs.push(root);
|
||||
let link_count = depth - 3;
|
||||
for index in 0..link_count {
|
||||
let mut link = Graph::new(&format!("Link{index}"));
|
||||
let target = if index + 1 == link_count { "Shared".into() } else { format!("Link{}", index + 1) };
|
||||
connect_reference(&mut link, &target);
|
||||
package.graphs.push(link);
|
||||
}
|
||||
|
||||
let mut shared = Graph::new("Shared");
|
||||
connect_reference(&mut shared, "Leaf");
|
||||
package.graphs.extend([shared, Graph::new("Leaf")]);
|
||||
|
||||
let published = snapshot(&package, 0);
|
||||
|
||||
if depth == MAX_DEPENDENCY_DEPTH {
|
||||
assert_eq!(published.unwrap().graphs.len(), depth);
|
||||
} else {
|
||||
assert!(published.unwrap_err().to_string().contains("depth"), "cached first: {cached_first}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,79 +1,70 @@
|
||||
use super::embedded_error::EmbeddedError;
|
||||
use crate::{FormatError, Result};
|
||||
use base64::Engine as _;
|
||||
use std::io::{Read, Write};
|
||||
use std::{
|
||||
cell::Cell,
|
||||
io::{self, Read, Write},
|
||||
};
|
||||
|
||||
pub(super) fn base64_engine() -> base64::engine::GeneralPurpose {
|
||||
base64::engine::general_purpose::STANDARD
|
||||
}
|
||||
|
||||
pub(super) fn decode_embedded(strdata: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
decode_embedded_bounded(strdata, crate::MAX_RESOURCE, &std::cell::Cell::new(crate::MAX_RESOURCE + 1)).map_err(|error| error.to_string())
|
||||
decode_embedded_bounded(strdata, crate::MAX_RESOURCE, &Cell::new(crate::MAX_RESOURCE + 1)).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum EmbeddedError {
|
||||
Damaged(String),
|
||||
Budget,
|
||||
WorkBudget,
|
||||
}
|
||||
impl From<String> for EmbeddedError {
|
||||
fn from(message: String) -> Self {
|
||||
Self::Damaged(message)
|
||||
}
|
||||
}
|
||||
impl From<&str> for EmbeddedError {
|
||||
fn from(message: &str) -> Self {
|
||||
Self::Damaged(message.into())
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for EmbeddedError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Damaged(message) => f.write_str(message),
|
||||
Self::WorkBudget => f.write_str("embedded resource exceeds the material inflation work budget"),
|
||||
Self::Budget => f.write_str("embedded resource exceeds the remaining material resource budget"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decode_embedded_bounded(strdata: &str, remaining: u64, work: &std::cell::Cell<u64>) -> std::result::Result<Vec<u8>, EmbeddedError> {
|
||||
if work.get() == 0 {
|
||||
pub(super) fn decode_embedded_bounded(strdata: &str, remaining_bytes: u64, inflation_work: &Cell<u64>) -> std::result::Result<Vec<u8>, EmbeddedError> {
|
||||
let work_before = inflation_work.get();
|
||||
if work_before == 0 {
|
||||
return Err(EmbeddedError::WorkBudget);
|
||||
}
|
||||
let raw = base64_engine().decode(strdata.split_whitespace().collect::<String>()).map_err(|e| format!("bad base64: {e}"))?;
|
||||
|
||||
let raw = match strdata.split_once(char::is_whitespace) {
|
||||
Some((prefix, rest)) => base64_engine().decode(std::iter::once(prefix).chain(rest.split_whitespace()).collect::<String>()),
|
||||
None => base64_engine().decode(strdata),
|
||||
}
|
||||
.map_err(|error| format!("bad base64: {error}"))?;
|
||||
let (length, compressed) = raw.split_at_checked(4).ok_or("too short")?;
|
||||
let length = u32::from_be_bytes([length[0], length[1], length[2], length[3]]) as usize;
|
||||
if length as u64 > crate::MAX_RESOURCE {
|
||||
let declared_bytes = u64::from(u32::from_be_bytes([length[0], length[1], length[2], length[3]]));
|
||||
if declared_bytes > crate::MAX_RESOURCE {
|
||||
return Err("embedded resource exceeds the 256 MiB limit".into());
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
|
||||
// Probe only one byte beyond the tighter cap. Corruption detected within that
|
||||
// prefix remains damaged data regardless of the untrusted declared length.
|
||||
// Stop at budget + 1; damage later in an oversized stream is not inspected.
|
||||
let cap = (length as u64).min(remaining) + 1;
|
||||
let work_before = work.get();
|
||||
// Read one probe byte beyond the tighter bound to detect overruns
|
||||
let probe_limit = declared_bytes.min(remaining_bytes) + 1;
|
||||
let mut decoder = flate2::read::ZlibDecoder::new(compressed);
|
||||
let result = decoder.by_ref().take(cap.min(work_before)).read_to_end(&mut out);
|
||||
// Count discarded output and bytes produced before a checksum/error, not only
|
||||
// successfully retained resources. Never restart inflation after exhaustion.
|
||||
work.set(work_before.saturating_sub(decoder.total_out()));
|
||||
result.map_err(|e| format!("bad compressed data: {e}"))?;
|
||||
if out.len() > length {
|
||||
return Err(format!("{} bytes where {length} were declared", out.len()).into());
|
||||
let mut limited = decoder.by_ref().take(probe_limit.min(work_before));
|
||||
let mut output = Vec::new();
|
||||
let result = if declared_bytes > remaining_bytes || declared_bytes >= work_before {
|
||||
// Discard probe output that cannot become a retained asset
|
||||
io::copy(&mut limited, &mut io::sink())
|
||||
} else {
|
||||
limited.read_to_end(&mut output).map(|bytes| bytes as u64)
|
||||
};
|
||||
|
||||
// Charge every emitted byte, including output produced before a checksum error
|
||||
inflation_work.set(work_before.saturating_sub(decoder.total_out()));
|
||||
let actual_bytes = result.map_err(|error| format!("bad compressed data: {error}"))?;
|
||||
if actual_bytes > declared_bytes {
|
||||
return Err(format!("{actual_bytes} bytes where {declared_bytes} were declared").into());
|
||||
}
|
||||
if work_before < cap && out.len() as u64 == work_before {
|
||||
|
||||
if work_before < probe_limit && actual_bytes == work_before {
|
||||
return Err(EmbeddedError::WorkBudget);
|
||||
}
|
||||
if out.len() as u64 > remaining {
|
||||
|
||||
if actual_bytes > remaining_bytes {
|
||||
return Err(EmbeddedError::Budget);
|
||||
}
|
||||
if out.len() != length {
|
||||
return Err(format!("{} bytes where {length} were declared", out.len()).into());
|
||||
|
||||
if actual_bytes != declared_bytes {
|
||||
return Err(format!("{actual_bytes} bytes where {declared_bytes} were declared").into());
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
// ResourceBytes retains the vector and its capacity
|
||||
output.shrink_to_fit();
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub(super) fn encode_embedded(bytes: &[u8]) -> Result<String> {
|
||||
@@ -108,7 +99,7 @@ mod tests {
|
||||
assert!(decode_embedded("AA").unwrap_err().starts_with("bad base64:"));
|
||||
|
||||
let encoded = encode_embedded(b"payload").unwrap();
|
||||
let spaced = encoded.chars().map(|c| format!("{c} \n")).collect::<String>();
|
||||
let spaced = encoded.chars().map(|c| format!("{c} \n\u{2003}")).collect::<String>();
|
||||
|
||||
assert_eq!(decode_embedded(&spaced).unwrap(), b"payload");
|
||||
}
|
||||
@@ -119,24 +110,27 @@ mod tests {
|
||||
let mut raw = length.to_be_bytes().to_vec();
|
||||
raw.push(255);
|
||||
let encoded = base64_engine().encode(raw);
|
||||
assert!(matches!(decode_embedded_bounded(&encoded, 3, &std::cell::Cell::new(16)), Err(EmbeddedError::Damaged(_))));
|
||||
assert!(matches!(decode_embedded_bounded(&encoded, 3, &Cell::new(16)), Err(EmbeddedError::Damaged(_))));
|
||||
}
|
||||
let encoded = encode_embedded(b"four").unwrap();
|
||||
assert!(matches!(decode_embedded_bounded(&encoded, 3, &std::cell::Cell::new(16)), Err(EmbeddedError::Budget)));
|
||||
assert_eq!(decode_embedded_bounded(&encoded, 4, &std::cell::Cell::new(16)).unwrap(), b"four");
|
||||
|
||||
assert!(matches!(decode_embedded_bounded(&encoded, 3, &Cell::new(16)), Err(EmbeddedError::Budget)));
|
||||
assert_eq!(decode_embedded_bounded(&encoded, 4, &Cell::new(16)).unwrap(), b"four");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inflation_work_counts_discarded_prefixes_and_stops_before_next_decode() {
|
||||
let work = std::cell::Cell::new(8);
|
||||
let work = Cell::new(8);
|
||||
let encoded = encode_embedded(b"four").unwrap();
|
||||
for expected in [4, 0] {
|
||||
assert!(matches!(decode_embedded_bounded(&encoded, 3, &work), Err(EmbeddedError::Budget)));
|
||||
assert_eq!(work.get(), expected);
|
||||
}
|
||||
// Even invalid base64 is not inspected after work exhaustion.
|
||||
|
||||
// Exhaustion stops the next resource before Base64 decoding
|
||||
assert!(matches!(decode_embedded_bounded("!!!!", 3, &work), Err(EmbeddedError::WorkBudget)));
|
||||
let work = std::cell::Cell::new(2);
|
||||
|
||||
let work = Cell::new(2);
|
||||
assert!(matches!(decode_embedded_bounded(&encoded, 4, &work), Err(EmbeddedError::WorkBudget)));
|
||||
assert_eq!(work.get(), 0);
|
||||
}
|
||||
@@ -145,7 +139,8 @@ mod tests {
|
||||
fn checksum_errors_charge_output_without_spending_retained_budget() {
|
||||
let mut raw = base64_engine().decode(encode_embedded(b"four").unwrap()).unwrap();
|
||||
*raw.last_mut().unwrap() ^= 1;
|
||||
let work = std::cell::Cell::new(8);
|
||||
let work = Cell::new(8);
|
||||
|
||||
assert!(matches!(decode_embedded_bounded(&base64_engine().encode(raw), 4, &work), Err(EmbeddedError::Damaged(_))));
|
||||
assert_eq!(work.get(), 4);
|
||||
}
|
||||
@@ -154,11 +149,23 @@ mod tests {
|
||||
fn proven_length_mismatch_precedes_retained_budget() {
|
||||
let mut raw = base64_engine().decode(encode_embedded(b"four").unwrap()).unwrap();
|
||||
raw[..4].copy_from_slice(&3_u32.to_be_bytes());
|
||||
let work = std::cell::Cell::new(4);
|
||||
let work = Cell::new(4);
|
||||
|
||||
assert!(matches!(decode_embedded_bounded(&base64_engine().encode(raw), 3, &work), Err(EmbeddedError::Damaged(_))));
|
||||
assert_eq!(work.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_assets_release_spare_decompression_capacity() {
|
||||
let bytes = vec![17; 2 << 20];
|
||||
let encoded = encode_embedded(&bytes).unwrap();
|
||||
|
||||
let decoded = decode_embedded(&encoded).unwrap();
|
||||
|
||||
assert_eq!(decoded, bytes);
|
||||
assert!(decoded.capacity() < 2 * decoded.len(), "retained {} bytes for a {}-byte asset", decoded.capacity(), decoded.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompression_requires_the_declared_length() {
|
||||
let encoded = encode_embedded(&[1, 2, 3, 4]).unwrap();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#[derive(Debug)]
|
||||
pub(super) enum EmbeddedError {
|
||||
Damaged(String),
|
||||
Budget,
|
||||
WorkBudget,
|
||||
}
|
||||
|
||||
impl From<String> for EmbeddedError {
|
||||
fn from(message: String) -> Self {
|
||||
Self::Damaged(message)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for EmbeddedError {
|
||||
fn from(message: &str) -> Self {
|
||||
Self::Damaged(message.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EmbeddedError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Damaged(message) => formatter.write_str(message),
|
||||
Self::Budget => formatter.write_str("embedded resource exceeds the remaining material resource budget"),
|
||||
Self::WorkBudget => formatter.write_str("embedded resource exceeds the material inflation work budget"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Retain typed, including unconnected, material graph inputs when references become local.
|
||||
//! Preserve typed graph inputs, including unconnected inputs, when localizing graph references.
|
||||
use super::xml::{child_element, child_value, children_named, xml_escape};
|
||||
use materialcraft_core::GraphPort;
|
||||
use roxmltree::Node;
|
||||
use std::{collections::BTreeSet, fmt::Write};
|
||||
|
||||
const MAX_INPUTS: usize = 4096;
|
||||
pub(super) const MAX_INPUTS: usize = 4096;
|
||||
|
||||
pub(super) fn read(element: Node<'_, '_>) -> Option<Result<Vec<GraphPort>, String>> {
|
||||
let interface = child_element(element, "materialcraftInterface")?;
|
||||
@@ -13,12 +13,14 @@ pub(super) fn read(element: Node<'_, '_>) -> Option<Result<Vec<GraphPort>, Strin
|
||||
let mut names = BTreeSet::new();
|
||||
for port in children_named(interface, "input") {
|
||||
if inputs.len() == MAX_INPUTS {
|
||||
return Err("Graph instance exceeds the 4096-input limit".into());
|
||||
return Err(format!("Graph instance exceeds the {MAX_INPUTS}-input limit"));
|
||||
}
|
||||
|
||||
let identifier = child_value(port, "identifier").unwrap_or("");
|
||||
if identifier.is_empty() || !names.insert(identifier) {
|
||||
return Err("Invalid or duplicate graph input identifier".into());
|
||||
}
|
||||
|
||||
let type_code = child_value(port, "type").and_then(|value| value.parse().ok()).ok_or("Invalid graph input type")?;
|
||||
inputs.push(GraphPort { identifier: identifier.into(), type_code });
|
||||
}
|
||||
@@ -26,21 +28,19 @@ pub(super) fn read(element: Node<'_, '_>) -> Option<Result<Vec<GraphPort>, Strin
|
||||
})())
|
||||
}
|
||||
|
||||
// XML 1.0 characters: escaping must not silently remove identifier characters.
|
||||
fn xml_identifier_char(c: char) -> bool {
|
||||
matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')
|
||||
}
|
||||
|
||||
pub(super) fn write(out: &mut String, inputs: &[GraphPort]) -> Result<(), String> {
|
||||
if inputs.len() > MAX_INPUTS {
|
||||
return Err("Graph instance exceeds the 4096-input limit".into());
|
||||
return Err(format!("Graph instance exceeds the {MAX_INPUTS}-input limit"));
|
||||
}
|
||||
|
||||
// Validate before writing because the XML escaper drops unsupported characters
|
||||
let mut names = BTreeSet::new();
|
||||
for port in inputs {
|
||||
if port.identifier.is_empty() || !port.identifier.chars().all(xml_identifier_char) || !names.insert(&port.identifier) {
|
||||
if port.identifier.is_empty() || !port.identifier.chars().all(craft_xml::is_xml_char) || !names.insert(&port.identifier) {
|
||||
return Err("Invalid or duplicate graph input identifier".into());
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("<materialcraftInterface>");
|
||||
for port in inputs {
|
||||
let _ = write!(out, "<input><identifier v=\"{}\"/><type v=\"{}\"/></input>", xml_escape(&port.identifier), port.type_code);
|
||||
@@ -60,13 +60,16 @@ mod tests {
|
||||
let document = roxmltree::Document::parse(&xml).unwrap();
|
||||
read(document.root_element()).unwrap()
|
||||
};
|
||||
|
||||
assert!(parse("<input><identifier v=\"a\"/><type v=\"bad\"/></input>").is_err());
|
||||
assert!(parse("<input><identifier v=\"a\"/><type v=\"1\"/></input>".repeat(2).as_str()).is_err());
|
||||
|
||||
let mut body = String::new();
|
||||
for index in 0..4096 {
|
||||
for index in 0..MAX_INPUTS {
|
||||
write!(body, "<input><identifier v=\"p{index}\"/><type v=\"2\"/></input>").unwrap();
|
||||
}
|
||||
assert_eq!(parse(&body).unwrap().len(), 4096);
|
||||
|
||||
assert_eq!(parse(&body).unwrap().len(), MAX_INPUTS);
|
||||
body.push_str("<input><identifier v=\"extra\"/><type v=\"2\"/></input>");
|
||||
assert!(parse(&body).is_err());
|
||||
}
|
||||
@@ -82,16 +85,20 @@ mod writer_tests {
|
||||
let inputs =
|
||||
vec![GraphPort { identifier: "roughness".into(), type_code: 2 }, GraphPort { identifier: format!("roughness{invalid}"), type_code: 2 }];
|
||||
let mut out = String::from("unchanged");
|
||||
|
||||
assert!(write(&mut out, &inputs).is_err());
|
||||
assert_eq!(out, "unchanged");
|
||||
assert!(write(&mut out, &inputs[1..]).is_err());
|
||||
assert_eq!(out, "unchanged");
|
||||
}
|
||||
|
||||
let inputs = vec![GraphPort { identifier: "é😀<&\"'\t\n\r".into(), type_code: 2 }];
|
||||
let mut xml = String::from("<compInstance>");
|
||||
|
||||
write(&mut xml, &inputs).unwrap();
|
||||
xml.push_str("</compInstance>");
|
||||
let document = roxmltree::Document::parse(&xml).unwrap();
|
||||
|
||||
assert_eq!(read(document.root_element()).unwrap().unwrap(), inputs);
|
||||
}
|
||||
|
||||
@@ -99,19 +106,33 @@ mod writer_tests {
|
||||
fn writer_matches_reader_limits_and_refuses_before_appending() {
|
||||
let mut inputs: Vec<_> = (0..MAX_INPUTS).map(|index| GraphPort { identifier: format!("p{index}"), type_code: 2 }).collect();
|
||||
let mut xml = String::from("<compInstance>");
|
||||
|
||||
write(&mut xml, &inputs).unwrap();
|
||||
xml.push_str("</compInstance>");
|
||||
let document = roxmltree::Document::parse(&xml).unwrap();
|
||||
|
||||
assert_eq!(read(document.root_element()).unwrap().unwrap(), inputs);
|
||||
|
||||
inputs.push(GraphPort { identifier: "extra".into(), type_code: 2 });
|
||||
let mut out = String::from("unchanged");
|
||||
assert!(write(&mut out, &inputs).unwrap_err().contains("4096"));
|
||||
assert_eq!(out, "unchanged");
|
||||
|
||||
inputs.truncate(2);
|
||||
inputs[1].identifier = inputs[0].identifier.clone();
|
||||
assert!(write(&mut out, &inputs).is_err());
|
||||
|
||||
inputs[1].identifier.clear();
|
||||
assert!(write(&mut out, &inputs).is_err());
|
||||
assert_eq!(out, "unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_rejects_input_identifiers_that_xml_would_change() {
|
||||
let mut xml = String::new();
|
||||
let inputs = [GraphPort { identifier: "roughness".into(), type_code: 2 }, GraphPort { identifier: "roughness\u{1f}".into(), type_code: 2 }];
|
||||
|
||||
assert!(write(&mut xml, &inputs).is_err());
|
||||
assert!(xml.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod component_usage;
|
||||
mod connection;
|
||||
mod constant;
|
||||
mod embedded;
|
||||
mod embedded_error;
|
||||
mod filter_map;
|
||||
mod function_graph;
|
||||
mod function_instance;
|
||||
|
||||
@@ -12,6 +12,7 @@ pub(super) fn write(out: &mut String, graph: &Graph, uids: &HashMap<String, u64>
|
||||
if graph.presets.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
out.push_str("<sbspresets>");
|
||||
for preset in &graph.presets {
|
||||
let _ = write!(out, "<sbspreset><label v=\"{}\"/><presetinputs>", xml_escape(&preset.name));
|
||||
@@ -34,11 +35,13 @@ pub(super) fn read(element: Node<'_, '_>, graph: &mut Graph) {
|
||||
let Some(presets) = child_element(element, "sbspresets") else {
|
||||
return;
|
||||
};
|
||||
|
||||
let exposed: HashMap<_, _> = graph.exposed.iter().map(|p| (p.id.as_str(), p)).collect();
|
||||
for preset in children_named(presets, "sbspreset") {
|
||||
let Some(name) = child_value(preset, "label") else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let values = child_element(preset, "presetinputs")
|
||||
.into_iter()
|
||||
.flat_map(|inputs| children_named(inputs, "presetinput"))
|
||||
|
||||
@@ -33,10 +33,10 @@ pub(super) fn read_document(
|
||||
_ => "Untitled package".to_string(),
|
||||
};
|
||||
|
||||
// Include one probe byte so a valid inline asset can use the exact retained limit
|
||||
let inflation_work = std::cell::Cell::new(resource_budget.map_or(0, |budget| budget.get().saturating_add(1)));
|
||||
let mut reader = SbsReader {
|
||||
// A separate output-work allowance counts failed/discarded inflations too.
|
||||
// One probe byte distinguishes an exact retained limit from an overrun.
|
||||
inflation_work: std::cell::Cell::new(resource_budget.map_or(0, |budget| budget.get().saturating_add(1))),
|
||||
inflation_work,
|
||||
resource_budget,
|
||||
text,
|
||||
warnings: &mut warnings,
|
||||
|
||||
@@ -3,10 +3,12 @@ use super::component_usage;
|
||||
use super::connection::connect_all;
|
||||
use super::constant::{MAX_NODES, MAX_WIRES};
|
||||
use super::constant::{NODE_HALF_SIZE, SELF_DEPENDENCY};
|
||||
use super::embedded::{EmbeddedError, decode_embedded, decode_embedded_bounded};
|
||||
use super::embedded::{decode_embedded, decode_embedded_bounded};
|
||||
use super::embedded_error::EmbeddedError;
|
||||
use super::filter_map::{BASE_PARAMS, FilterMap, HANDLED_PARAMS, filter_by_sbs_name};
|
||||
use super::function_graph;
|
||||
use super::input_bridge::InputBridge;
|
||||
use super::instance_interface::MAX_INPUTS;
|
||||
use super::placeholder::{add_placeholder_input, fill_placeholder, placeholder_outputs};
|
||||
use super::read_node::ReadNode;
|
||||
use super::sbs_value::{SbsValue, exposed_default, sbs_constant, to_natural_value, to_param_value};
|
||||
@@ -118,15 +120,14 @@ impl<'text> SbsReader<'text, '_> {
|
||||
match decoded {
|
||||
Ok(data) if !font || !data.is_empty() => {
|
||||
if let Some(budget) = self.resource_budget {
|
||||
// The decoder bounded its output and checked the retained length.
|
||||
// The decoder checked the retained length
|
||||
budget.set(budget.get().saturating_sub(data.len() as u64));
|
||||
}
|
||||
bytes = Some(data);
|
||||
}
|
||||
Ok(_) => why_missing = "its embedded font data is empty".into(),
|
||||
Err(error @ (EmbeddedError::Budget | EmbeddedError::WorkBudget)) => {
|
||||
// A valid inline asset wins over linked data. Never silently change
|
||||
// the material when retaining that asset would exhaust its budget.
|
||||
// Reject a budget error to preserve inline asset precedence
|
||||
self.warnings.add(format!("resource `{path}`: {error}"));
|
||||
return unique_name(&mut self.used_resource_names, if identifier.is_empty() { "resource" } else { identifier });
|
||||
}
|
||||
@@ -154,7 +155,7 @@ impl<'text> SbsReader<'text, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
// A supplied font, including cour.ttf or embedded data, always wins. Only absence uses the shared fallback
|
||||
// Prefer supplied font bytes before trying the shared fallback
|
||||
if font && bytes.is_none() {
|
||||
if let Some(name) = super::resource_replacement::load_font(self, pkg, identifier, path, linked) {
|
||||
return name;
|
||||
@@ -402,6 +403,13 @@ impl<'text> SbsReader<'text, '_> {
|
||||
if let Some(node) = graph.nodes.get_mut(to.index) {
|
||||
if let Some(instance) = &mut node.instance {
|
||||
if !instance.inputs.iter().any(|port| port.identifier == sbs_input) {
|
||||
if instance.inputs.len() >= MAX_INPUTS || sbs_input.is_empty() {
|
||||
self.warnings.add(format!(
|
||||
"graph `{name}`: invalid input `{sbs_input}` or instance at its {MAX_INPUTS}-input limit; wire was dropped"
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
instance.inputs.push(materialcraft_core::GraphPort { identifier: sbs_input.into(), type_code: 1 });
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -507,9 +507,34 @@ fn published_material_preserves_disabled_nodes_and_localized_typed_interfaces()
|
||||
assert_eq!(restored.outputs, vec![GraphPort { identifier: "result".into(), type_code: 2 }]);
|
||||
assert!(opened.graph_by_name(&restored.graph).is_some());
|
||||
assert!(graph.connections.iter().any(|wire| wire.to == node.id && wire.to_port == "gray"));
|
||||
// Republish the already-localized graph as well as the original external reference.
|
||||
|
||||
// Republish the already-localized graph to exercise local interfaces
|
||||
let bytes = write_material(&opened, entry).unwrap();
|
||||
let (reopened, entry) = read_material(&bytes).unwrap();
|
||||
assert_eq!(reopened.graphs[entry].nodes.iter().find_map(|node| node.instance.as_ref()).unwrap().inputs, inputs);
|
||||
assert!(reopened.graphs[entry].nodes.iter().find(|node| node.def == "levels").unwrap().disabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inferred_instance_inputs_respect_the_typed_interface_limit() {
|
||||
use materialcraft_core::{GraphInstance, GraphPort};
|
||||
|
||||
let mut package = Package::new("Package");
|
||||
let mut root = Graph::new("Root");
|
||||
let source = root.add_node("uniform", [0.0; 2]);
|
||||
let instance = root.add_node("graph_instance", [0.0; 2]);
|
||||
let inputs = (0..4096).map(|index| GraphPort { identifier: format!("input{index}"), type_code: 1 }).collect();
|
||||
root.node_mut(instance).unwrap().instance =
|
||||
Some(GraphInstance { label: String::new(), package: String::new(), graph: "Helper".into(), inputs, outputs: Vec::new(), defaults: Default::default() });
|
||||
root.connect(source, "output", instance, "input0").unwrap();
|
||||
package.graphs.extend([root, Graph::new("Helper")]);
|
||||
let xml = String::from_utf8(write_sbs(&package).unwrap()).unwrap();
|
||||
let xml = xml.replace("<connection><identifier v=\"input0\"", "<connection><identifier v=\"inferred\"");
|
||||
|
||||
let restored = read_sbs(xml.as_bytes(), "instance.sbs", &no_linked_files).unwrap();
|
||||
|
||||
let root = &restored.pkg.graphs[0];
|
||||
assert_eq!(root.instances().next().unwrap().inputs.len(), 4096);
|
||||
assert!(root.connections.is_empty());
|
||||
assert!(restored.warnings.iter().any(|warning| warning.contains("4096-input")));
|
||||
}
|
||||
@@ -36,11 +36,10 @@ craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
|
||||
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-platform = { workspace = true, features = ["browser"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Navigator"] }
|
||||
|
||||
# winit needs a window system on Linux, so the crate's own tests build with X11.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
|
||||
@@ -35,7 +35,7 @@ fn selection_names_the_checked_outputs_and_their_color_spaces() {
|
||||
|
||||
let (outputs, color_spaces) = settings.selection(graph).unwrap();
|
||||
assert_eq!(outputs, Value::Null, "with every output checked, file.export writes them all");
|
||||
assert_eq!(color_spaces, json!({"base_color": "srgb", "height": "raw"}), "unpicked outputs follow their usage");
|
||||
assert_eq!(color_spaces, json!({}), "unpicked outputs follow the encoder's defaults");
|
||||
|
||||
settings.skipped_outputs.insert(output_key("New_graph", "height"));
|
||||
settings.color_spaces.insert(output_key("New_graph", "base_color"), materialcraft_engine::ColorSpace::Linear);
|
||||
@@ -120,7 +120,8 @@ fn material_dialog_rejects_another_package_with_the_same_graph_path() {
|
||||
assert!(!publish(&mut app, &draft));
|
||||
assert!(app.toasts.last().unwrap().text.contains("export package changed"));
|
||||
assert!(app.material_export_job.is_none());
|
||||
// Switching back preserves the original dialog and reaches destination validation.
|
||||
|
||||
// Switching back preserves the original dialog and reaches destination validation
|
||||
app.run("package.activate", json!({"document": original})).unwrap();
|
||||
assert!(!publish(&mut app, &draft));
|
||||
assert!(app.toasts.last().unwrap().text.contains("export destination"));
|
||||
@@ -165,13 +166,16 @@ fn folder_graphs_keep_independent_output_selection_and_color_spaces() {
|
||||
let mut outdoor = indoor.clone();
|
||||
outdoor.folder = "Outdoor".into();
|
||||
let mut settings = ExportSettings::default();
|
||||
|
||||
settings.include_all(&indoor, false);
|
||||
assert!(settings.selection(&indoor).is_none());
|
||||
assert!(settings.selection(&outdoor).is_some());
|
||||
assert_eq!(settings.selection(&outdoor).unwrap(), (Value::Null, json!({})));
|
||||
|
||||
settings.include_all(&indoor, true);
|
||||
settings.color_spaces.insert(output_key(&indoor.sbs_path(), "base_color"), materialcraft_engine::ColorSpace::Linear);
|
||||
assert_eq!(settings.selection(&indoor).unwrap().1["base_color"], "linear");
|
||||
assert_eq!(settings.selection(&outdoor).unwrap().1["base_color"], "srgb");
|
||||
|
||||
assert_eq!(settings.selection(&indoor).unwrap(), (Value::Null, json!({"base_color":"linear"})));
|
||||
assert_eq!(settings.selection(&outdoor).unwrap(), (Value::Null, json!({})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -101,11 +101,12 @@ fn tabs(ui: &mut Ui, current: &mut ExportTab) {
|
||||
}
|
||||
|
||||
fn from_graph(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportSettings) {
|
||||
let graph = app.session.graph().ok().filter(|graph| graph.function.is_none()).cloned();
|
||||
image_options(app, ui, settings, graph.as_ref());
|
||||
image_options(app, ui, settings);
|
||||
|
||||
let graph = app.session.graph().ok().filter(|graph| graph.function.is_none());
|
||||
ui.add_space(6.0);
|
||||
ui.label(RichText::new(tr("Outputs")).strong());
|
||||
outputs::tree(ui, settings, graph.as_slice().iter().collect::<Vec<_>>().as_slice());
|
||||
outputs::tree(ui, settings, graph.as_slice());
|
||||
all_or_none(ui, settings, graph.as_slice());
|
||||
|
||||
ui.add_space(4.0);
|
||||
@@ -119,11 +120,12 @@ fn from_graph(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportSett
|
||||
}
|
||||
|
||||
fn batch(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportSettings) {
|
||||
let graphs = material_graphs(app);
|
||||
image_options(app, ui, settings, graphs.first());
|
||||
image_options(app, ui, settings);
|
||||
|
||||
let graphs: Vec<_> = app.session.pkg.graphs.iter().filter(|graph| graph.function.is_none()).collect();
|
||||
ui.add_space(6.0);
|
||||
ui.label(RichText::new(tr("Outputs")).strong());
|
||||
outputs::tree(ui, settings, graphs.iter().collect::<Vec<_>>().as_slice());
|
||||
outputs::tree(ui, settings, &graphs);
|
||||
all_or_none(ui, settings, &graphs);
|
||||
|
||||
ui.add_space(4.0);
|
||||
@@ -149,8 +151,14 @@ fn batch(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportSettings)
|
||||
}
|
||||
|
||||
/// Destination, format, bit depth, file name pattern and its preview
|
||||
fn image_options(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportSettings, preview_graph: Option<&Graph>) {
|
||||
fn image_options(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportSettings) {
|
||||
let preview_graph = if app.ui.export_tab == ExportTab::Batch {
|
||||
app.session.pkg.graphs.iter().find(|graph| graph.function.is_none())
|
||||
} else {
|
||||
app.session.graph().ok().filter(|graph| graph.function.is_none())
|
||||
};
|
||||
let preview = preview_graph.and_then(|graph| preview_file(settings, graph)).unwrap_or_default();
|
||||
|
||||
form(ui, "export-image-options", |ui, width| {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
@@ -161,9 +169,6 @@ fn image_options(app: &mut MaterialCraftApp, ui: &mut Ui, settings: &mut ExportS
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = &app;
|
||||
|
||||
form_label(ui, tr("Format"));
|
||||
let selected = ExportFormat::find(&settings.format).map_or_else(|| settings.format.clone(), ExportFormat::title);
|
||||
dropdown(ui, "Format", width, selected, |ui| {
|
||||
@@ -241,12 +246,13 @@ pub(super) fn path_field(ui: &mut Ui, path: &mut String, width: f32) -> bool {
|
||||
|
||||
/// The file name the first checked output of `graph` is written to
|
||||
fn preview_file(settings: &ExportSettings, graph: &Graph) -> Option<String> {
|
||||
let output = outputs::listed(graph).into_iter().find(|output| settings.includes(&graph.sbs_path(), &output.identifier))?;
|
||||
let graph_path = graph.sbs_path();
|
||||
let output = outputs::listed(graph).into_iter().find(|output| settings.includes(&graph_path, &output.identifier))?;
|
||||
let name = materialcraft_engine::formats::output_name(&settings.pattern, &graph.name, &output.identifier, output.usage);
|
||||
Some(format!("{name}.{}", settings.format))
|
||||
}
|
||||
|
||||
fn all_or_none(ui: &mut Ui, settings: &mut ExportSettings, graphs: &[Graph]) {
|
||||
fn all_or_none(ui: &mut Ui, settings: &mut ExportSettings, graphs: &[&Graph]) {
|
||||
ui.horizontal(|ui| {
|
||||
for (label, include) in [("All", true), ("None", false)] {
|
||||
if ui.add(egui::Button::new(tr(label)).min_size(vec2(100.0, 0.0))).clicked() {
|
||||
@@ -290,11 +296,6 @@ fn footer(ui: &mut Ui, tab: ExportTab) -> Option<Action> {
|
||||
action
|
||||
}
|
||||
|
||||
/// The package's material graphs, in package order
|
||||
fn material_graphs(app: &MaterialCraftApp) -> Vec<Graph> {
|
||||
app.session.pkg.graphs.iter().filter(|graph| graph.function.is_none()).cloned().collect()
|
||||
}
|
||||
|
||||
/// Export what the current tab describes; true when the window can close
|
||||
fn export(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool {
|
||||
match app.ui.export_tab {
|
||||
@@ -319,6 +320,7 @@ fn export_images(app: &mut MaterialCraftApp, settings: &ExportSettings, graphs:
|
||||
app.toast(crate::i18n::trf("{format} export isn't available yet", &[("format", &format.title())]), true);
|
||||
return false;
|
||||
}
|
||||
|
||||
if settings.destination.trim().is_empty() && !cfg!(target_arch = "wasm32") {
|
||||
app.toast(tr("Choose a folder to export to"), true);
|
||||
return false;
|
||||
@@ -358,15 +360,18 @@ fn export_images(app: &mut MaterialCraftApp, settings: &ExportSettings, graphs:
|
||||
|
||||
fn publish(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool {
|
||||
let material = &settings.material;
|
||||
// Graph paths are only unique within a package. Never resolve a stale dialog against another one.
|
||||
|
||||
// Keep the draft tied to its package because graph paths can repeat across documents
|
||||
if !app.session.has_package() || material.document != Some(app.session.document_id) {
|
||||
app.toast(tr("The export package changed. Reopen the Export window"), true);
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some((index, graph)) = app.session.pkg.graph_by_name(&material.root) else {
|
||||
app.toast(tr("Choose a root graph"), true);
|
||||
return false;
|
||||
};
|
||||
|
||||
let is_archive = app.ui.export_tab == ExportTab::Mcmat;
|
||||
let (command, params) = if is_archive {
|
||||
("file.exportMaterial", json!({"graph":index,"path":material.archive}))
|
||||
@@ -375,6 +380,7 @@ fn publish(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool {
|
||||
app.toast(tr("Check at least one output to export"), true);
|
||||
return false;
|
||||
};
|
||||
|
||||
let depth = match material.texture_depth {
|
||||
TextureDepth::Automatic => None,
|
||||
TextureDepth::Eight => Some(8),
|
||||
@@ -392,10 +398,12 @@ fn publish(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool {
|
||||
app.toast(tr("A material export is running"), true);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (if is_archive { &material.archive } else { &material.folder }).trim().is_empty() {
|
||||
app.toast(tr("Choose an export destination"), true);
|
||||
return false;
|
||||
}
|
||||
|
||||
let package = app.session.pkg.clone();
|
||||
let environment = app.session.environment;
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
@@ -472,5 +480,6 @@ pub(crate) fn poll(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
/// Keep native and browser exports explicit about omitted shader connections.
|
||||
fn material_export_message(report: &Value) -> String {
|
||||
let unmapped = report["unmapped"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>();
|
||||
|
||||
if unmapped.is_empty() { tr("Material exported").to_string() } else { format!("{}: {}", tr("Exported without shader connections"), unmapped.join(", ")) }
|
||||
}
|
||||
@@ -34,14 +34,16 @@ impl ExportSettings {
|
||||
!self.skipped_outputs.contains(&output_key(graph, identifier))
|
||||
}
|
||||
|
||||
/// The chosen color space or the graph usage's default before format-specific encoding.
|
||||
pub fn color_space(&self, graph: &str, output: &ListedOutput) -> ColorSpace {
|
||||
self.color_spaces.get(&output_key(graph, &output.identifier)).copied().unwrap_or_else(|| ColorSpace::for_usage(output.usage))
|
||||
}
|
||||
|
||||
/// Check or uncheck every output of `graph`
|
||||
pub fn include_all(&mut self, graph: &Graph, include: bool) {
|
||||
let graph_path = graph.sbs_path();
|
||||
for output in listed(graph) {
|
||||
let key = output_key(&graph.sbs_path(), &output.identifier);
|
||||
let key = output_key(&graph_path, &output.identifier);
|
||||
if include {
|
||||
self.skipped_outputs.remove(&key);
|
||||
} else {
|
||||
@@ -52,16 +54,22 @@ impl ExportSettings {
|
||||
|
||||
/// The `file.export` `outputs` and `colorSpaces` for `graph`; `None` when none of its outputs is checked
|
||||
pub fn selection(&self, graph: &Graph) -> Option<(Value, Value)> {
|
||||
let graph_path = graph.sbs_path();
|
||||
let outputs = listed(graph);
|
||||
let included: Vec<&ListedOutput> = outputs.iter().filter(|output| self.includes(&graph.sbs_path(), &output.identifier)).collect();
|
||||
let included: Vec<&ListedOutput> = outputs.iter().filter(|output| self.includes(&graph_path, &output.identifier)).collect();
|
||||
if included.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let identifiers =
|
||||
if included.len() == outputs.len() { Value::Null } else { json!(included.iter().map(|output| &output.identifier).collect::<Vec<_>>()) };
|
||||
let color_spaces: serde_json::Map<String, Value> =
|
||||
included.iter().map(|output| (output.identifier.clone(), json!(self.color_space(&graph.sbs_path(), output).id()))).collect();
|
||||
let color_spaces: serde_json::Map<String, Value> = included
|
||||
.iter()
|
||||
.filter_map(|output| {
|
||||
let space = self.color_spaces.get(&output_key(&graph_path, &output.identifier))?;
|
||||
Some((output.identifier.clone(), json!(space.id())))
|
||||
})
|
||||
.collect();
|
||||
Some((identifiers, Value::Object(color_spaces)))
|
||||
}
|
||||
}
|
||||
@@ -76,9 +84,10 @@ pub fn tree(ui: &mut Ui, settings: &mut ExportSettings, graphs: &[&Graph]) {
|
||||
|
||||
egui::ScrollArea::vertical().id_salt("export-outputs").max_height(240.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
for graph in graphs {
|
||||
let graph_path = graph.sbs_path();
|
||||
let outputs = listed(graph);
|
||||
let included = outputs.iter().filter(|output| settings.includes(&graph.sbs_path(), &output.identifier)).count();
|
||||
let id = ui.make_persistent_id(("export-graph", graph.sbs_path()));
|
||||
let included = outputs.iter().filter(|output| settings.includes(&graph_path, &output.identifier)).count();
|
||||
let id = ui.make_persistent_id(("export-graph", &graph_path));
|
||||
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
|
||||
.show_header(ui, |ui| {
|
||||
let mut all = !outputs.is_empty() && included == outputs.len();
|
||||
@@ -91,21 +100,21 @@ pub fn tree(ui: &mut Ui, settings: &mut ExportSettings, graphs: &[&Graph]) {
|
||||
ui.add_space((OUTPUT_COLUMN_WIDTH + indent + 16.0 - ui.min_rect().width()).max(8.0));
|
||||
ui.label(RichText::new(tr("Exported color space")).color(tokens.text_dim));
|
||||
})
|
||||
.body(|ui| outputs_grid(ui, settings, graph, &outputs));
|
||||
.body(|ui| outputs_grid(ui, settings, &graph_path, &outputs));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn outputs_grid(ui: &mut Ui, settings: &mut ExportSettings, graph: &Graph, outputs: &[ListedOutput]) {
|
||||
fn outputs_grid(ui: &mut Ui, settings: &mut ExportSettings, graph_path: &str, outputs: &[ListedOutput]) {
|
||||
if outputs.is_empty() {
|
||||
ui.label(RichText::new(tr("This graph has no outputs")).color(Tokens::get(ui.ctx()).text_dim));
|
||||
return;
|
||||
}
|
||||
|
||||
egui::Grid::new(("export-outputs-grid", graph.sbs_path())).num_columns(2).min_col_width(OUTPUT_COLUMN_WIDTH).spacing([8.0, 4.0]).show(ui, |ui| {
|
||||
egui::Grid::new(("export-outputs-grid", graph_path)).num_columns(2).min_col_width(OUTPUT_COLUMN_WIDTH).spacing([8.0, 4.0]).show(ui, |ui| {
|
||||
for output in outputs {
|
||||
let key = output_key(&graph.sbs_path(), &output.identifier);
|
||||
let mut included = settings.includes(&graph.sbs_path(), &output.identifier);
|
||||
let key = output_key(graph_path, &output.identifier);
|
||||
let mut included = !settings.skipped_outputs.contains(&key);
|
||||
let checkbox = ui.checkbox(&mut included, &output.identifier);
|
||||
crate::widgets::name(&checkbox, egui::Role::CheckBox, &output.identifier);
|
||||
if checkbox.changed() {
|
||||
@@ -116,15 +125,22 @@ fn outputs_grid(ui: &mut Ui, settings: &mut ExportSettings, graph: &Graph, outpu
|
||||
}
|
||||
}
|
||||
|
||||
let mut space = settings.color_space(&graph.sbs_path(), output);
|
||||
let combo = egui::ComboBox::from_id_salt(("export-color-space", &key)).width(110.0).selected_text(space.label()).show_ui(ui, |ui| {
|
||||
let original_space = settings.color_spaces.get(&key).copied();
|
||||
let mut space = original_space;
|
||||
let label = space.map_or_else(|| tr("Automatic"), ColorSpace::label);
|
||||
let combo = egui::ComboBox::from_id_salt(("export-color-space", &key)).width(110.0).selected_text(label).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut space, None, tr("Automatic"));
|
||||
for choice in ColorSpace::ALL {
|
||||
ui.selectable_value(&mut space, choice, choice.label());
|
||||
ui.selectable_value(&mut space, Some(choice), choice.label());
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&combo.response, egui::Role::ComboBox, &format!("{} {}", output.identifier, tr("color space")));
|
||||
if space != settings.color_space(&graph.sbs_path(), output) {
|
||||
settings.color_spaces.insert(key, space);
|
||||
if space != original_space {
|
||||
if let Some(space) = space {
|
||||
settings.color_spaces.insert(key, space);
|
||||
} else {
|
||||
settings.color_spaces.remove(&key);
|
||||
}
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
@@ -128,6 +128,7 @@ impl MaterialCraftApp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
window_layout: None,
|
||||
keymap: menus::keymap(craft_keymap::Platform::current()),
|
||||
|
||||
// Accept clipboard events without duplicating web key commands
|
||||
dispatcher: craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(true),
|
||||
system_clipboard: None,
|
||||
|
||||
@@ -470,9 +470,10 @@ fn a_saved_package_goes_to_the_document_that_asked() {
|
||||
let second = app.session.document_id;
|
||||
assert_ne!(first, second, "a second package is open");
|
||||
|
||||
// SBS saves also write adjacent resources; isolate this test from parallel saves.
|
||||
// Keep adjacent SBS resources in an exclusive directory
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("first.sbs");
|
||||
|
||||
let saved = save_to(&mut app, first, false, &path.display().to_string());
|
||||
assert!(saved, "{}", app.toasts.last().map_or("no error toast", |toast| toast.text.as_str()));
|
||||
assert_eq!(app.session.document_id, first, "the asking package is active again");
|
||||
|
||||
@@ -206,8 +206,6 @@ pub use web::*;
|
||||
mod web {
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
use super::{INBOX, Pick, zip_files};
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
@@ -320,27 +318,12 @@ mod web {
|
||||
|
||||
/// Start a browser download of `bytes` named `name` (Blob + a temporary `<a download>`)
|
||||
pub fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type(if name.ends_with(".zip") { "application/zip" } else { "application/octet-stream" });
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
|
||||
a.set_href(&url);
|
||||
a.set_download(name);
|
||||
a.style().set_property("display", "none").map_err(js)?;
|
||||
document.body().ok_or("no body")?.append_child(&a).map_err(js)?;
|
||||
a.click();
|
||||
a.remove();
|
||||
// Revoke once the click has been dispatched; the download keeps its own reference
|
||||
let revoke = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
web_sys::Url::revoke_object_url(&url).ok();
|
||||
});
|
||||
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?;
|
||||
Ok(())
|
||||
use craft_platform::browser::{DownloadOptions, download_bytes};
|
||||
|
||||
// Allow the browser to acquire the Blob after the click
|
||||
const DOWNLOAD_URL_LIFETIME_MS: i32 = 10_000;
|
||||
let mime = if name.ends_with(".zip") { "application/zip" } else { "application/octet-stream" };
|
||||
download_bytes(name, mime, bytes, DownloadOptions { revoke_after_ms: DOWNLOAD_URL_LIFETIME_MS }).map_err(|error| format!("{error:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -130,6 +130,7 @@ mod import_tests {
|
||||
assert_eq!(app.session.history().len(), base);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_dialogs_offer_separate_formats_and_import_filters_show_full_names() {
|
||||
use super::{package_filters, resource_filters};
|
||||
|
||||
@@ -25,7 +25,8 @@ fn open_from_the_graph_menu(harness: &mut Harness<'static, MaterialCraftApp>, it
|
||||
let graph = harness.state().session.graph().unwrap().name.clone();
|
||||
harness.get(By::new().role(Role::TreeItem).label(graph.as_str())).click_secondary();
|
||||
harness.run_steps(3);
|
||||
// The Explorer toolbar has an Export outputs button too; the menu opens after it
|
||||
|
||||
// The menu item follows the identically named toolbar button
|
||||
harness.get_all(By::new().role(Role::Button).label(item)).last().unwrap().click();
|
||||
harness.run_steps(3);
|
||||
}
|
||||
@@ -96,6 +97,30 @@ fn checking_outputs_in_the_tree_updates_the_window_copy() {
|
||||
assert!(harness.state().ui.export_draft.as_ref().unwrap().skipped_outputs.is_empty(), "the graph's checkbox checks all its outputs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_color_can_be_explicit_or_automatic() {
|
||||
let mut harness = harness();
|
||||
open_from_the_graph_menu(&mut harness, "Export outputs...");
|
||||
let graph = harness.state().session.graph().unwrap().sbs_path();
|
||||
let key = materialcraft_ui_egui::export::output_key(&graph, "height");
|
||||
|
||||
harness.get(By::new().role(Role::ComboBox).label("height color space")).click();
|
||||
harness.run_steps(2);
|
||||
harness.get_by_label("Raw").click();
|
||||
harness.run_steps(2);
|
||||
|
||||
let draft = harness.state().ui.export_draft.as_ref().unwrap();
|
||||
assert_eq!(draft.color_spaces.get(&key), Some(&materialcraft_engine::ColorSpace::Raw));
|
||||
|
||||
harness.get(By::new().role(Role::ComboBox).label("height color space")).click();
|
||||
harness.run_steps(2);
|
||||
harness.get_by_label("Automatic").click();
|
||||
harness.run_steps(2);
|
||||
|
||||
let draft = harness.state().ui.export_draft.as_ref().unwrap();
|
||||
assert!(!draft.color_spaces.contains_key(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_the_graph_chosen_in_the_dialog() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -9,8 +9,8 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState};
|
||||
|
||||
fn harness(w: f32, h: f32) -> Harness<'static, MaterialCraftApp> {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
|
||||
// This tests resize scheduling, not full-viewport ray-tracing throughput under coverage.
|
||||
// Keep real background rendering and viewport-relative dimensions, with fewer pixels.
|
||||
|
||||
// Retain real background rendering with fewer pixels to test resize scheduling under coverage
|
||||
app.session.view3d.override_resolution = true;
|
||||
app.session.view3d.viewport_resolution = true;
|
||||
app.session.view3d.render_scale = 25;
|
||||
@@ -29,7 +29,7 @@ fn settle(h: &mut Harness<'static, MaterialCraftApp>) {
|
||||
h.step();
|
||||
let app = h.state();
|
||||
if !app.cooker.busy() && !app.session.dirty && !app.view3d.busy() && app.view3d.renders > 0 {
|
||||
// A few more frames: the settle delay may still be running after the last change.
|
||||
// Allow the resize settle delay to elapse after the last change
|
||||
for _ in 0..20 {
|
||||
h.step();
|
||||
}
|
||||
@@ -55,14 +55,16 @@ fn a_resize_does_not_render_the_3d_view_on_every_frame() {
|
||||
settle(&mut h);
|
||||
let before = h.state().view3d.renders;
|
||||
let shown = h.state().view3d.shown.as_ref().map(|(w, ht, _)| (*w, *ht));
|
||||
// A drag: the window (and with it every panel) gets narrower on each of 40 frames.
|
||||
|
||||
// Simulate a continuous window resize
|
||||
for i in 0..40 {
|
||||
h.set_size(vec2(1400.0 - 4.0 * i as f32, 860.0));
|
||||
h.step();
|
||||
}
|
||||
assert_eq!(h.state().view3d.renders, before, "the 3D view rendered while it was being resized");
|
||||
assert!(!h.state().view3d.busy(), "a render started while the view was being resized");
|
||||
// Released: one full-quality frame at the new size, in the background.
|
||||
|
||||
// Expect one background render once the size settles
|
||||
settle(&mut h);
|
||||
assert_eq!(h.state().view3d.renders, before + 1);
|
||||
let now = h.state().view3d.shown.as_ref().map(|(w, ht, _)| (*w, *ht));
|
||||
|
||||
@@ -352,6 +352,8 @@ includes frame, comment and pin rectangles for synthetic input.
|
||||
|
||||
A v3 `.mcmat` publishes a single material graph for procedural cooking. Choose **Export material… → MCMAT → Root graph** or give the graph's full SBS path to the CLI.
|
||||
|
||||
The commands below assume `surfaces.sbs` has a connected material graph at `Materials/Oak`, a scalar control named `wear`, a preset named `Worn`, and an image input named `curvature`. Supply a mesh map at `mesh/curvature.exr`.
|
||||
|
||||
```sh
|
||||
materialcraft-cli publish surfaces.sbs Oak.mcmat --graph Materials/Oak
|
||||
materialcraft-cli info Oak.mcmat
|
||||
@@ -366,13 +368,12 @@ The ZIP contains a version marker (`material.json` with `{"version":3}`), a DEFL
|
||||
|
||||
TextureCraft requests `--profile maps` at its texture set's resolution and supplies mesh maps through repeated `--input identifier=path`. Common identifiers include `ambientOcclusion`, `curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`, `opacity`, `colorMap` and `worldDirection`. An image override uses the published preview binding’s color space when present. Otherwise the input’s declared usage determines the transfer, with the identifier as a fallback for untagged inputs. The JSON report lists each map's identifier, usage, filename, color space and actual dimensions.
|
||||
|
||||
Named bake profiles select their own output formats and filenames: do not supply `format` or `pattern`.
|
||||
`normalFormat` requires an explicit bake profile. Explicit sRGB overrides are refused for floating-point
|
||||
EXR outputs; omit the override or choose raw/linear. The CLI's `--graph-path` selects a literal SBS path,
|
||||
including a numeric name, while `--graph` retains numeric-index shorthand.
|
||||
The CLI's `--graph-path` selects a literal SBS path, including a numeric name, while `--graph` retains numeric-index shorthand.
|
||||
|
||||
The `materialx` profile writes `material.mtlx` with relative texture paths and an OpenPBR surface. Color textures default to sRGB PNG, data textures to linear 16-bit PNG, and out-of-range values to floating-point EXR. Both bake profiles write tangent-space Y+ normals. A directly connected Normal node supplies its evaluated convention, including through routing dots. Other normal sources default to Y+. Use `--normal-format directx` for a Y− source or `--normal-format opengl` for Y+. OpenPBR scalar and normal inputs require linear data. Height becomes signed EXR displacement in scene units using `(height - 0.5) × displacementScale`. The CLI accepts `--displacement-scale`. MaterialX texture filenames include a hash of the output name and bytes. Re-export writes the document last and keeps earlier texture versions, so a failed export leaves the previous material usable. Outputs without an OpenPBR connection are written alongside the document and listed in `unmapped`.
|
||||
|
||||
The named profiles choose their own file names and formats. Use `--format` and `--pattern` with plain image export. `--normal-format` applies to both named profiles, and `--displacement-scale` applies to MaterialX. Profile EXR files are linear. Leave the color space automatic, or choose linear or raw explicitly.
|
||||
|
||||
| Command | Params |
|
||||
|---|---|
|
||||
| `file.exportMaterial` | `{path, graph?}` publishes the chosen source graph by SBS path or index. The default is the open graph. |
|
||||
@@ -400,6 +401,7 @@ dialog or prompt blocks it. `package_open` opens `.mcmat` files
|
||||
too. `material_export` accepts `{path, graph?}` and publishes below the write root. Use
|
||||
`outputs_export` to bake variations with `profile`, `size`, `preset`, `values` and `inputs`.
|
||||
Image paths are relative to the read root and the destination is relative to the write root.
|
||||
Workspace publication limits both the combined uncompressed assets and the final archive to 256 MiB.
|
||||
|
||||
While an FX-Map subgraph is open, `ui.inspect.subgraph` identifies its owner and selection. Canvas
|
||||
node IDs and ports refer to that embedded graph. `ui.menu.invoke` with `ui.graph.parent` returns
|
||||
|
||||
Reference in new issue
Block a user