@@ -92,7 +95,8 @@
## Made in MaterialCraft
-Every material below is a node graph that ships with MaterialCraft as a template, built only from
+These historical renders used the former Rust library and are no longer bundled as templates.
+They were built from
its own procedural nodes (no photos, scans or textures from anywhere else) and rendered by
`materialcraft-cli render --scene sphere --full --hq` (the height output displaces the mesh, with
ray-traced ambient occlusion and a shadowed key light).
@@ -110,12 +114,12 @@ ray-traced ambient occlusion and a shadowed key light).
histogram of its input, see [docs/levels-editor.md](docs/levels-editor.md)). Space opens the
node search.
- **Fast.** Every node cooks on every CPU core, and a content-addressed cache means an edit
- re-cooks only what lies downstream: the brick wall sample cooks in about 40 ms at preview size.
+ re-cooks only what lies downstream.
Cooking runs on a worker thread, so the UI never waits.
- **Tileable by design.** Noises and patterns live on whole-number lattices, so everything tiles
seamlessly at any resolution, from 16 px to 8K.
- **Robust.** No panics in shipped code, every command tested with hostile input, every node cooked
- with odd inputs in tests, unlimited undo from snapshots, and lossless project files.
+ with odd inputs in tests, undo from snapshots, and native SBS project files.
- **Open.** Export base color, normal, roughness, metallic, height and ambient occlusion as PNG,
JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with your own file name pattern.
- **Works with TextureCraft.** **File ▸ Send to TextureCraft** puts a material on TextureCraft's
@@ -134,7 +138,7 @@ git clone https://github.com/storytold/materialcraft
cd materialcraft
cargo run --release -p materialcraft # desktop app
-cargo run --release -p materialcraft -- package.sbs # open a package (.sbs or .mcraft)
+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
@@ -170,21 +174,12 @@ The details are in [`docs/control-protocol.md`](docs/control-protocol.md).
MaterialCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the parity estimate by
area, the remaining work and what's next.
-**Where we are (2026-11-02):** the node engine and 227 nodes (the atomic nodes including FX-Map,
-SVG and Text, noises including tileable 3D ones, patterns, filters, the flood fill family,
-whole-material blending and weathering), function graphs with a visual editor and dynamic
-parameters, sub-graphs with exposed inputs and presets, the full editor (graph, library,
-properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes, alpha transparency and an
-alpha channel view; wires you can select, delete, swap (X) and reroute with dots, see
-[docs/wires-and-alpha.md](docs/wires-and-alpha.md)), SBS project files (`.mcraft` too),
-texture export, portable `.mcmat` materials that TextureCraft paints with (inputs stay editable
-there), the browser build with file I/O, the CLI, the control channel and the MCP server
-all work today. We estimate about two thirds (≈ 67%) of a material artist's daily workflow works
-end to end; [docs/target-app-parity.md](docs/target-app-parity.md) has the breakdown.
+**Current focus (2026-11-05):** primitive editing and native SBS save/load. The old Rust
+procedural library has been removed. The replacement includes 30 main-graph entries, 85 function
+operations and three pattern node kinds. Start with **File → New → Atomic sample**.
-**What's missing:** the rest of the node library, a GPU 3D view with tessellation and lights,
-mesh-based nodes, translations and the first signed release. The ranked list is in
-[`docs/gaps.md`](docs/gaps.md).
+See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scope and limitations.
+Reference-app rendering parity and full SBS library loading are still pending.
**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}`
and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own
diff --git a/ROADMAP.md b/ROADMAP.md
index 9a58e922..0e97d7b7 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,46 +1,20 @@
# MaterialCraft roadmap
-> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (≈ 67%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow
+**Current focus (2026-11-05):** native primitive editing, evaluation and SBS save/load.
-**Stage:** alpha (in active development). MaterialCraft aims for full parity with the professional
-node-based procedural material workflow, with better performance, every feature drivable by agents
-(MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web.
+The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native
+primitives and four graph input/output items. Functions have 85 operations; pattern graphs have
+Quadrant, Switch, Iterate and Dot. See [the primitive workflow](docs/atomic-workflow.md) for usage and limits.
-## Headline numbers
+Earlier percentage estimates and node counts are superseded by this change. Reference-app
+rendering parity and arbitrary SBS round trips have not been established.
-- **Parity: ≈ 67%** of a material artist's daily workflow works end to end
- ([docs/target-app-parity.md](docs/target-app-parity.md)).
-- **Remaining: ≈ 83 Opus 5.5 agent hours** ([docs/roadmap.md](docs/roadmap.md)).
-- **Nodes:** 227 (all tileable), cooked on every CPU core through a content-addressed cache; the
- brick wall sample cooks in about 40 ms at preview size.
+## Next steps
-## By area
-
-| Area | Weight | Done |
-|---|---:|---:|
-| Graph editing | 15 | 75% |
-| Atomic nodes | 12 | 95% |
-| Node library | 20 | 45% |
-| Function graphs | 10 | 70% |
-| Graph parameters and instances | 8 | 70% |
-| 2D view | 5 | 80% |
-| 3D view | 10 | 55% |
-| Files | 8 | 70% |
-| UI and UX | 8 | 70% |
-| Platforms | 4 | 50% |
-| **Total** | **100** | **≈ 67%** |
-
-## What's next
-
-1. The rest of the node library: scan processing, more grunges, spline tools, SDF shapes.
-2. A GPU 3D view with tessellation and lights.
-3. Mesh-based generators and bakers.
-4. Function loops and reusable functions.
-5. The first release on every platform.
-
-The ranked work list is [docs/gaps.md](docs/gaps.md); file formats are in
-[docs/file-format-parity.md](docs/file-format-parity.md) and languages in
-[docs/localization-parity.md](docs/localization-parity.md).
+1. Verify the original atomic sample in the reference application
+2. Compare primitive outputs and parameter semantics against reference results
+3. Add SBS graph references with cycle-safe resolution
+4. Build the library from SBS definitions instead of duplicate Rust nodes
## Progress log
diff --git a/UI_PARITY_NOTES.md b/UI_PARITY_NOTES.md
index e8912620..5bc67dbb 100644
--- a/UI_PARITY_NOTES.md
+++ b/UI_PARITY_NOTES.md
@@ -1,7 +1,33 @@
-# UI parity drop (branch 123-improving-ui)
+# UI parity drop (re-based on main after the primitive rewrite)
What changed, per area of the reference screenshots. Everything is wired to the engine; no empty settings.
+## Re-port onto main (2026-11-06)
+- Built on `origin/main` (1a468e7, PR #125). Everything from the 123-improving-ui drop was re-applied in the new
+ layout: one type per file, new engine commands in their own module (`engine/src/resource_cmds.rs`, registered by
+ one line in `commands.rs`), 3D view settings in `engine/src/view3d_settings.rs`, the 3D view split into
+ `ui-egui/src/view3d/{actions,menus,overlays,settings,side_strip}.rs`, the explorer actions in `explorer/{actions,package_menu}.rs`,
+ the new-graph dialog in `new_graph_dialog.rs`, graph toolbar tools in `graph/toolbar_tools.rs`, auto conversion in `graph/auto_convert.rs`.
+- Upstream features kept as they are: the material-preview assignment (View in 3D view, graph drop onto the 3D view,
+ `view.3d.outputs`, `view.3d.clear`), the Material assignment list now lives at the bottom of the 3D view's Materials menu;
+ the function and FX-Map pattern editors; `snapToGrid` from `prefs.snap_to_grid`.
+- `.mcraft` is gone upstream, so everything here is SBS only: linked bitmaps are written as `` without `binembedded`,
+ plugins load `.sbs` packages, the Plugin Manager installs `.sbs` files.
+- Library: the reference's generator/filter groups are no longer Rust nodes ("SBS library nodes belong in SBS graphs"), so
+ the library shows the 26 atomic nodes, graph items, the 85 function ops (added through the function editor), the package's
+ graphs by kind, and the graphs of loaded plugin packages filed under each graph's `attributes.category` (else "PBR materials ▸ Plugins").
+ The remaining reference groups stay listed, greyed, with a 0 count.
+
+## Menu pass (2026-11-06, late)
+- Library: the "SDF functions" group is now "MCF functions"; empty reference groups explain on hover that library
+ packages (Tools ▸ Plugin Manager) fill them.
+- Help menu points at getartcraft.com: Documentation/website → the MaterialCraft app page, Tutorials → /tutorials,
+ What's new → /news, System requirements → /faq, Support and feedback → /support, Discord; release notes and bug
+ reports stay on GitHub. Home and About carry the same links.
+- Home screen: Samples shows the starter templates and the graphs of loaded library packages (click imports the graph).
+- Graph toolbar quick-insert row now has every atomic node (added SVG, Text, Gradient Dynamic, Motion Blur,
+ Value Processor, Input Color, Input Value).
+
## Menus (File / Edit / Tools / Windows / Help)
- File: New ▸ Graph / Empty package, Open, Recent, Save, Save as, Save a copy as, Export with dependencies, Import bitmap, Link bitmap, Export outputs, Export material, Send to TextureCraft, Close, Quit.
- Tools: Switch engine (F9: CPU thread count, rayon pool), Cancel rendering, Suspend engine, Clear cache, Reload resources, Plugin Manager.
@@ -45,11 +71,13 @@ What changed, per area of the reference screenshots. Everything is wired to the
- Skipped on purpose: UDIM, .sbsar publishing.
## Plugin Manager (Tools ▸ Plugin Manager)
-- Filter, Plugins/Loaded table, Browse (opens the plugins folder), Install (copies .sbs/.mcraft files in), Refresh.
+- Filter, Plugins/Loaded table, Browse (opens the plugins folder), Install (copies .sbs files in), Refresh.
- A plugin = a package file or a folder with package files + optional plugin.json {name, version, author, description} in Documents/MaterialCraft/plugins. Loaded plugins' graphs show in the library under PBR materials ▸ Plugins.
## Engine commands added
file.linkBitmap, file.reloadResources, file.deleteResource, file.importGraph, file.packageGraphs, file.saveCopy, file.exportWithDependencies, graph.add, session.settings, view.3d.reset {what}, view.3d.state, view.3d.loadState; `view.3d` nested objects. Resources can be linked (SBS keeps relative links).
## Checks run here
-cargo fmt, cargo clippy --workspace --all-targets -D warnings, cargo xtask layers, cargo test --workspace --release, cargo xtask wasm.
+cargo fmt --all, cargo check --workspace --all-targets, cargo clippy --workspace --all-targets -- -D warnings, cargo xtask layers,
+cargo test --workspace --release --no-fail-fast. `cargo xtask wasm` could not run in this container (the wasm target cannot be
+downloaded here); please run it on your side.
diff --git a/crates/automation/src/server.rs b/_to_delete/automation_server.rs
similarity index 100%
rename from crates/automation/src/server.rs
rename to _to_delete/automation_server.rs
diff --git a/crates/core/src/function.rs b/_to_delete/core_function.rs
similarity index 100%
rename from crates/core/src/function.rs
rename to _to_delete/core_function.rs
diff --git a/crates/formats/src/material.rs b/_to_delete/formats_material.rs
similarity index 100%
rename from crates/formats/src/material.rs
rename to _to_delete/formats_material.rs
diff --git a/crates/formats/src/sbs.rs b/_to_delete/formats_sbs.rs
similarity index 100%
rename from crates/formats/src/sbs.rs
rename to _to_delete/formats_sbs.rs
diff --git a/crates/formats/src/sbs_functions.rs b/_to_delete/formats_sbs_functions.rs
similarity index 100%
rename from crates/formats/src/sbs_functions.rs
rename to _to_delete/formats_sbs_functions.rs
diff --git a/crates/formats/tests/sbs_functions.rs b/_to_delete/formats_tests_sbs_functions.rs
similarity index 100%
rename from crates/formats/tests/sbs_functions.rs
rename to _to_delete/formats_tests_sbs_functions.rs
diff --git a/crates/formats/tests/sbs_library_aliases.rs b/_to_delete/formats_tests_sbs_library_aliases.rs
similarity index 100%
rename from crates/formats/tests/sbs_library_aliases.rs
rename to _to_delete/formats_tests_sbs_library_aliases.rs
diff --git a/crates/nodes/src/atomic.rs b/_to_delete/nodes_atomic.rs
similarity index 100%
rename from crates/nodes/src/atomic.rs
rename to _to_delete/nodes_atomic.rs
diff --git a/crates/nodes/src/catalog.test.rs b/_to_delete/nodes_catalog.test.rs
similarity index 100%
rename from crates/nodes/src/catalog.test.rs
rename to _to_delete/nodes_catalog.test.rs
diff --git a/crates/nodes/src/filters.rs b/_to_delete/nodes_filters.rs
similarity index 100%
rename from crates/nodes/src/filters.rs
rename to _to_delete/nodes_filters.rs
diff --git a/crates/nodes/src/filters.test.rs b/_to_delete/nodes_filters.test.rs
similarity index 100%
rename from crates/nodes/src/filters.test.rs
rename to _to_delete/nodes_filters.test.rs
diff --git a/crates/nodes/src/filters_extra.rs b/_to_delete/nodes_filters_extra.rs
similarity index 100%
rename from crates/nodes/src/filters_extra.rs
rename to _to_delete/nodes_filters_extra.rs
diff --git a/crates/nodes/src/filters_more.rs b/_to_delete/nodes_filters_more.rs
similarity index 100%
rename from crates/nodes/src/filters_more.rs
rename to _to_delete/nodes_filters_more.rs
diff --git a/crates/nodes/src/flood_fill.rs b/_to_delete/nodes_flood_fill.rs
similarity index 100%
rename from crates/nodes/src/flood_fill.rs
rename to _to_delete/nodes_flood_fill.rs
diff --git a/crates/nodes/src/function.rs b/_to_delete/nodes_function.rs
similarity index 100%
rename from crates/nodes/src/function.rs
rename to _to_delete/nodes_function.rs
diff --git a/crates/nodes/src/fx_map.rs b/_to_delete/nodes_fx_map.rs
similarity index 100%
rename from crates/nodes/src/fx_map.rs
rename to _to_delete/nodes_fx_map.rs
diff --git a/crates/nodes/src/generators.rs b/_to_delete/nodes_generators.rs
similarity index 100%
rename from crates/nodes/src/generators.rs
rename to _to_delete/nodes_generators.rs
diff --git a/crates/nodes/src/generators.test.rs b/_to_delete/nodes_generators.test.rs
similarity index 100%
rename from crates/nodes/src/generators.test.rs
rename to _to_delete/nodes_generators.test.rs
diff --git a/crates/nodes/src/material.rs b/_to_delete/nodes_material.rs
similarity index 100%
rename from crates/nodes/src/material.rs
rename to _to_delete/nodes_material.rs
diff --git a/crates/nodes/src/material_more.rs b/_to_delete/nodes_material_more.rs
similarity index 100%
rename from crates/nodes/src/material_more.rs
rename to _to_delete/nodes_material_more.rs
diff --git a/crates/nodes/src/noise.rs b/_to_delete/nodes_noise.rs
similarity index 100%
rename from crates/nodes/src/noise.rs
rename to _to_delete/nodes_noise.rs
diff --git a/crates/nodes/src/noise3d.rs b/_to_delete/nodes_noise3d.rs
similarity index 100%
rename from crates/nodes/src/noise3d.rs
rename to _to_delete/nodes_noise3d.rs
diff --git a/crates/nodes/src/noises_more.rs b/_to_delete/nodes_noises_more.rs
similarity index 100%
rename from crates/nodes/src/noises_more.rs
rename to _to_delete/nodes_noises_more.rs
diff --git a/crates/nodes/src/patterns.rs b/_to_delete/nodes_patterns.rs
similarity index 100%
rename from crates/nodes/src/patterns.rs
rename to _to_delete/nodes_patterns.rs
diff --git a/crates/nodes/src/patterns.test.rs b/_to_delete/nodes_patterns.test.rs
similarity index 100%
rename from crates/nodes/src/patterns.test.rs
rename to _to_delete/nodes_patterns.test.rs
diff --git a/crates/nodes/src/patterns_more.rs b/_to_delete/nodes_patterns_more.rs
similarity index 100%
rename from crates/nodes/src/patterns_more.rs
rename to _to_delete/nodes_patterns_more.rs
diff --git a/crates/nodes/src/svg.rs b/_to_delete/nodes_svg.rs
similarity index 100%
rename from crates/nodes/src/svg.rs
rename to _to_delete/nodes_svg.rs
diff --git a/crates/nodes/src/text.rs b/_to_delete/nodes_text.rs
similarity index 100%
rename from crates/nodes/src/text.rs
rename to _to_delete/nodes_text.rs
diff --git a/crates/nodes/src/weathering.rs b/_to_delete/nodes_weathering.rs
similarity index 100%
rename from crates/nodes/src/weathering.rs
rename to _to_delete/nodes_weathering.rs
diff --git a/crates/nodes/src/weathering.test.rs b/_to_delete/nodes_weathering.test.rs
similarity index 100%
rename from crates/nodes/src/weathering.test.rs
rename to _to_delete/nodes_weathering.test.rs
diff --git a/_to_delete/ui-parity-main-port.zip b/_to_delete/ui-parity-main-port.zip
new file mode 100644
index 00000000..3ff3f8eb
Binary files /dev/null and b/_to_delete/ui-parity-main-port.zip differ
diff --git a/crates/ui-egui/src/function_editor.rs b/_to_delete/ui_function_editor.rs
similarity index 100%
rename from crates/ui-egui/src/function_editor.rs
rename to _to_delete/ui_function_editor.rs
diff --git a/crates/ui-egui/src/graph_view.rs b/_to_delete/ui_graph_view.rs
similarity index 100%
rename from crates/ui-egui/src/graph_view.rs
rename to _to_delete/ui_graph_view.rs
diff --git a/crates/ui-egui/src/lib.test.rs b/_to_delete/ui_lib.test.rs
similarity index 100%
rename from crates/ui-egui/src/lib.test.rs
rename to _to_delete/ui_lib.test.rs
diff --git a/crates/ui-egui/src/properties.rs b/_to_delete/ui_properties.rs
similarity index 100%
rename from crates/ui-egui/src/properties.rs
rename to _to_delete/ui_properties.rs
diff --git a/crates/ui-egui/src/state.rs b/_to_delete/ui_state.rs
similarity index 100%
rename from crates/ui-egui/src/state.rs
rename to _to_delete/ui_state.rs
diff --git a/crates/ui-egui/tests/common/search.rs b/_to_delete/ui_tests_common_search.rs
similarity index 100%
rename from crates/ui-egui/tests/common/search.rs
rename to _to_delete/ui_tests_common_search.rs
diff --git a/crates/ui-egui/tests/search_query.rs b/_to_delete/ui_tests_search_query.rs
similarity index 100%
rename from crates/ui-egui/tests/search_query.rs
rename to _to_delete/ui_tests_search_query.rs
diff --git a/crates/ui-egui/tests/search_rows.rs b/_to_delete/ui_tests_search_rows.rs
similarity index 100%
rename from crates/ui-egui/tests/search_rows.rs
rename to _to_delete/ui_tests_search_rows.rs
diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs
index 5cef46d0..fa7a15ef 100644
--- a/apps/materialcraft-cli/src/main.rs
+++ b/apps/materialcraft-cli/src/main.rs
@@ -1,12 +1,11 @@
-//! Headless MaterialCraft command line: inspect, script, cook, export and render packages, and
-//! serve agents over MCP or JSON lines. Never opens a window.
+//! Headless MaterialCraft command line: inspect, script, cook, export and render packages, and serve agents over MCP or JSON lines. Never opens a window
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::sync::{Arc, Mutex};
use materialcraft_automation::security::{client_token, server_token};
-use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialcraftMcp, RenderOptions, rpc};
+use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialCraftMcp, RenderOptions, rpc};
use serde_json::{Value, json};
const USAGE: &str = "\
@@ -14,7 +13,7 @@ materialcraft-cli: headless MaterialCraft
USAGE:
materialcraft-cli --version
- materialcraft-cli info
+ materialcraft-cli info
Graphs, nodes, outputs and cook results, as JSON.
materialcraft-cli commands [--filter ]
List the engine commands (id, label, params).
@@ -25,8 +24,7 @@ USAGE:
materialcraft-cli batch
Run [{\"id\", \"params\"}, ...] or {\"open\": , \"steps\": [...], \"save\": }.
materialcraft-cli new [--size ] [--name ]
- A new package with one graph from a template (empty, pbr, bricks, stone_tiles, wood,
- metal_plates, rusty_metal, lava, marble, wicker, fabric, ground).
+ A new package with one graph from a template (empty, pbr, atomics).
materialcraft-cli cook [--graph ] [--set =]... [--full]
Cook a graph and print per-node timings and errors.
materialcraft-cli export [--graph ] [--set =]... [--format ]
@@ -45,8 +43,7 @@ USAGE:
materialcraft-cli serve [--port ] [--read-root ] [--write-root ]
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token.
- is an .sbs or .mcraft package or `sample` (the built-in brick wall). Packages save as SBS
-unless the output path ends in .mcraft. --set gives a graph input a value
+ is an .sbs package or `sample` (the built-in atomic sample). Packages save as native SBS. --set gives a graph input a value
(JSON, e.g. `--set roughness=0.4 --set tint=\"#aa7744\"`) before cooking. See docs/control-protocol.md.
";
@@ -120,7 +117,7 @@ fn version() -> String {
}
}
-/// A headless session on `input` (an .sbs or .mcraft package, or `sample`), with local file access.
+/// A headless session on `input` (an .sbs package, or `sample`), with local file access
fn open(input: &str) -> Result {
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
if input != "sample" {
@@ -133,7 +130,7 @@ fn print(v: &Value) {
println!("{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}")));
}
-/// Open `--graph` and apply every `--set =` (the value is JSON, else a string).
+/// Open `--graph` and apply every `--set =` (the value is JSON, else a string)
fn select_graph(h: &mut Headless, a: &Args) -> Result<(), String> {
if let Some(g) = a.num::("--graph")? {
h.command_run("graph.open", json!({"graph": g})).map_err(|e| e.to_string())?;
@@ -189,6 +186,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
Some(p) => serde_json::from_str(p).map_err(|e| format!("params: {e}"))?,
None => Value::Null,
};
+
print(&h.command_run(id, params).map_err(|e| e.to_string())?);
if let Some(out) = a.get("-o") {
h.save(Some(out)).map_err(|e| e.to_string())?;
@@ -205,6 +203,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
obj.get("save").and_then(Value::as_str),
),
};
+
let mut h = open(input)?;
let r = h.batch(&steps);
print(&r);
@@ -248,6 +247,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
}
None => (None, None),
};
+
let o = RenderOptions {
view: a.get("--view").map(str::to_string),
width: w,
@@ -262,6 +262,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
hq: a.has("--hq"),
displacement: a.num("--displacement")?,
};
+
let r = h.render_png(&o).map_err(|e| e.to_string())?;
materialcraft_engine::formats::write_atomic(std::path::Path::new(out), &r.png).map_err(|e| e.to_string())?;
print(&json!({"path": out, "width": r.width, "height": r.height}));
@@ -271,18 +272,18 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let server = match a.num::("--bridge")? {
Some(port) => {
let token = client_token(port, a.get("--token").map(str::to_string)).map_err(|e| e.to_string())?;
- MaterialcraftMcp::bridge(BridgeClient::new(port, token))
+ MaterialCraftMcp::bridge(BridgeClient::new(port, token))
}
- None => MaterialcraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)),
+ None => MaterialCraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)),
};
+
rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())?;
}
"serve" => {
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?)));
match a.num::("--port")? {
Some(port) => {
- // Bind first: a port in use must not replace its server's token file, and port 0's
- // token file is named after the port actually picked.
+ // Bind first: a port in use must not replace its server's token file, and port 0's token file is named after the port actually picked
let listener = rpc::bind_tcp(port).map_err(|e| e.to_string())?;
let addr = listener.local_addr().map_err(|e| e.to_string())?;
let (token, file) = server_token(addr.port()).map_err(|e| e.to_string())?;
@@ -300,7 +301,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
Ok(())
}
-/// File access for servers: none without roots, else only below them.
+/// File access for servers: none without roots, else only below them
fn workspace(a: &Args) -> Result {
let (r, w) = (a.get("--read-root"), a.get("--write-root"));
if r.is_none() && w.is_none() {
diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs
index b3e9e348..37dec33d 100644
--- a/apps/materialcraft/src/main.rs
+++ b/apps/materialcraft/src/main.rs
@@ -1,6 +1,5 @@
-//! MaterialCraft desktop app.
-//!
-//! Usage: `materialcraft [package.sbs|package.mcraft] [--control ] [--empty] [--version]`
+//! MaterialCraft desktop app
+//! Usage: `materialcraft [package.sbs] [--control ] [--empty] [--version]`
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -39,14 +38,14 @@ fn parse_args() -> Result, String> {
return Ok(None);
}
"--help" | "-h" => {
- println!("{}\n\nUsage: materialcraft [package.sbs|package.mcraft] [--control ] [--empty]", version());
+ println!("{}\n\nUsage: materialcraft [package.sbs] [--control ] [--empty]", version());
return Ok(None);
}
"--control" => {
let p = it.next().ok_or("--control needs a port")?;
args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?);
}
- // Kept for scripts written before empty startup became the default.
+ // Kept for scripts written before empty startup became the default
"--empty" => {}
f if !f.starts_with('-') => args.file = Some(f.to_string()),
other => return Err(format!("unknown option `{other}`")),
@@ -81,6 +80,7 @@ fn main() {
std::process::exit(2);
}
};
+
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
eprintln!("materialcraft: internal error: {info}");
@@ -91,8 +91,7 @@ fn main() {
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
- // Scripted runs (agents, tests) set MATERIALCRAFT_NO_PREFS so they neither read nor overwrite
- // the user's saved layout and settings: state goes to a throwaway file.
+ // Scripted runs (agents, tests) set MATERIALCRAFT_NO_PREFS so they neither read nor overwrite the user's saved layout and settings: state goes to a throwaway file
let persistence_path =
std::env::var_os("MATERIALCRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("materialcraft-noprefs-{}.ron", std::process::id())));
let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
@@ -136,11 +135,13 @@ mod tests {
#[test]
fn startup_opens_the_requested_package() {
- let path = std::env::temp_dir().join(format!("mc-startup-{}.mcraft", std::process::id()));
+ let path = std::env::temp_dir().join(format!("mc-startup-{}.sbs", std::process::id()));
let original = materialcraft_engine::sample_session();
std::fs::write(&path, materialcraft_engine::file_cmds::save_bytes(&original).unwrap()).unwrap();
let s = initial_session(&Args { file: Some(path.to_string_lossy().into_owned()), control: None });
- assert_eq!(s.pkg.graphs, original.pkg.graphs);
+ assert_eq!(s.pkg.graphs.len(), original.pkg.graphs.len());
+ assert_eq!(s.pkg.graphs[0].name, original.pkg.graphs[0].name);
+ assert_eq!(materialcraft_engine::file_cmds::save_bytes(&s).unwrap(), materialcraft_engine::file_cmds::save_bytes(&original).unwrap());
assert_eq!(s.path.as_deref(), path.to_str());
assert!(!s.modified);
std::fs::remove_file(path).unwrap();
diff --git a/crates/automation/src/automation_error.rs b/crates/automation/src/automation_error.rs
new file mode 100644
index 00000000..93c71197
--- /dev/null
+++ b/crates/automation/src/automation_error.rs
@@ -0,0 +1,19 @@
+#[derive(Debug, thiserror::Error)]
+pub enum AutomationError {
+ #[error("{0}")]
+ BadRequest(String),
+ #[error("I/O: {0}")]
+ Io(String),
+ #[error(transparent)]
+ Engine(#[from] materialcraft_engine::EngineError),
+ #[error("bridge: {0}")]
+ Bridge(String),
+ #[error("app: {0}")]
+ App(String),
+ #[error("{0}")]
+ Other(String),
+}
+
+pub(crate) fn bad(msg: impl Into) -> AutomationError {
+ AutomationError::BadRequest(msg.into())
+}
diff --git a/crates/automation/src/filesystem.rs b/crates/automation/src/filesystem.rs
new file mode 100644
index 00000000..7e2054ec
--- /dev/null
+++ b/crates/automation/src/filesystem.rs
@@ -0,0 +1,10 @@
+use crate::AuthorizedWorkspace;
+/// Where file paths given to [`crate::Headless`] may point
+pub enum Filesystem {
+ /// No file access (an MCP server started without roots)
+ Denied,
+ /// Host paths as given: the local CLI user typed them
+ TrustedLocal,
+ /// Relative paths under the authorized roots (remote or agent callers)
+ Workspace(AuthorizedWorkspace),
+}
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 66a1373a..20ef2589 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -1,5 +1,4 @@
-//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and
-//! UI-free; the MCP server, the RPC server and the CLI all drive it.
+//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and UI-free; the MCP server, the RPC server and the CLI all drive it
use std::path::Path;
@@ -11,50 +10,8 @@ use serde_json::{Value, json};
use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png};
use crate::workspace::{MAX_READ_BYTES, authorize_command};
-use crate::{AuthorizedWorkspace, AutomationError, bad};
-
-/// Where file paths given to [`Headless`] may point.
-pub enum Filesystem {
- /// No file access (an MCP server started without roots).
- Denied,
- /// Host paths as given: the local CLI user typed them.
- TrustedLocal,
- /// Relative paths under the authorized roots (remote or agent callers).
- Workspace(AuthorizedWorkspace),
-}
-
-/// What [`Headless::render_png`] draws.
-#[derive(Clone, Debug, Default)]
-pub struct RenderOptions {
- /// `3d` (default) or `2d` (a node's output; the 2D view's node by default).
- pub view: Option,
- pub width: Option,
- pub height: Option,
- /// Camera overrides in degrees (the session's view is not changed).
- pub yaw: Option,
- pub pitch: Option,
- /// 3D scene override (`rounded_cube`, `sphere`, …).
- pub scene: Option,
- /// 2D: the node whose output to show.
- pub node: Option,
- /// 2D: the output port.
- pub port: Option,
- /// Cook at full size instead of the preview size.
- pub full: bool,
- /// 3D: UV repeats override (the session's view is not changed).
- pub tiling: Option,
- /// 3D: beauty render: a finer displaced mesh, ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling.
- pub hq: bool,
- /// 3D, with `hq`: displacement depth in scene radii (default: the view's height depth).
- pub displacement: Option,
-}
-
-/// A PNG render.
-pub struct Rendered {
- pub width: u32,
- pub height: u32,
- pub png: Vec,
-}
+use crate::{AutomationError, bad};
+pub use crate::{Filesystem, RenderOptions, Rendered};
pub struct Headless {
pub session: Session,
@@ -63,7 +20,7 @@ pub struct Headless {
light: Option,
}
-/// Read a file under `fs`'s access rules.
+/// Read a file under `fs`'s access rules
fn read_file(fs: &Filesystem, path: &str) -> Result, AutomationError> {
match fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root ")),
@@ -83,7 +40,7 @@ impl Headless {
Headless { session, fs, scene: None, light: None }
}
- /// The session a fresh server starts with: the brick wall sample.
+ /// The session a fresh server starts with: the atomic sample
pub fn default_session() -> Session {
materialcraft_engine::sample_session()
}
@@ -122,19 +79,15 @@ impl Headless {
commands::list(&self.session, filter)
}
- /// Run an engine command. Untrusted callers can't reach host paths through it.
+ /// Run an engine command. Untrusted callers can't reach host paths through it
pub fn command_run(&mut self, id: &str, params: Value) -> Result {
if !self.trusted() {
authorize_command(id, ¶ms)?;
}
- // Each request is its own undo step, never merged with a neighbour's.
- self.session.end_merge();
- let r = materialcraft_engine::execute(&mut self.session, id, ¶ms);
- self.session.end_merge();
- Ok(r?)
+ Ok(materialcraft_engine::commands::execute_request(&mut self.session, id, ¶ms)?)
}
- /// Run `[{id, params?}]` in order, stopping at the first error (reported with its index).
+ /// Run `[{id, params?}]` in order, stopping at the first error (reported with its index)
pub fn batch(&mut self, steps: &[Value]) -> Value {
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
@@ -147,7 +100,7 @@ impl Headless {
batch_reply(results, None)
}
- /// Open an `.sbs` or `.mcraft` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules.
+ /// Open an `.sbs` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules
pub fn open(&mut self, path: &str) -> Result {
let bytes = self.read(path)?;
let folder = path.replace('\\', "/").rsplit_once('/').map(|(folder, _)| format!("{folder}/")).unwrap_or_default();
@@ -166,21 +119,21 @@ impl Headless {
Ok(self.inspect())
}
- /// Save to `path` (`.sbs` appended without a package extension) or the package's own file; SBS unless it is a `.mcraft`.
+ /// Save to `path` (`.sbs` appended without a package extension) or the package's own file; native SBS
pub fn save(&mut self, path: Option<&str>) -> Result {
let path = match path {
Some(p) => file_cmds::package_path(p),
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 bytes = file_cmds::save_bytes_as(&self.session, file_cmds::PackageFormat::of_path(&path))?;
+ let bytes = file_cmds::save_bytes(&self.session)?;
self.write(&path, &bytes)?;
self.session.path = Some(path.clone());
self.session.modified = false;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
- /// Embed an image file as a bitmap resource.
+ /// Embed an image file as a bitmap resource
pub fn import_bitmap(&mut self, path: &str, name: Option<&str>) -> Result {
let bytes = self.read(path)?;
let file = Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string();
@@ -188,7 +141,7 @@ impl Headless {
Ok(json!({"name": name}))
}
- /// Export every output of a graph into folder `dir`.
+ /// Export every output of a graph into folder `dir`
pub fn export(&mut self, p: &Value) -> Result {
let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("`dir` is required"))?;
let (gi, ext, pattern, depth, size) = file_cmds::export_params(&self.session, p)?;
@@ -203,9 +156,7 @@ impl Headless {
Ok(json!({"files": written}))
}
- /// Cook a graph and write it as a portable `.mcmat` material (`.mcmat` appended when
- /// missing) to `path`: `{path, graph?, size?, values?}`, the workspace-scoped
- /// `file.exportMaterial`. The file is capped at what `package_open` may read back.
+ /// Export a portable material below the granted write root
pub fn export_material(&mut self, p: &Value) -> Result {
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
@@ -223,7 +174,7 @@ impl Headless {
Ok(json!({"path": path, "bytes": bytes.len()}))
}
- /// Render the 3D view or a node's 2D output as PNG.
+ /// Render the assigned material or a node output as PNG
pub fn render_png(&mut self, o: &RenderOptions) -> Result {
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
let saved = self.session.preview_size;
@@ -237,6 +188,7 @@ impl Headless {
"3d" => Ok(self.render_3d(o, max)),
other => Err(bad(format!("unknown view `{other}` (3d or 2d)"))),
};
+
if o.full {
self.session.preview_size = saved;
self.session.dirty = true;
@@ -252,6 +204,7 @@ impl Headless {
Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?,
};
+
let (w, h) = (o.width.unwrap_or(img.w).clamp(16, max), o.height.unwrap_or(img.h).clamp(16, max));
let img = img.resize(w, h, true);
Ok((w, h, img.to_rgba8_display()))
@@ -267,6 +220,7 @@ impl Headless {
Some((_, mesh)) => Scene::new((*mesh).clone()),
None => Scene::builtin(&scene_id),
};
+
self.scene = Some((key, scene));
}
if self.light.as_ref().is_none_or(|l| l.name != v.environment) {
@@ -290,6 +244,7 @@ impl Headless {
alpha_view: v.alpha_view,
..Settings::default()
};
+
let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max));
let maps = Maps::from_usages(self.session.material_maps());
let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) };
diff --git a/crates/automation/src/headless.test.rs b/crates/automation/src/headless.test.rs
index dd39c1d5..4d9ee590 100644
--- a/crates/automation/src/headless.test.rs
+++ b/crates/automation/src/headless.test.rs
@@ -9,8 +9,8 @@ mod end_merge_tests {
h.command_run("file.new", json!({"template": "empty"})).unwrap();
let id = h.command_run("graph.node.add", json!({"def": "levels"})).unwrap()["id"].as_u64().unwrap();
let sets = |h: &Headless| h.session.history().iter().filter(|l| *l == "Set parameter").count();
- h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": 0.3})).unwrap();
- h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": 0.4})).unwrap();
+ h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": [0.3, 0.3, 0.3, 0.3]})).unwrap();
+ h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": [0.4, 0.4, 0.4, 0.4]})).unwrap();
assert_eq!(sets(&h), 2, "separate requests must not merge");
}
}
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index d50b55de..56aa9f44 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -1,16 +1,3 @@
-//! # materialcraft-automation
-//!
-//! Agent-facing automation, L4 (no UI toolkit):
-//!
-//! * [`MaterialcraftMcp`]: an MCP server (official `rmcp` SDK). Headless mode drives an
-//! in-process [`Headless`] session; bridge mode forwards to a running desktop app over the
-//! JSON-lines control channel (`docs/control-protocol.md`).
-//! * [`Headless`]: a [`materialcraft_engine::Session`] plus file I/O through an
-//! [`AuthorizedWorkspace`] and windowless renders. Shared by the MCP server, the RPC server
-//! and `materialcraft-cli`.
-//! * [`rpc`]: the control channel's methods (plus `render`) over stdio or loopback TCP, used by
-//! `materialcraft-cli serve`.
-//! * [`BridgeClient`]: the client side of the app's control channel.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -23,26 +10,16 @@ pub mod server;
pub mod workspace;
pub use bridge::BridgeClient;
-pub use headless::{Filesystem, Headless, RenderOptions};
-pub use server::{Backend, MaterialcraftMcp};
+mod filesystem;
+mod render_options;
+mod rendered;
+pub use filesystem::Filesystem;
+pub use headless::Headless;
+pub use render_options::RenderOptions;
+pub use rendered::Rendered;
+pub use server::{Backend, MaterialCraftMcp};
pub use workspace::AuthorizedWorkspace;
-#[derive(Debug, thiserror::Error)]
-pub enum AutomationError {
- #[error("{0}")]
- BadRequest(String),
- #[error("I/O: {0}")]
- Io(String),
- #[error(transparent)]
- Engine(#[from] materialcraft_engine::EngineError),
- #[error("bridge: {0}")]
- Bridge(String),
- #[error("app: {0}")]
- App(String),
- #[error("{0}")]
- Other(String),
-}
-
-pub(crate) fn bad(msg: impl Into) -> AutomationError {
- AutomationError::BadRequest(msg.into())
-}
+mod automation_error;
+pub use automation_error::AutomationError;
+pub(crate) use automation_error::bad;
diff --git a/crates/automation/src/render_options.rs b/crates/automation/src/render_options.rs
new file mode 100644
index 00000000..318619f5
--- /dev/null
+++ b/crates/automation/src/render_options.rs
@@ -0,0 +1,25 @@
+/// What [`crate::Headless::render_png`] draws
+#[derive(Clone, Debug, Default)]
+pub struct RenderOptions {
+ /// `3d` (default) or `2d` (a node's output; the 2D view's node by default)
+ pub view: Option,
+ pub width: Option,
+ pub height: Option,
+ /// Camera overrides in degrees (the session's view is not changed)
+ pub yaw: Option,
+ pub pitch: Option,
+ /// 3D scene override (`rounded_cube`, `sphere`, …)
+ pub scene: Option,
+ /// 2D: the node whose output to show
+ pub node: Option,
+ /// 2D: the output port
+ pub port: Option,
+ /// Cook at full size instead of the preview size
+ pub full: bool,
+ /// 3D: UV repeats override (the session's view is not changed)
+ pub tiling: Option,
+ /// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills
+ pub hq: bool,
+ /// 3D, with `hq`: displacement depth in scene radii (default 0.04)
+ pub displacement: Option,
+}
diff --git a/crates/automation/src/rendered.rs b/crates/automation/src/rendered.rs
new file mode 100644
index 00000000..32970910
--- /dev/null
+++ b/crates/automation/src/rendered.rs
@@ -0,0 +1,6 @@
+/// A PNG render
+pub struct Rendered {
+ pub width: u32,
+ pub height: u32,
+ pub png: Vec,
+}
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index 3befa2a5..dae2611d 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -1,15 +1,3 @@
-//! Headless JSON-lines server with the app's control-channel envelope:
-//! `{"id","method","params"}` → `{"id","ok":true,"result"}` | `{"id","ok":false,"error"}`.
-//! `materialcraft-cli serve` runs it on stdio or on a loopback TCP port (first request `auth`).
-//!
-//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
-//! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`,
-//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`,
-//! `material.export {path, graph?, size?, values?}` (workspace-scoped versions of the engine
-//! commands; the last writes a portable `.mcmat`), `render {view?, width?, height?, yaw?,
-//! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`)
-//! and `methods`.
-
use std::io::{BufRead, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex, PoisonError};
@@ -69,7 +57,7 @@ fn required<'a>(p: &'a Value, k: &str) -> Result<&'a str, AutomationError> {
}
impl Headless {
- /// Dispatch one request. Unknown methods and bad params are errors, never panics.
+ /// Dispatch one request. Unknown methods and bad params are errors, never panics
pub fn handle(&mut self, method: &str, p: &Value) -> Result {
match method {
"ping" => Ok(json!("pong")),
@@ -104,6 +92,7 @@ impl Headless {
hq: bool_of(p, "hq")?,
displacement: f32_of(p, "displacement")?,
};
+
let r = self.render_png(&o)?;
Ok(json!({ "width": r.width, "height": r.height, "png": base64::engine::general_purpose::STANDARD.encode(r.png) }))
}
@@ -115,17 +104,18 @@ impl Headless {
}
}
-/// Answer one request line. A panic inside a command becomes an error reply (edits run on a
-/// snapshot, so the session stays consistent).
+/// Answer one request line. A panic inside a command becomes an error reply (edits run on a snapshot, so the session stays consistent)
pub fn respond(h: &Mutex, line: &str) -> Value {
let req: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(e) => return json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}),
};
+
let id = req.get("id").cloned().unwrap_or(Value::Null);
let Some(method) = req.get("method").and_then(Value::as_str) else {
return json!({"id": id, "ok": false, "error": "`method` is required"});
};
+
let params = req.get("params").cloned().unwrap_or(Value::Null);
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).handle(method, ¶ms)))
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))));
@@ -135,14 +125,14 @@ pub fn respond(h: &Mutex, line: &str) -> Value {
}
}
-/// Write one reply line; an oversized reply becomes an error with the same id.
+/// Write one reply line; an oversized reply becomes an error with the same id
fn write_reply(w: &mut impl Write, reply: &Value) -> std::io::Result<()> {
let text = json_text(reply).unwrap_or_else(|e| json!({"id": reply.get("id"), "ok": false, "error": e.to_string()}).to_string());
writeln!(w, "{text}")?;
w.flush()
}
-/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication).
+/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication)
pub fn serve_lines(h: &Mutex, mut r: impl BufRead, mut w: impl Write) -> std::io::Result<()> {
let mut line = String::new();
loop {
@@ -154,11 +144,12 @@ pub fn serve_lines(h: &Mutex, mut r: impl BufRead, mut w: impl Write)
Ok(LineRead::Line) if line.trim().is_empty() => continue,
Ok(LineRead::Line) => respond(h, &line),
};
+
write_reply(&mut w, &reply)?;
}
}
-/// One TCP connection: the first request must be `auth {token}`, as on the app's channel.
+/// One TCP connection: the first request must be `auth {token}`, as on the app's channel
fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &str) -> std::io::Result<()> {
stream.set_read_timeout(Some(std::time::Duration::from_secs(600)))?;
let mut r = std::io::BufReader::new(stream.try_clone()?);
@@ -189,20 +180,19 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st
}
}
-/// Listen on `127.0.0.1:port` (0 picks a port).
+/// Listen on `127.0.0.1:port` (0 picks a port)
pub fn bind_tcp(port: u16) -> Result {
TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))
}
-/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared
-/// session. `ready` gets the bound address.
+/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared session. `ready` gets the bound address
pub fn serve_tcp(port: u16, h: Arc>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> {
let listener = bind_tcp(port)?;
ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?);
serve_listener(listener, h, token)
}
-/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session.
+/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session
pub fn serve_listener(listener: TcpListener, h: Arc>, token: String) -> Result<(), AutomationError> {
let limiter = ConnectionLimiter::default();
let token = Arc::new(token);
@@ -212,6 +202,7 @@ pub fn serve_listener(listener: TcpListener, h: Arc>, token: Str
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"}));
continue;
};
+
let (h, token) = (h.clone(), token.clone());
if let Err(e) = std::thread::Builder::new().name("materialcraft-rpc-client".into()).spawn(move || {
let _permit = permit;
@@ -251,7 +242,7 @@ mod tests {
r#"{"id":4,"method":"command.run","params":{"id":"file.open","params":{"path":"/etc/passwd"}}}"#,
"
",
- r#"{"id":5,"method":"package.open","params":{"path":"x.mcraft"}}"#,
+ r#"{"id":5,"method":"package.open","params":{"path":"x.sbs"}}"#,
"
",
r#"{"id":6,"method":"command.batch","params":{"steps":[{"id":"edit.selectAll"},{"id":"nope"},{"id":"edit.selectAll"}]}}"#,
@@ -298,7 +289,7 @@ mod tests {
assert_eq!(r["bytes"], bytes.len());
let (m, source) = materialcraft_engine::formats::material::read_material(&bytes).unwrap();
assert_eq!(m.size, [32, 32]);
- assert!(m.maps.iter().any(|e| e.usage == "baseColor"));
+ assert!(m.maps.iter().any(|e| e.usage == "height"));
assert!(!source.is_empty());
assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind");
// An explicit extension is kept (case-insensitively) and the file can be opened again.
@@ -369,6 +360,7 @@ mod tests {
})
.collect::>()
};
+
let denied = talk(&[r#"{"id":1,"method":"session.inspect"}"#]);
assert_eq!(denied[0]["ok"], false);
let ok = talk(&[r#"{"id":1,"method":"auth","params":{"token":"0123456789abcdef0123"}}"#, r#"{"id":2,"method":"ping"}"#]);
diff --git a/crates/automation/src/server/backend.rs b/crates/automation/src/server/backend.rs
new file mode 100644
index 00000000..0d250b71
--- /dev/null
+++ b/crates/automation/src/server/backend.rs
@@ -0,0 +1,10 @@
+use crate::{BridgeClient, Headless};
+use std::sync::{Arc, Mutex};
+
+/// Where tools run
+pub enum Backend {
+ /// An in-process session
+ Headless(Arc>),
+ /// The running desktop app, over its control channel
+ Bridge(Arc),
+}
diff --git a/crates/automation/src/server/material_craft_mcp.rs b/crates/automation/src/server/material_craft_mcp.rs
new file mode 100644
index 00000000..71cb233b
--- /dev/null
+++ b/crates/automation/src/server/material_craft_mcp.rs
@@ -0,0 +1,320 @@
+use super::{Backend, parameter::*};
+use std::sync::{Arc, Mutex, PoisonError};
+
+use base64::Engine as _;
+use rmcp::handler::server::router::tool::ToolRouter;
+use rmcp::handler::server::wrapper::Parameters;
+use rmcp::model::{CallToolResult, ContentBlock as Content};
+use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
+use serde::Serialize;
+use serde_json::{Value, json};
+
+use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text};
+use crate::headless::batch_reply;
+use crate::security::MAX_BATCH_STEPS;
+use crate::workspace::authorize_command;
+use crate::{AutomationError, BridgeClient, Headless, bad};
+
+#[derive(Clone)]
+pub struct MaterialCraftMcp {
+ backend: Arc,
+ tool_router: ToolRouter,
+}
+
+fn ok_json(v: &Value) -> CallToolResult {
+ match json_text(v) {
+ Ok(text) => CallToolResult::success(vec![Content::text(text)]),
+ Err(e) => fail(e),
+ }
+}
+
+fn fail(e: impl std::fmt::Display) -> CallToolResult {
+ CallToolResult::error(vec![Content::text(e.to_string())])
+}
+
+fn to_result(r: Result) -> Result {
+ Ok(match r {
+ Ok(v) => ok_json(&v),
+ Err(e) => fail(e),
+ })
+}
+
+/// A `{width, height, png: base64}` reply (render or app screenshot) as image content
+fn image_result(r: Result, note: &str, refit: bool) -> Result {
+ let png = r.and_then(|v| {
+ let b64 = v.get("png").and_then(Value::as_str).ok_or_else(|| AutomationError::Other("the reply has no PNG".into()))?;
+ if !refit {
+ check_png(b64.len() / 4 * 3)?;
+ return Ok(b64.to_string());
+ }
+ let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| AutomationError::Other(format!("bad PNG data: {e}")))?;
+ Ok(base64::engine::general_purpose::STANDARD.encode(fit_png(bytes, MAX_PNG_SIDE)?))
+ });
+ Ok(match png {
+ Ok(b64) => CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note.to_string())]),
+ Err(e) => fail(e),
+ })
+}
+
+fn params(p: &T) -> Value {
+ serde_json::to_value(p).unwrap_or(Value::Null)
+}
+
+impl MaterialCraftMcp {
+ pub fn headless(h: Headless) -> Self {
+ Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h))))
+ }
+
+ pub fn bridge(client: BridgeClient) -> Self {
+ Self::with_backend(Backend::Bridge(Arc::new(client)))
+ }
+
+ pub fn with_backend(backend: Backend) -> Self {
+ MaterialCraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
+ }
+
+ /// Serve MCP on stdin/stdout until the client disconnects
+ pub async fn serve_stdio(self) -> Result<(), AutomationError> {
+ let running = self.serve(rmcp::transport::stdio()).await.map_err(|e| AutomationError::Other(format!("MCP start: {e}")))?;
+ running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()))?;
+ Ok(())
+ }
+
+ fn is_bridge(&self) -> bool {
+ matches!(*self.backend, Backend::Bridge(_))
+ }
+
+ /// One control-channel method on the backend
+ async fn call(&self, method: &str, p: Value) -> Result {
+ match &*self.backend {
+ Backend::Headless(h) => {
+ let (h, m) = (h.clone(), method.to_string());
+ // Edits run on snapshots (`Session::edit`), so a panicking command leaves the session consistent: keep serving after a poisoned lock
+ tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
+ .await
+ .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
+ }
+ Backend::Bridge(b) => match method {
+ "command.run" => {
+ let id = p.get("id").and_then(Value::as_str).unwrap_or_default();
+ authorize_command(id, p.get("params").unwrap_or(&Value::Null))?;
+ b.call(method, p).await
+ }
+ "package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
+ "package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => {
+ Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
+ }
+ _ => b.call(method, p).await,
+ },
+ }
+ }
+
+ async fn run(&self, id: &str, p: Value) -> Result {
+ self.call("command.run", json!({"id": id, "params": p})).await
+ }
+
+ async fn bridge_only(&self, method: &str, p: Value) -> Result {
+ if self.is_bridge() {
+ self.call(method, p).await
+ } else {
+ Err(bad(format!(
+ "`{method}` needs the running app: start `materialcraft --control ` and run `materialcraft-cli mcp --bridge ` (headless renders: view_render)"
+ )))
+ }
+ }
+}
+
+// --------------------------------------------------------------------------------------------- Tools
+
+#[tool_router]
+impl MaterialCraftMcp {
+ #[tool(description = "The whole session as JSON: package, graphs, the open graph's nodes (definition, parameters, base \
+ parameters, ports, cook errors, timings, mean values), connections, frames, comments, pins, exposed inputs, views and history.")]
+ async fn session_inspect(&self) -> Result {
+ to_result(self.call("session.inspect", json!({})).await)
+ }
+
+ #[tool(description = "List engine commands: id, label, menu path, shortcut, params doc and whether it can run now.")]
+ async fn command_list(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("command.list", params(&p)).await)
+ }
+
+ #[tool(description = "Run an engine command by id with JSON params (see command_list). Runs with defaults, never opens a \
+ dialog. Commands given host paths are disabled: use package_open, package_save, bitmap_import and outputs_export.")]
+ async fn command_run(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("command.run", params(&p)).await)
+ }
+
+ #[tool(description = "Run several commands in order: steps [{id, params}]. Stops at the first error. Returns {completed, \
+ results, failed: {index, id, error} | null}; a failed batch is a tool error.")]
+ async fn command_batch(&self, Parameters(p): Parameters) -> Result {
+ if p.steps.len() > MAX_BATCH_STEPS {
+ return Ok(fail(format!("at most {MAX_BATCH_STEPS} steps per batch")));
+ }
+ let reply = if self.is_bridge() {
+ let mut results = Vec::new();
+ let mut failed = None;
+ for (i, s) in p.steps.iter().enumerate() {
+ match self.call("command.run", params(s)).await {
+ Ok(v) => results.push(v),
+ Err(e) => {
+ failed = Some((i, s.id.as_str(), e.to_string()));
+ break;
+ }
+ }
+ }
+ batch_reply(results, failed)
+ } else {
+ match self.call("command.batch", params(&p)).await {
+ Ok(v) => v,
+ Err(e) => return Ok(fail(e)),
+ }
+ };
+ Ok(if reply["failed"].is_null() { ok_json(&reply) } else { fail(json_text(&reply).unwrap_or_else(|e| e.to_string())) })
+ }
+
+ #[tool(description = "The node library: every node's id, label, category, input and output ports and parameters (id, \
+ default, range, enum options). Filter by text or category.")]
+ async fn library_list(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.run("library.list", params(&p)).await)
+ }
+
+ #[tool(description = "Add a new graph to the package from a template and open it. Returns {graph, name}.")]
+ async fn graph_new(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.run("file.new", params(&p)).await)
+ }
+
+ #[tool(description = "Add a node to the open graph (optionally wired from another node's output). Returns {id}.")]
+ async fn node_add(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.run("graph.node.add", params(&p)).await)
+ }
+
+ #[tool(description = "Wire an output port of one node into an input port of another (replacing what fed that input).")]
+ async fn node_connect(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.run("graph.connect", params(&p)).await)
+ }
+
+ #[tool(description = "Set one parameter of a node.")]
+ async fn node_param(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.run("graph.node.param", params(&p)).await)
+ }
+
+ #[tool(
+ description = "Open an .sbs package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
+ )]
+ async fn package_open(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("package.open", params(&p)).await)
+ }
+
+ #[tool(description = "Save the package (path relative to the write root; omit to save to its own file). Saves native SBS (.sbs).")]
+ async fn package_save(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("package.save", params(&p)).await)
+ }
+
+ #[tool(description = "Embed an image (path relative to the read root) as a bitmap resource. Returns its name, for a \
+ `bitmap` node's `resource` parameter.")]
+ async fn bitmap_import(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("bitmap.import", params(&p)).await)
+ }
+
+ #[tool(description = "Cook a graph at full size and write every output (base color, normal, roughness, …) into a folder \
+ relative to the write root. Returns the written files.")]
+ async fn outputs_export(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("outputs.export", params(&p)).await)
+ }
+
+ #[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \
+ source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \
+ Returns {path, bytes}.")]
+ async fn material_export(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.call("material.export", params(&p)).await)
+ }
+
+ #[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \
+ 2048 px a side. In bridge mode use view_screenshot.")]
+ async fn view_render(&self, Parameters(p): Parameters) -> Result {
+ let note = format!("render {}", params(&p));
+ image_result(self.call("render", params(&p)).await, ¬e, false)
+ }
+
+ #[tool(description = "Bridge mode: PNG of the live app's 3D or 2D view.")]
+ async fn view_screenshot(&self, Parameters(p): Parameters) -> Result {
+ image_result(self.bridge_only("view.screenshot", params(&p)).await, "screenshot of an app view", true)
+ }
+
+ #[tool(description = "Bridge mode: PNG of the whole app window (downscaled to 2048 px a side at most).")]
+ async fn ui_screenshot(&self) -> Result {
+ image_result(self.bridge_only("ui.screenshot", json!({})).await, "screenshot of the app window", true)
+ }
+
+ #[tool(description = "Bridge mode: the app's UI state (panels, windows, graph view camera, node rectangles on screen, toasts).")]
+ async fn ui_inspect(&self) -> Result {
+ to_result(self.bridge_only("ui.inspect", json!({})).await)
+ }
+
+ #[tool(description = "Bridge mode: activate a menu item by id like a click (may open a window). ui.menu.list lists ids.")]
+ async fn ui_menu_invoke(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.bridge_only("ui.menu.invoke", params(&p)).await)
+ }
+
+ #[tool(description = "Bridge mode: synthesize mouse, keyboard and text input in the app window (clicks, drags between \
+ node ports, scrolling, shortcuts, typing). Positions are window points (see ui_inspect for node rectangles).")]
+ async fn ui_input(&self, Parameters(p): Parameters) -> Result {
+ to_result(self.bridge_only("ui.input", params(&p)).await)
+ }
+}
+
+#[tool_handler(
+ router = self.tool_router,
+ name = "materialcraft",
+ instructions = "MaterialCraft procedural material designer. A package holds graphs of nodes; each graph's output nodes \
+ (usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \
+ (templates: empty, pbr, atomics) or package_open, browse nodes with library_list, build with node_add / node_connect \
+ / node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \
+ view_render (3d, or 2d for one node), then package_save, outputs_export or material_export. Undo: command_run edit.undo."
+)]
+impl ServerHandler for MaterialCraftMcp {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::headless::Filesystem;
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn a_panic_does_not_wedge_the_session() {
+ let mcp = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
+ let Backend::Headless(h) = &*mcp.backend else { panic!("headless") };
+ let h2 = h.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ let _g = h2.lock().unwrap();
+ panic!("boom")
+ })
+ .await;
+ assert!(mcp.call("session.inspect", json!({})).await.is_ok());
+ }
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn material_export_tool_writes_through_the_workspace_only() {
+ let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ std::fs::create_dir_all(&base).unwrap();
+ let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None });
+
+ let denied = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
+ assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true));
+
+ let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap();
+ let mcp = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
+ assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false));
+ assert!(base.join("m.mcmat").is_file());
+ let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None });
+ assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true));
+ assert!(!base.parent().unwrap().join("m.mcmat").exists());
+ }
+
+ #[test]
+ fn oversized_replies_become_errors() {
+ let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES)));
+ assert_eq!(r.is_error, Some(true));
+ }
+}
diff --git a/crates/automation/src/server/mod.rs b/crates/automation/src/server/mod.rs
new file mode 100644
index 00000000..29444de2
--- /dev/null
+++ b/crates/automation/src/server/mod.rs
@@ -0,0 +1,6 @@
+mod backend;
+mod material_craft_mcp;
+mod parameter;
+
+pub use backend::Backend;
+pub use material_craft_mcp::MaterialCraftMcp;
diff --git a/crates/automation/src/server/parameter/batch_params.rs b/crates/automation/src/server/parameter/batch_params.rs
new file mode 100644
index 00000000..0c8bff7f
--- /dev/null
+++ b/crates/automation/src/server/parameter/batch_params.rs
@@ -0,0 +1,9 @@
+use super::RunParams;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct BatchParams {
+ /// Commands run in order; the batch stops at the first error and reports its index
+ pub steps: Vec,
+}
diff --git a/crates/automation/src/server/parameter/bitmap_params.rs b/crates/automation/src/server/parameter/bitmap_params.rs
new file mode 100644
index 00000000..8424dead
--- /dev/null
+++ b/crates/automation/src/server/parameter/bitmap_params.rs
@@ -0,0 +1,11 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct BitmapParams {
+ /// Image file relative to the read root (png, jpg, tga, tif, bmp, webp, exr, hdr)
+ pub path: String,
+ /// Resource name (default: the file name)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option,
+}
diff --git a/crates/automation/src/server/parameter/connect_params.rs b/crates/automation/src/server/parameter/connect_params.rs
new file mode 100644
index 00000000..ced3f356
--- /dev/null
+++ b/crates/automation/src/server/parameter/connect_params.rs
@@ -0,0 +1,16 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct ConnectParams {
+ /// Source node id
+ pub from: u64,
+ /// Source output port id (default: its first output)
+ #[serde(default, rename = "fromPort", skip_serializing_if = "Option::is_none")]
+ pub from_port: Option,
+ /// Target node id
+ pub to: u64,
+ /// Target input port id (default: its first input)
+ #[serde(default, rename = "toPort", skip_serializing_if = "Option::is_none")]
+ pub to_port: Option,
+}
diff --git a/crates/automation/src/server/parameter/export_params.rs b/crates/automation/src/server/parameter/export_params.rs
new file mode 100644
index 00000000..40004254
--- /dev/null
+++ b/crates/automation/src/server/parameter/export_params.rs
@@ -0,0 +1,23 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct ExportParams {
+ /// Output folder relative to the write root (created if missing; `.` = the root)
+ pub dir: String,
+ /// png (default), jpg, tga, tif, bmp, webp, exr, hdr
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub format: Option,
+ /// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pattern: Option,
+ /// 8, 16 or 32 bits (default: the graph's output format)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub depth: Option,
+ /// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option,
+ /// Graph index (default: the open graph)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub graph: Option,
+}
diff --git a/crates/automation/src/server/parameter/filter_params.rs b/crates/automation/src/server/parameter/filter_params.rs
new file mode 100644
index 00000000..be9d1f7a
--- /dev/null
+++ b/crates/automation/src/server/parameter/filter_params.rs
@@ -0,0 +1,9 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
+pub struct FilterParams {
+ /// Only entries whose id or label contains this text (case-insensitive)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub filter: Option,
+}
diff --git a/crates/automation/src/server/parameter/input_params.rs b/crates/automation/src/server/parameter/input_params.rs
new file mode 100644
index 00000000..1fea5686
--- /dev/null
+++ b/crates/automation/src/server/parameter/input_params.rs
@@ -0,0 +1,9 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct InputParams {
+ /// Input events in window points, applied in order on the next frames
+ pub events: Vec,
+}
diff --git a/crates/automation/src/server/parameter/library_params.rs b/crates/automation/src/server/parameter/library_params.rs
new file mode 100644
index 00000000..26cfc86d
--- /dev/null
+++ b/crates/automation/src/server/parameter/library_params.rs
@@ -0,0 +1,12 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
+pub struct LibraryParams {
+ /// Only nodes whose id or label contains this text
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub filter: Option,
+ /// Library category, such as "Atomic nodes" or "Graph items"
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub category: Option,
+}
diff --git a/crates/automation/src/server/parameter/material_export_params.rs b/crates/automation/src/server/parameter/material_export_params.rs
new file mode 100644
index 00000000..88f7ddbb
--- /dev/null
+++ b/crates/automation/src/server/parameter/material_export_params.rs
@@ -0,0 +1,19 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct MaterialExportParams {
+ /// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The
+ /// parent folder must exist
+ pub path: String,
+ /// Graph index (default: the open graph)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub graph: Option,
+ /// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option,
+ /// Exposed input values to cook with and embed, by input id (see `session_inspect`)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub values: Option,
+}
diff --git a/crates/automation/src/server/parameter/menu_params.rs b/crates/automation/src/server/parameter/menu_params.rs
new file mode 100644
index 00000000..dadf89cc
--- /dev/null
+++ b/crates/automation/src/server/parameter/menu_params.rs
@@ -0,0 +1,8 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct MenuParams {
+ /// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `ui.newGraph`, `ui.view.library`
+ pub id: String,
+}
diff --git a/crates/automation/src/server/parameter/mod.rs b/crates/automation/src/server/parameter/mod.rs
new file mode 100644
index 00000000..f9d71284
--- /dev/null
+++ b/crates/automation/src/server/parameter/mod.rs
@@ -0,0 +1,36 @@
+mod batch_params;
+mod bitmap_params;
+mod connect_params;
+mod export_params;
+mod filter_params;
+mod input_params;
+mod library_params;
+mod menu_params;
+mod new_graph_params;
+mod node_add_params;
+mod param_set_params;
+mod path_params;
+mod render_params;
+mod run_params;
+mod save_params;
+mod screenshot_params;
+
+pub use batch_params::BatchParams;
+pub use bitmap_params::BitmapParams;
+pub use connect_params::ConnectParams;
+pub use export_params::ExportParams;
+pub use filter_params::FilterParams;
+pub use input_params::InputParams;
+pub use library_params::LibraryParams;
+pub use menu_params::MenuParams;
+pub use new_graph_params::NewGraphParams;
+pub use node_add_params::NodeAddParams;
+pub use param_set_params::ParamSetParams;
+pub use path_params::PathParams;
+pub use render_params::RenderParams;
+pub use run_params::RunParams;
+pub use save_params::SaveParams;
+pub use screenshot_params::ScreenshotParams;
+
+mod material_export_params;
+pub use material_export_params::MaterialExportParams;
diff --git a/crates/automation/src/server/parameter/new_graph_params.rs b/crates/automation/src/server/parameter/new_graph_params.rs
new file mode 100644
index 00000000..cc4d5ced
--- /dev/null
+++ b/crates/automation/src/server/parameter/new_graph_params.rs
@@ -0,0 +1,14 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
+pub struct NewGraphParams {
+ /// Template id: empty, pbr (six material outputs), atomics
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub template: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option,
+ /// Graph size in pixels, a power of two from 16 to 8192 (default 1024)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub size: Option,
+}
diff --git a/crates/automation/src/server/parameter/node_add_params.rs b/crates/automation/src/server/parameter/node_add_params.rs
new file mode 100644
index 00000000..5a0832a4
--- /dev/null
+++ b/crates/automation/src/server/parameter/node_add_params.rs
@@ -0,0 +1,18 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct NodeAddParams {
+ /// Node definition id from `library_list`, e.g. `uniform`, `blend`, `levels`, `normal`, `output`
+ pub def: String,
+ /// Graph position `[x, y]` (default: right of `connectFrom`, else the origin)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub at: Option<[f32; 2]>,
+ /// Parameter values by id (see `library_list`): numbers, `[x, y]`, `"#rrggbb"`, enum indices
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub params: Option,
+ /// Wire `{node, port?}`'s output into the new node's first input
+ #[serde(default, rename = "connectFrom", skip_serializing_if = "Option::is_none")]
+ pub connect_from: Option,
+}
diff --git a/crates/automation/src/server/parameter/param_set_params.rs b/crates/automation/src/server/parameter/param_set_params.rs
new file mode 100644
index 00000000..271e7284
--- /dev/null
+++ b/crates/automation/src/server/parameter/param_set_params.rs
@@ -0,0 +1,13 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct ParamSetParams {
+ /// Node id
+ pub id: u64,
+ /// Parameter id (see `library_list`)
+ pub param: String,
+ /// The value: a number, `[x, y]`, `"#rrggbb"`, an enum index, a curve `[[x, y], …]` or a gradient `[[pos, color], …]`
+ pub value: Value,
+}
diff --git a/crates/automation/src/server/parameter/path_params.rs b/crates/automation/src/server/parameter/path_params.rs
new file mode 100644
index 00000000..b21194e4
--- /dev/null
+++ b/crates/automation/src/server/parameter/path_params.rs
@@ -0,0 +1,8 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct PathParams {
+ /// Forward-slash path relative to the workspace root
+ pub path: String,
+}
diff --git a/crates/automation/src/server/parameter/render_params.rs b/crates/automation/src/server/parameter/render_params.rs
new file mode 100644
index 00000000..93876ed9
--- /dev/null
+++ b/crates/automation/src/server/parameter/render_params.rs
@@ -0,0 +1,40 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
+pub struct RenderParams {
+ /// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub view: Option,
+ /// Pixels, 16..2048
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub width: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub height: Option,
+ /// Camera yaw/pitch in degrees for this render only
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub yaw: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pitch: Option,
+ /// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub scene: Option,
+ /// 2D: the node to show (default: the 2D view's node, else the first output)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub node: Option,
+ /// 2D: the output port index
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub port: Option,
+ /// Cook at the full graph size instead of the preview size
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub full: Option,
+ /// 3D: UV repeats of the material on the scene for this render only
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tiling: Option,
+ /// 3D beauty render: real displacement from the height output, ambient occlusion and a shadowed key light (slower)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub hq: Option,
+ /// With `hq`: displacement depth in scene radii (default 0.04)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub displacement: Option,
+}
diff --git a/crates/automation/src/server/parameter/run_params.rs b/crates/automation/src/server/parameter/run_params.rs
new file mode 100644
index 00000000..59bb5f9c
--- /dev/null
+++ b/crates/automation/src/server/parameter/run_params.rs
@@ -0,0 +1,12 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+pub struct RunParams {
+ /// Command id from `command_list`, e.g. `graph.node.add`, `graph.connect`, `edit.undo`
+ pub id: String,
+ /// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub params: Option,
+}
diff --git a/crates/automation/src/server/parameter/save_params.rs b/crates/automation/src/server/parameter/save_params.rs
new file mode 100644
index 00000000..c5f15e27
--- /dev/null
+++ b/crates/automation/src/server/parameter/save_params.rs
@@ -0,0 +1,9 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
+pub struct SaveParams {
+ /// Optional path relative to the write root, with an .sbs extension
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub path: Option,
+}
diff --git a/crates/automation/src/server/parameter/screenshot_params.rs b/crates/automation/src/server/parameter/screenshot_params.rs
new file mode 100644
index 00000000..e2fc5b8a
--- /dev/null
+++ b/crates/automation/src/server/parameter/screenshot_params.rs
@@ -0,0 +1,9 @@
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
+pub struct ScreenshotParams {
+ /// `3d` (default) or `2d`
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub view: Option,
+}
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 80812243..89d6f226 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -1,8 +1,4 @@
-//! Capability-based file access for untrusted automation paths (MCP, `serve`).
-//!
-//! Roots are trusted launch-time configuration (`--read-root`, `--write-root`); request paths
-//! are untrusted, forward-slash relative paths resolved by `cap-std` beneath the held directory
-//! handle, so `..`, absolute paths, drive prefixes and symlink or junction escapes all fail.
+//! Capability-based file access for untrusted automation paths (MCP, `serve`)
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
@@ -14,10 +10,10 @@ use serde_json::Value;
use crate::{AutomationError, bad};
-/// Largest file read through automation (the mesh importer's own limit).
+/// Largest file read through automation (the mesh importer's own limit)
pub const MAX_READ_BYTES: u64 = 256 << 20;
-/// Separate read and write directory capabilities. A missing authority fails closed.
+/// Separate read and write directory capabilities. A missing authority fails closed
#[derive(Clone, Default)]
pub struct AuthorizedWorkspace {
read: Option>,
@@ -29,7 +25,7 @@ impl AuthorizedWorkspace {
Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? })
}
- /// Read one regular file below the read root.
+ /// Read one regular file below the read root
pub fn read(&self, path: &str) -> Result, AutomationError> {
let rel = relative_path(path)?;
let root = self.read.as_ref().ok_or_else(|| denied("read"))?;
@@ -46,8 +42,7 @@ impl AuthorizedWorkspace {
Ok(bytes)
}
- /// Create or replace one file below the write root: a temporary file beside the target,
- /// synced and renamed over it. The parent directory must exist.
+ /// Create or replace one file below the write root: a temporary file beside the target, synced and renamed over it. The parent directory must exist
pub fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
@@ -69,14 +64,13 @@ impl AuthorizedWorkspace {
Ok(())
}
- /// Fail now, before any expensive work, when [`write`](Self::write) to `path` cannot succeed
- /// for lack of a write root or because the path is malformed.
+ /// Validate the write capability and relative path before cooking
pub fn check_write(&self, path: &str) -> Result<(), AutomationError> {
relative_path(path)?;
self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write"))
}
- /// Create a directory (and its parents) below the write root.
+ /// Create a directory and its parents below the write root
pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
@@ -94,7 +88,7 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result>, A
Ok(Some(Arc::new(dir)))
}
-/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root).
+/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root)
pub fn relative_path(raw: &str) -> Result {
let reject = |why: &str| bad(format!("path rejected ({why}): `{raw}`; use a forward-slash path relative to the workspace root"));
if raw.is_empty() {
@@ -134,18 +128,14 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
}
-/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
-/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
-/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
-/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
-/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
-/// embedded mesh).
+/// Route file access through the workspace boundary
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
let ok = match id {
- "file.new" | "file.newPackage" => !has_path,
+ "file.new" | "file.newPackage" | "file.newAtomicSample" => !has_path,
_ => !id.starts_with("file.") && !has_path,
};
+
if ok {
Ok(())
} else {
@@ -241,12 +231,11 @@ mod tests {
assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}");
assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}");
}
- assert!(authorize_command("file.new", &json!({"template": "bricks"})).is_ok());
+ assert!(authorize_command("file.new", &json!({"template": "atomics"})).is_ok());
assert!(authorize_command("graph.node.add", &json!({"def": "blur", "path": null})).is_ok());
}
- /// Every registry command documenting a host path must be classified (fails when a new
- /// path-taking command is added without an automation policy).
+ /// Every registry command documenting a host path must be classified (fails when a new path-taking command is added without an automation policy)
#[test]
fn registry_path_params_are_classified() {
let probe = json!({"path": "/outside/probe", "dir": "/outside", "mesh": "/outside/m.obj"});
diff --git a/crates/automation/tests/normal_maps.rs b/crates/automation/tests/normal_maps.rs
index 41e2854f..aadac01f 100644
--- a/crates/automation/tests/normal_maps.rs
+++ b/crates/automation/tests/normal_maps.rs
@@ -14,7 +14,7 @@ fn generated_normal_conventions_produce_the_same_surface_when_matched() {
let gl = height_to_normal(&height, 8.0, false, false, false);
let dx = height_to_normal(&height, 8.0, true, false, false);
let normal_node = materialcraft_engine::nodes::find("normal").unwrap();
- assert_eq!(normal_node.param("format").unwrap().default.as_i32(), Some(0));
+ assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(true));
let maps = |normal| Maps { normal: Some(normal), base_color: Some(Image::filled(4, 4, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() };
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
let settings = Settings::default();
diff --git a/crates/core/src/attributes.rs b/crates/core/src/attributes.rs
new file mode 100644
index 00000000..1dc3b2bc
--- /dev/null
+++ b/crates/core/src/attributes.rs
@@ -0,0 +1,11 @@
+use serde::{Deserialize, Serialize};
+
+/// Descriptive metadata ("Attributes")
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Attributes {
+ pub category: String,
+ pub description: String,
+ pub author: String,
+ pub tags: String,
+}
diff --git a/crates/core/src/base_parameters.rs b/crates/core/src/base_parameters.rs
new file mode 100644
index 00000000..2eba06c5
--- /dev/null
+++ b/crates/core/src/base_parameters.rs
@@ -0,0 +1,23 @@
+use serde::{Deserialize, Serialize};
+
+use crate::{OutputFormat, SizeMode};
+
+/// Parameters every node has ("Base parameters")
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct BaseParameters {
+ pub size_mode: SizeMode,
+ /// log2 offset per axis (relative modes) or log2 size (absolute)
+ pub size: [i32; 2],
+ pub format: OutputFormat,
+ /// Added to the graph's random seed for this node
+ pub seed: i32,
+ /// Whether sampling wraps at the edges (horizontal, vertical)
+ pub tiling: [bool; 2],
+}
+
+impl Default for BaseParameters {
+ fn default() -> Self {
+ BaseParameters { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] }
+ }
+}
diff --git a/crates/core/src/color.rs b/crates/core/src/color.rs
new file mode 100644
index 00000000..f7e34c0e
--- /dev/null
+++ b/crates/core/src/color.rs
@@ -0,0 +1,34 @@
+/// `[r, g, b(, a)]` linear floats, a single gray number, or `"#rrggbb(aa)"` (sRGB, converted to linear)
+pub fn parse_color(j: &serde_json::Value) -> Option<[f32; 4]> {
+ use serde_json::Value as J;
+ match j {
+ J::Array(a) if a.len() >= 3 => {
+ let v: Vec = a.iter().take(4).filter_map(|x| x.as_f64().map(|x| x as f32)).filter(|x| x.is_finite()).collect();
+ if v.len() < 3 {
+ return None;
+ }
+ Some([v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)])
+ }
+ J::Number(n) => n.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).map(|v| [v, v, v, 1.0]),
+ J::String(s) => {
+ let s = s.trim_start_matches('#');
+ if s.len() != 6 && s.len() != 8 {
+ return None;
+ }
+ let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0);
+ let a = if s.len() == 8 { c(6)? } else { 1.0 };
+ Some([srgb_to_linear(c(0)?), srgb_to_linear(c(2)?), srgb_to_linear(c(4)?), a])
+ }
+ _ => None,
+ }
+}
+
+/// sRGB transfer function, encoded → linear
+pub fn srgb_to_linear(v: f32) -> f32 {
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+}
+
+/// sRGB transfer function, linear → encoded
+pub fn linear_to_srgb(v: f32) -> f32 {
+ if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 }
+}
diff --git a/crates/core/src/comment.rs b/crates/core/src/comment.rs
new file mode 100644
index 00000000..4027f6bc
--- /dev/null
+++ b/crates/core/src/comment.rs
@@ -0,0 +1,15 @@
+use serde::{Deserialize, Serialize};
+
+/// Plain text on the graph canvas
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Comment {
+ pub id: u64,
+ pub text: String,
+ pub pos: [f32; 2],
+ #[serde(default = "comment_size")]
+ pub size: [f32; 2],
+}
+
+fn comment_size() -> [f32; 2] {
+ [180.0, 70.0]
+}
diff --git a/crates/core/src/component_usage.rs b/crates/core/src/component_usage.rs
new file mode 100644
index 00000000..5c0c6ac1
--- /dev/null
+++ b/crates/core/src/component_usage.rs
@@ -0,0 +1,81 @@
+/// Input/output semantics shared by node properties, SBS and texture exports
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ComponentUsage {
+ pub id: &'static str,
+ pub label: &'static str,
+}
+
+impl ComponentUsage {
+ pub const ANY: Self = Self { id: "any", label: "Any" };
+ pub const ANY_INDEX: u32 = 9;
+
+ // Existing indices are saved in documents; append new entries without reordering
+ pub const ALL: &'static [Self] = &[
+ Self { id: "baseColor", label: "Base color" },
+ Self { id: "normal", label: "Normal" },
+ Self { id: "roughness", label: "Roughness" },
+ Self { id: "metallic", label: "Metallic" },
+ Self { id: "height", label: "Height" },
+ Self { id: "ambientOcclusion", label: "Ambient occlusion" },
+ Self { id: "emissive", label: "Emissive" },
+ Self { id: "opacity", label: "Opacity" },
+ Self { id: "specular", label: "Specular" },
+ Self::ANY,
+ Self { id: "diffuse", label: "Diffuse" },
+ Self { id: "glossiness", label: "Glossiness" },
+ Self { id: "specularLevel", label: "Specular level" },
+ Self { id: "specularEdgeColor", label: "Specular edge color" },
+ Self { id: "anisotropyLevel", label: "Anisotropy level" },
+ Self { id: "anisotropyAngle", label: "Anisotropy angle" },
+ Self { id: "IOR", label: "Index of refraction" },
+ Self { id: "scattering", label: "Scattering" },
+ Self { id: "scatteringColor", label: "Scattering color" },
+ Self { id: "scatteringDistance", label: "Scattering distance" },
+ Self { id: "scatteringDistanceScale", label: "Scattering distance scale" },
+ Self { id: "transmissive", label: "Transmissive" },
+ Self { id: "translucency", label: "Translucency" },
+ Self { id: "absorptionColor", label: "Absorption color" },
+ Self { id: "absorptionDistance", label: "Absorption distance" },
+ Self { id: "coatOpacity", label: "Coat opacity" },
+ Self { id: "coatColor", label: "Coat color" },
+ Self { id: "coatRoughness", label: "Coat roughness" },
+ Self { id: "coatSpecularLevel", label: "Coat specular level" },
+ Self { id: "coatNormal", label: "Coat normal" },
+ Self { id: "coatIOR", label: "Coat index of refraction" },
+ Self { id: "sheenOpacity", label: "Sheen opacity" },
+ Self { id: "sheenColor", label: "Sheen color" },
+ Self { id: "sheenRoughness", label: "Sheen roughness" },
+ Self { id: "reflection", label: "Reflection" },
+ Self { id: "displacement", label: "Displacement" },
+ Self { id: "ambient", label: "Ambient" },
+ Self { id: "mask", label: "Mask" },
+ Self { id: "blendingmask", label: "Blending mask" },
+ Self { id: "bump", label: "Bump" },
+ Self { id: "user0", label: "User 0" },
+ Self { id: "user1", label: "User 1" },
+ Self { id: "user2", label: "User 2" },
+ Self { id: "user3", label: "User 3" },
+ Self { id: "user4", label: "User 4" },
+ Self { id: "user5", label: "User 5" },
+ Self { id: "user6", label: "User 6" },
+ Self { id: "user7", label: "User 7" },
+ ];
+
+ pub const LABELS: &'static [&'static str] = &{
+ let mut labels = [""; Self::ALL.len()];
+ let mut index = 0;
+ while index < labels.len() {
+ labels[index] = Self::ALL[index].label;
+ index += 1;
+ }
+ labels
+ };
+
+ pub fn from_index(index: u32) -> Self {
+ Self::ALL.get(index as usize).copied().unwrap_or(Self::ANY)
+ }
+
+ pub fn index(id: &str) -> u32 {
+ Self::ALL.iter().position(|usage| usage.id.eq_ignore_ascii_case(id.trim())).map_or(Self::ANY_INDEX, |index| index as u32)
+ }
+}
diff --git a/crates/core/src/connection.rs b/crates/core/src/connection.rs
new file mode 100644
index 00000000..1a201bf1
--- /dev/null
+++ b/crates/core/src/connection.rs
@@ -0,0 +1,13 @@
+use serde::{Deserialize, Serialize};
+
+use crate::NodeId;
+
+/// A link from an output port to an input port
+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Connection {
+ pub from: NodeId,
+ pub from_port: String,
+ pub to: NodeId,
+ pub to_port: String,
+}
diff --git a/crates/core/src/core_error.rs b/crates/core/src/core_error.rs
new file mode 100644
index 00000000..3964a222
--- /dev/null
+++ b/crates/core/src/core_error.rs
@@ -0,0 +1,9 @@
+#[derive(Debug, thiserror::Error)]
+pub enum CoreError {
+ #[error("no node {0}")]
+ NoNode(u64),
+ #[error("no graph {0}")]
+ NoGraph(usize),
+ #[error("that connection would make a cycle")]
+ Cycle,
+}
diff --git a/crates/core/src/curve.rs b/crates/core/src/curve.rs
new file mode 100644
index 00000000..73e14e9c
--- /dev/null
+++ b/crates/core/src/curve.rs
@@ -0,0 +1,78 @@
+use serde::{Deserialize, Serialize};
+
+use crate::CurvePoint;
+
+/// A monotone tone curve through sorted control points (linear when it has two points)
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Curve {
+ pub points: Vec,
+}
+
+impl Default for Curve {
+ fn default() -> Self {
+ Curve { points: vec![CurvePoint::new(0.0, 0.0), CurvePoint::new(1.0, 1.0)] }
+ }
+}
+
+impl Curve {
+ pub fn eval(&self, x: f32) -> f32 {
+ let Some(first) = self.points.first() else { return x };
+ if x <= first.x {
+ return first.y;
+ }
+ let Some(index) = self.points.windows(2).position(|points| x <= points[1].x) else {
+ return self.points.last().map_or(x, |point| point.y);
+ };
+
+ let Some([start, control_left, control_right, end]) = self.segment(index) else { return x };
+ let bezier = |axis: usize, t: f32| {
+ let inverse = 1.0 - t;
+ inverse.powi(3) * start[axis] + 3.0 * inverse.powi(2) * t * control_left[axis] + 3.0 * inverse * t * t * control_right[axis] + t.powi(3) * end[axis]
+ };
+
+ let (mut low, mut high) = (0.0, 1.0);
+ for _ in 0..24 {
+ let middle = (low + high) * 0.5;
+ if bezier(0, middle) < x {
+ low = middle;
+ } else {
+ high = middle;
+ }
+ }
+ bezier(1, (low + high) * 0.5)
+ }
+
+ pub fn segment(&self, index: usize) -> Option<[[f32; 2]; 4]> {
+ let left = self.points.get(index)?;
+ let right = self.points.get(index.checked_add(1)?)?;
+ let span = (right.x - left.x).max(1e-6);
+ let slope = |index: usize| {
+ let left = self.points.get(index.saturating_sub(1));
+ let right = self.points.get((index + 1).min(self.points.len().saturating_sub(1)));
+ match (left, right) {
+ (Some(left), Some(right)) if (right.x - left.x).abs() > 1e-6 => (right.y - left.y) / (right.x - left.x),
+ _ => 0.0,
+ }
+ };
+
+ let secant = (right.y - left.y) / span;
+ let mut slopes = [slope(index), slope(index + 1)];
+ if secant == 0.0 {
+ slopes = [0.0; 2];
+ } else {
+ for slope in &mut slopes {
+ if *slope * secant < 0.0 {
+ *slope = 0.0;
+ }
+ }
+ let length_squared = (slopes[0] / secant).powi(2) + (slopes[1] / secant).powi(2);
+ if length_squared > 9.0 {
+ slopes = slopes.map(|slope| slope * 3.0 / length_squared.sqrt());
+ }
+ }
+
+ let left_handle = left.right.unwrap_or([left.x + span / 3.0, left.y + slopes[0] * span / 3.0]);
+ let right_handle = right.left.unwrap_or([right.x - span / 3.0, right.y - slopes[1] * span / 3.0]);
+ Some([[left.x, left.y], left_handle, right_handle, [right.x, right.y]])
+ }
+}
diff --git a/crates/core/src/curve_point.rs b/crates/core/src/curve_point.rs
new file mode 100644
index 00000000..e9d53f9e
--- /dev/null
+++ b/crates/core/src/curve_point.rs
@@ -0,0 +1,18 @@
+use serde::{Deserialize, Serialize};
+
+/// One control point of a [`Curve`]: position and value, both 0..1
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CurvePoint {
+ pub x: f32,
+ pub y: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub left: Option<[f32; 2]>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub right: Option<[f32; 2]>,
+}
+
+impl CurvePoint {
+ pub fn new(x: f32, y: f32) -> Self {
+ Self { x, y, left: None, right: None }
+ }
+}
diff --git a/crates/core/src/exposed_parameter.rs b/crates/core/src/exposed_parameter.rs
new file mode 100644
index 00000000..43d663af
--- /dev/null
+++ b/crates/core/src/exposed_parameter.rs
@@ -0,0 +1,26 @@
+use serde::{Deserialize, Serialize};
+
+use crate::Value;
+
+/// The kind of value an exposed graph input carries
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ExposedParameter {
+ /// Identifier, unique in the graph
+ pub id: String,
+ pub label: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub group: String,
+ pub default: Value,
+ #[serde(default)]
+ pub min: f32,
+ #[serde(default = "one")]
+ pub max: f32,
+ /// Labels when the value is an enum
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub options: Vec,
+}
+
+fn one() -> f32 {
+ 1.0
+}
diff --git a/crates/core/src/frame.rs b/crates/core/src/frame.rs
new file mode 100644
index 00000000..f7e74738
--- /dev/null
+++ b/crates/core/src/frame.rs
@@ -0,0 +1,31 @@
+use serde::{Deserialize, Serialize};
+
+/// A titled, colored rectangle behind a group of nodes
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Frame {
+ pub id: u64,
+ pub title: String,
+ #[serde(default = "default_title_visible")]
+ pub title_visible: bool,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub description: String,
+ /// `[x, y, width, height]` in graph space
+ pub rect: [f32; 4],
+ /// Linear RGBA (alpha is the fill opacity)
+ pub color: [f32; 4],
+}
+
+fn default_title_visible() -> bool {
+ true
+}
+
+impl Frame {
+ pub fn contains_position(&self, position: [f32; 2]) -> bool {
+ let [x, y, width, height] = self.rect;
+ position[0] >= x && position[1] >= y && position[0] <= x + width && position[1] <= y + height
+ }
+
+ pub fn contains_rect(&self, rect: [f32; 4]) -> bool {
+ self.contains_position([rect[0], rect[1]]) && self.contains_position([rect[0] + rect[2], rect[1] + rect[3]])
+ }
+}
diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs
new file mode 100644
index 00000000..11f2aa71
--- /dev/null
+++ b/crates/core/src/function_graph.rs
@@ -0,0 +1,67 @@
+use serde::{Deserialize, Serialize};
+
+use crate::Value;
+
+use crate::FunctionNode;
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct FunctionGraph {
+ pub nodes: Vec,
+ #[serde(default)]
+ pub output: Option,
+}
+
+impl FunctionGraph {
+ pub fn node(&self, id: u32) -> Option<&FunctionNode> {
+ self.nodes.iter().find(|node| node.id == id)
+ }
+
+ pub fn next_id(&self) -> u32 {
+ let maximum = self.nodes.iter().map(|node| node.id).max().unwrap_or(0);
+ if let Some(next) = maximum.checked_add(1) {
+ return next;
+ }
+
+ (1..=u32::MAX).find(|id| self.node(*id).is_none()).unwrap_or(0)
+ }
+
+ pub fn add(&mut self, operation: &str, inputs: &[u32], value: Option) -> u32 {
+ let id = self.next_id();
+ let horizontal_position = self.nodes.len() as f32 * 140.0;
+ let node =
+ FunctionNode { id, type_code: 0, op: operation.into(), inputs: inputs.iter().copied().map(Some).collect(), value, pos: [horizontal_position, 0.0] };
+
+ self.nodes.push(node);
+ id
+ }
+
+ pub fn constant(value: Value) -> FunctionGraph {
+ let mut graph = FunctionGraph::default();
+ graph.output = Some(graph.add_constant(value));
+ graph
+ }
+
+ pub fn add_constant(&mut self, value: Value) -> u32 {
+ let operation = match &value {
+ Value::Float(_) => "const_float1",
+ Value::Float2(_) => "const_float2",
+ Value::Float3(_) => "const_float3",
+ Value::Float4(_) | Value::Color(_) => "const_float4",
+ Value::Int(_) | Value::Enum(_) => "const_int1",
+ Value::Int2(_) => "const_int2",
+ Value::Int3(_) => "const_int3",
+ Value::Int4(_) => "const_int4",
+ Value::Text(_) => "const_string",
+ Value::Bool(_) => "const_bool",
+ _ => "const_float1",
+ };
+
+ let value = match value {
+ Value::Color(color) => Value::Float4(color),
+ Value::Enum(index) => Value::Int(index.min(i32::MAX as u32) as i32),
+ value => value,
+ };
+
+ self.add(operation, &[], Some(value))
+ }
+}
diff --git a/crates/core/src/function_node.rs b/crates/core/src/function_node.rs
new file mode 100644
index 00000000..54976958
--- /dev/null
+++ b/crates/core/src/function_node.rs
@@ -0,0 +1,19 @@
+use serde::{Deserialize, Serialize};
+
+use crate::Value;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct FunctionNode {
+ pub id: u32,
+ // Zero requests type inference
+ #[serde(default)]
+ pub type_code: u32,
+ pub op: String,
+ // Slots follow the native operation's connector order
+ #[serde(default)]
+ pub inputs: Vec>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub value: Option,
+ #[serde(default)]
+ pub pos: [f32; 2],
+}
diff --git a/crates/core/src/gradient.rs b/crates/core/src/gradient.rs
new file mode 100644
index 00000000..38dcaf32
--- /dev/null
+++ b/crates/core/src/gradient.rs
@@ -0,0 +1,41 @@
+use serde::{Deserialize, Serialize};
+
+use crate::GradientKey;
+
+/// A color ramp (gradient map)
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Gradient {
+ pub keys: Vec,
+}
+
+impl Default for Gradient {
+ fn default() -> Self {
+ Gradient { keys: vec![GradientKey::new(0.0, [0.0, 0.0, 0.0, 1.0]), GradientKey::new(1.0, [1.0, 1.0, 1.0, 1.0])] }
+ }
+}
+
+impl Gradient {
+ /// Linear interpolation between the sorted keys
+ pub fn eval(&self, t: f32) -> [f32; 4] {
+ let k = &self.keys;
+ let Some(first) = k.first() else { return [t, t, t, 1.0] };
+ if t <= first.pos {
+ return first.color;
+ }
+ for w in k.windows(2) {
+ if t <= w[1].pos {
+ let span = (w[1].pos - w[0].pos).max(1e-6);
+ let midpoint = w[0].midpoint.clamp(0.001, 0.999);
+ let f = ((t - w[0].pos) / span).clamp(0.0, 1.0).powf(0.5_f32.ln() / midpoint.ln());
+ let (a, b) = (w[0].color, w[1].color);
+ return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f];
+ }
+ }
+ k.last().map_or([t, t, t, 1.0], |l| l.color)
+ }
+
+ /// Keys sorted by position (call after editing)
+ pub fn sort(&mut self) {
+ self.keys.sort_by(|a, b| a.pos.total_cmp(&b.pos));
+ }
+}
diff --git a/crates/core/src/gradient_key.rs b/crates/core/src/gradient_key.rs
new file mode 100644
index 00000000..aa13939b
--- /dev/null
+++ b/crates/core/src/gradient_key.rs
@@ -0,0 +1,20 @@
+use serde::{Deserialize, Serialize};
+
+/// One stop of a [`Gradient`]: position 0..1 and linear RGBA
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct GradientKey {
+ pub pos: f32,
+ pub color: [f32; 4],
+ #[serde(default = "midpoint")]
+ pub midpoint: f32,
+}
+
+fn midpoint() -> f32 {
+ 0.5
+}
+
+impl GradientKey {
+ pub fn new(pos: f32, color: [f32; 4]) -> Self {
+ Self { pos, color, midpoint: 0.5 }
+ }
+}
diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs
index adc90b6d..2c659bc1 100644
--- a/crates/core/src/graph.rs
+++ b/crates/core/src/graph.rs
@@ -1,254 +1,17 @@
-//! Graphs: nodes, connections, frames, comments, navigation pins and exposed inputs.
-
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{CoreError, Result, Value};
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
-pub struct NodeId(pub u64);
-
-/// How a node's output size follows its surroundings ("Output size" base parameter).
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum SizeMode {
- /// The size of the main (first connected) input; the graph size when none is connected.
- #[default]
- RelativeToInput,
- /// The graph ("parent") size.
- RelativeToParent,
- /// `offset` is the absolute log2 size (e.g. 10 = 1024 px).
- Absolute,
-}
-
-/// The output bit depth ("Output format").
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum OutputFormat {
- /// The main input's format; 16 bits for generators.
- #[default]
- Inherit,
- U8,
- U16,
- F16,
- F32,
-}
-
-impl OutputFormat {
- pub const ALL: [OutputFormat; 5] = [OutputFormat::Inherit, OutputFormat::U8, OutputFormat::U16, OutputFormat::F16, OutputFormat::F32];
-
- pub fn label(self) -> &'static str {
- match self {
- OutputFormat::Inherit => "Relative to input",
- OutputFormat::U8 => "8 bits per channel",
- OutputFormat::U16 => "16 bits per channel",
- OutputFormat::F16 => "16 bits per channel float (HDR)",
- OutputFormat::F32 => "32 bits per channel float (HDR)",
- }
- }
-
- /// The suffix of a node's size label: `8`, `16`, `16F`, `32F`.
- pub fn bits(self) -> &'static str {
- match self {
- OutputFormat::Inherit | OutputFormat::U16 => "16",
- OutputFormat::U8 => "8",
- OutputFormat::F16 => "16F",
- OutputFormat::F32 => "32F",
- }
- }
-}
-
-/// Parameters every node has ("Base parameters").
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(default, rename_all = "camelCase")]
-pub struct BaseParams {
- pub size_mode: SizeMode,
- /// log2 offset per axis (relative modes) or log2 size (absolute).
- pub size: [i32; 2],
- pub format: OutputFormat,
- /// Added to the graph's random seed for this node.
- pub seed: i32,
- /// Whether sampling wraps at the edges (horizontal, vertical).
- pub tiling: [bool; 2],
-}
-
-impl Default for BaseParams {
- fn default() -> Self {
- BaseParams { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] }
- }
-}
-
-/// A node instance: a catalog definition (`def`) with parameter overrides.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Node {
- pub id: NodeId,
- /// Catalog id, e.g. `blend`, `perlin_noise`, `output`, `input_color`, `graph_instance`.
- pub def: String,
- /// User label; empty = the definition's label.
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub label: String,
- /// Graph-space position of the node's top-left corner.
- pub pos: [f32; 2],
- /// Values that differ from the catalog defaults.
- #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
- pub params: BTreeMap,
- /// Parameters driven by a graph input (param id → exposed input id).
- #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
- pub bindings: BTreeMap,
- /// Dynamic parameters: param id → a function graph computing its value from the graph's
- /// inputs at cook time.
- #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
- pub functions: BTreeMap,
- #[serde(default)]
- pub base: BaseParams,
- /// A disabled node passes its first input through.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub disabled: bool,
-}
-
-impl Node {
- pub fn new(id: NodeId, def: &str, pos: [f32; 2]) -> Node {
- Node {
- id,
- def: def.into(),
- label: String::new(),
- pos,
- params: BTreeMap::new(),
- bindings: BTreeMap::new(),
- functions: BTreeMap::new(),
- base: BaseParams::default(),
- disabled: false,
- }
- }
-}
-
-/// The definition id of a placeholder for a node MaterialCraft does not have (a library node or
-/// atomic filter named in an SBS file). The node keeps its wires and the data needed to write it
-/// back; its ports come from [`missing_ports`] and it cooks to a soft error.
-pub const MISSING_NODE: &str = "missing_node";
-
-/// The ports of a [`MISSING_NODE`] placeholder: input ids, and output ids with whether each is
-/// grayscale. They are stored as comma-separated text in its `inputs` and `outputs` parameters
-/// (`outputs` entries are `id` or `id:gray`).
-pub fn missing_ports(node: &Node) -> (Vec, Vec<(String, bool)>) {
- let list = |key: &str| -> Vec {
- match node.params.get(key) {
- Some(Value::Text(s)) => s.split(',').map(str::trim).filter(|p| !p.is_empty()).take(64).map(str::to_string).collect(),
- _ => Vec::new(),
- }
- };
- let outputs = list("outputs")
- .into_iter()
- .map(|o| match o.split_once(':') {
- Some((id, kind)) => (id.to_string(), kind == "gray"),
- None => (o, false),
- })
- .collect();
- (list("inputs"), outputs)
-}
-
-/// A link from an output port to an input port.
-#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Connection {
- pub from: NodeId,
- pub from_port: String,
- pub to: NodeId,
- pub to_port: String,
-}
-
-/// A titled, colored rectangle behind a group of nodes.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Frame {
- pub id: u64,
- pub title: String,
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub description: String,
- /// `[x, y, width, height]` in graph space.
- pub rect: [f32; 4],
- /// Linear RGBA (alpha is the fill opacity).
- pub color: [f32; 4],
-}
-
-/// A sticky note on the canvas.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Comment {
- pub id: u64,
- pub text: String,
- pub pos: [f32; 2],
- #[serde(default = "comment_size")]
- pub size: [f32; 2],
-}
-
-fn comment_size() -> [f32; 2] {
- [180.0, 70.0]
-}
-
-/// A named bookmark on the canvas (Previous/Next pin).
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Pin {
- pub id: u64,
- pub name: String,
- pub pos: [f32; 2],
-}
-
-/// The kind of value an exposed graph input carries.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ExposedParam {
- /// Identifier, unique in the graph.
- pub id: String,
- pub label: String,
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub group: String,
- pub default: Value,
- #[serde(default)]
- pub min: f32,
- #[serde(default = "one")]
- pub max: f32,
- /// Labels when the value is an enum.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub options: Vec,
-}
-
-fn one() -> f32 {
- 1.0
-}
-
-/// A named set of input values (graph presets).
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Preset {
- pub name: String,
- pub values: BTreeMap,
-}
-
-/// Descriptive metadata ("Attributes").
-#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
-#[serde(default, rename_all = "camelCase")]
-pub struct Attributes {
- pub category: String,
- pub description: String,
- pub author: String,
- pub tags: String,
-}
-
-/// Whether a graph makes images or is a function.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum GraphKind {
- #[default]
- Material,
- Function,
-}
+use crate::{Attributes, Comment, Connection, ExposedParameter, Frame, GraphKind, Node, NodeId, OutputFormat, Pin, Preset};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Graph {
pub name: String,
#[serde(default)]
- pub kind: GraphKind,
+ pub function: Option,
pub nodes: Vec,
pub connections: Vec,
#[serde(default)]
@@ -257,34 +20,31 @@ pub struct Graph {
pub comments: Vec,
#[serde(default)]
pub pins: Vec,
- /// log2 of the graph ("parent") size per axis.
+ /// log2 of the graph ("parent") size per axis
pub size: [u32; 2],
#[serde(default)]
pub format: OutputFormat,
#[serde(default)]
pub seed: i32,
#[serde(default)]
- pub exposed: Vec,
- /// Current values of the exposed inputs (missing = default).
+ pub exposed: Vec,
+ /// Current values of the exposed inputs (missing = default)
#[serde(default)]
pub inputs: BTreeMap,
- /// Named sets of input values.
+ /// Named sets of input values
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub presets: Vec,
- /// Preview images of the graph's input nodes: identifier → bitmap resource (a mesh map
- /// baked in TextureCraft, say). Instances feed their inputs from their ports instead.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub input_images: BTreeMap,
- /// Identifiers whose preview image is a data map, read as stored rather than sRGB-decoded.
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub input_images_linear: BTreeSet,
#[serde(default)]
pub attributes: Attributes,
- /// The id the next node, frame, comment or pin gets.
+ /// The id the next node, frame, comment or pin gets
pub next_id: u64,
}
-/// Smallest and largest graph size, as log2 (16 px .. 8192 px).
+/// Smallest and largest graph size, as log2 (16 px .. 8192 px)
pub const MIN_SIZE_LOG2: u32 = 4;
pub const MAX_SIZE_LOG2: u32 = 13;
@@ -292,7 +52,7 @@ impl Graph {
pub fn new(name: &str) -> Graph {
Graph {
name: name.into(),
- kind: GraphKind::Material,
+ function: None,
nodes: Vec::new(),
connections: Vec::new(),
frames: Vec::new(),
@@ -311,6 +71,10 @@ impl Graph {
}
}
+ pub fn kind(&self) -> GraphKind {
+ if self.function.is_some() { GraphKind::Function } else { GraphKind::Material }
+ }
+
pub fn alloc_id(&mut self) -> u64 {
let id = self.next_id;
self.next_id = self.next_id.saturating_add(1);
@@ -325,21 +89,19 @@ impl Graph {
self.nodes.iter_mut().find(|n| n.id == id).ok_or(CoreError::NoNode(id.0))
}
- /// Add a node of definition `def` at `pos`; returns its id.
+ /// Add a node of definition `def` at `pos`; returns its id
pub fn add_node(&mut self, def: &str, pos: [f32; 2]) -> NodeId {
let id = NodeId(self.alloc_id());
self.nodes.push(Node::new(id, def, pos));
id
}
- /// Remove nodes and every connection touching them.
+ /// Remove nodes and every connection touching them
pub fn remove_nodes(&mut self, ids: &[NodeId]) {
self.nodes.retain(|n| !ids.contains(&n.id));
self.connections.retain(|c| !ids.contains(&c.from) && !ids.contains(&c.to));
}
- /// Connect `from.from_port` → `to.to_port`, replacing whatever fed that input. Refuses
- /// connections that would make a cycle.
pub fn connect(&mut self, from: NodeId, from_port: &str, to: NodeId, to_port: &str) -> Result<()> {
self.node(from)?;
self.node(to)?;
@@ -357,12 +119,12 @@ impl Graph {
before != self.connections.len()
}
- /// The connection feeding `to.to_port`.
+ /// The connection feeding `to.to_port`
pub fn input_of(&self, to: NodeId, to_port: &str) -> Option<&Connection> {
self.connections.iter().find(|c| c.to == to && c.to_port == to_port)
}
- /// Whether `b` is downstream of (or equal to) `a`.
+ /// Whether `b` is downstream of (or equal to) `a`
pub fn reaches(&self, a: NodeId, b: NodeId) -> bool {
let mut stack = vec![a];
let mut seen = std::collections::BTreeSet::new();
@@ -378,69 +140,26 @@ impl Graph {
false
}
- /// Nodes in dependency order (inputs before the nodes they feed). Nodes on a cycle (only
- /// possible in a hand-edited file) are left out.
pub fn topo_order(&self) -> Vec {
- let mut indeg: BTreeMap = self.nodes.iter().map(|n| (n.id, 0)).collect();
- for c in &self.connections {
- if let Some(d) = indeg.get_mut(&c.to)
- && self.nodes.iter().any(|n| n.id == c.from)
- {
- *d += 1;
- }
- }
- let mut ready: Vec = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect();
- let mut out = Vec::with_capacity(self.nodes.len());
- while let Some(n) = ready.pop() {
- out.push(n);
- for c in self.connections.iter().filter(|c| c.from == n) {
- if let Some(d) = indeg.get_mut(&c.to) {
- *d = d.saturating_sub(1);
- if *d == 0 {
- ready.push(c.to);
- }
- }
- }
- }
- out
+ crate::GraphIndex::new(self).topo_order()
}
- /// Every node upstream of `id` (not including it).
+ /// Every node upstream of `id` (not including it)
pub fn upstream(&self, id: NodeId) -> Vec {
- let mut out = Vec::new();
- let mut stack = vec![id];
- while let Some(n) = stack.pop() {
- for c in self.connections.iter().filter(|c| c.to == n) {
- if !out.contains(&c.from) {
- out.push(c.from);
- stack.push(c.from);
- }
- }
- }
- out
+ crate::GraphIndex::new(self).upstream(id)
}
- /// Every node downstream of `id` (not including it).
+ /// Every node downstream of `id` (not including it)
pub fn downstream(&self, id: NodeId) -> Vec {
- let mut out = Vec::new();
- let mut stack = vec![id];
- while let Some(n) = stack.pop() {
- for c in self.connections.iter().filter(|c| c.from == n) {
- if !out.contains(&c.to) {
- out.push(c.to);
- stack.push(c.to);
- }
- }
- }
- out
+ crate::GraphIndex::new(self).downstream(id)
}
- /// The value of exposed input `id` (its default when unset).
+ /// The value of exposed input `id` (its default when unset)
pub fn input_value(&self, id: &str) -> Option<&Value> {
self.inputs.get(id).or_else(|| self.exposed.iter().find(|e| e.id == id).map(|e| &e.default))
}
- /// Graph size in pixels.
+ /// Graph size in pixels
pub fn size_px(&self) -> [u32; 2] {
[1 << self.size[0].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), 1 << self.size[1].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)]
}
@@ -448,7 +167,7 @@ impl Graph {
#[cfg(test)]
mod tests {
- use super::*;
+ use crate::*;
#[test]
fn connect_refuses_cycles_and_replaces_inputs() {
diff --git a/crates/core/src/graph_index.rs b/crates/core/src/graph_index.rs
new file mode 100644
index 00000000..56354b17
--- /dev/null
+++ b/crates/core/src/graph_index.rs
@@ -0,0 +1,133 @@
+use std::collections::{BTreeMap, BTreeSet};
+
+use crate::{Connection, Graph, Node, NodeId};
+
+/// Borrowed lookups for one graph operation, rebuilt when the graph changes
+pub struct GraphIndex<'a> {
+ nodes: BTreeMap,
+ incoming: BTreeMap>,
+ outgoing: BTreeMap>,
+}
+
+impl<'a> GraphIndex<'a> {
+ pub fn new(graph: &'a Graph) -> Self {
+ let mut nodes = BTreeMap::new();
+ for node in &graph.nodes {
+ nodes.entry(node.id).or_insert(node);
+ }
+
+ let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
+ let mut outgoing: BTreeMap<_, Vec<_>> = BTreeMap::new();
+ for connection in &graph.connections {
+ incoming.entry(connection.to).or_default().push(connection);
+ outgoing.entry(connection.from).or_default().push(connection);
+ }
+
+ Self { nodes, incoming, outgoing }
+ }
+
+ pub fn node(&self, id: NodeId) -> Option<&'a Node> {
+ self.nodes.get(&id).copied()
+ }
+
+ pub fn incoming(&self, id: NodeId) -> &[&'a Connection] {
+ self.incoming.get(&id).map_or(&[], Vec::as_slice)
+ }
+
+ pub fn input_of(&self, id: NodeId, port: &str) -> Option<&'a Connection> {
+ self.incoming(id).iter().copied().find(|connection| connection.to_port == port)
+ }
+
+ pub fn topo_order(&self) -> Vec {
+ let mut degrees: BTreeMap<_, _> = self.nodes.keys().map(|id| (*id, 0usize)).collect();
+ for (id, connections) in &self.incoming {
+ if let Some(degree) = degrees.get_mut(id) {
+ *degree = connections.iter().filter(|connection| self.nodes.contains_key(&connection.from)).count();
+ }
+ }
+
+ let mut ready: Vec<_> = degrees.iter().filter(|(_, degree)| **degree == 0).map(|(id, _)| *id).collect();
+ let mut ordered = Vec::with_capacity(self.nodes.len());
+ while let Some(id) = ready.pop() {
+ ordered.push(id);
+ for connection in self.outgoing.get(&id).into_iter().flatten() {
+ if let Some(degree) = degrees.get_mut(&connection.to) {
+ *degree = degree.saturating_sub(1);
+ if *degree == 0 {
+ ready.push(connection.to);
+ }
+ }
+ }
+ }
+
+ ordered
+ }
+
+ pub fn upstream(&self, id: NodeId) -> Vec {
+ self.connected(id, true)
+ }
+
+ pub fn downstream(&self, id: NodeId) -> Vec {
+ self.connected(id, false)
+ }
+
+ pub fn required_nodes(&self, roots: &[NodeId]) -> BTreeSet {
+ let mut required: BTreeSet<_> = roots.iter().copied().collect();
+ let mut pending = roots.to_vec();
+ while let Some(id) = pending.pop() {
+ for connection in self.incoming(id) {
+ if required.insert(connection.from) {
+ pending.push(connection.from);
+ }
+ }
+ }
+
+ required
+ }
+
+ fn connected(&self, root: NodeId, upstream: bool) -> Vec {
+ let adjacency = if upstream { &self.incoming } else { &self.outgoing };
+
+ let mut visited = BTreeSet::new();
+ let mut connected = Vec::new();
+ let mut pending = vec![root];
+ while let Some(id) = pending.pop() {
+ for connection in adjacency.get(&id).into_iter().flatten() {
+ let next = if upstream { connection.from } else { connection.to };
+
+ if visited.insert(next) {
+ connected.push(next);
+ pending.push(next);
+ }
+ }
+ }
+
+ connected
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn traversal_preserves_document_order_and_dangling_edge_behavior() {
+ let mut graph = Graph::new("Traversal");
+ let first = graph.add_node("uniform", [0.0; 2]);
+ let second = graph.add_node("dot", [0.0; 2]);
+ let third = graph.add_node("blend", [0.0; 2]);
+ let fourth = graph.add_node("dot", [0.0; 2]);
+ for (from, to, port) in [(first, second, "input"), (first, third, "foreground"), (second, third, "background"), (NodeId(99), fourth, "input")] {
+ graph.connections.push(Connection { from, from_port: "output".into(), to, to_port: port.into() });
+ }
+ let index = GraphIndex::new(&graph);
+ assert_eq!(index.topo_order(), [fourth, first, second, third]);
+ assert_eq!(index.upstream(third), [first, second]);
+ assert_eq!(index.downstream(first), [second, third]);
+ assert_eq!(index.required_nodes(&[third, fourth]), BTreeSet::from([first, second, third, fourth, NodeId(99)]));
+ assert_eq!(index.input_of(third, "background").unwrap().from, second);
+
+ graph.connections.push(Connection { from: third, from_port: "output".into(), to: first, to_port: "input".into() });
+ assert_eq!(GraphIndex::new(&graph).topo_order(), [fourth]);
+ }
+}
diff --git a/crates/core/src/graph_kind.rs b/crates/core/src/graph_kind.rs
new file mode 100644
index 00000000..5f0551aa
--- /dev/null
+++ b/crates/core/src/graph_kind.rs
@@ -0,0 +1,10 @@
+use serde::{Deserialize, Serialize};
+
+/// Whether a graph makes images or is a function
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum GraphKind {
+ #[default]
+ Material,
+ Function,
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index caa14a9c..3ec6fb6a 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -1,33 +1,77 @@
-//! # materialcraft-core
-//!
-//! The MaterialCraft document model, L0 (pure data, no I/O): a [`Package`] holds [`Graph`]s and
-//! [`Resource`]s; a graph holds [`Node`]s (catalog definitions with parameter overrides),
-//! [`Connection`]s between named ports, frames, comments, navigation pins and exposed inputs.
-//! Parameter values are [`Value`]s; function graphs ([`function::FnGraph`]) drive pixel and value
-//! processors.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
-pub mod function;
-pub mod graph;
-pub mod package;
-pub mod value;
+mod attributes;
+mod base_parameters;
+mod color;
+mod comment;
+mod component_usage;
+mod connection;
+mod core_error;
+mod curve;
+mod curve_point;
+mod exposed_parameter;
+mod frame;
+mod function_graph;
+mod function_node;
+mod gradient;
+mod gradient_key;
+mod graph;
+mod graph_index;
+mod graph_kind;
+mod material_channel;
+mod missing_node;
+mod node;
+mod node_id;
+mod output_format;
+mod package;
+mod pattern_graph;
+mod pattern_node;
+mod pattern_node_kind;
+mod pin;
+mod preset;
+mod resource;
+mod resource_bytes;
+mod size_mode;
+mod value;
+mod value_type;
-pub use graph::{
- Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat,
- Pin, Preset, SizeMode, missing_ports,
-};
-pub use package::{PACKAGE_EXT, Package, Resource, ResourceBytes};
-pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear};
-
-#[derive(Debug, thiserror::Error)]
-pub enum CoreError {
- #[error("no node {0}")]
- NoNode(u64),
- #[error("no graph {0}")]
- NoGraph(usize),
- #[error("that connection would make a cycle")]
- Cycle,
-}
+pub use attributes::Attributes;
+pub use base_parameters::BaseParameters;
+pub use color::{linear_to_srgb, parse_color, srgb_to_linear};
+pub use comment::Comment;
+pub use component_usage::ComponentUsage;
+pub use connection::Connection;
+pub use core_error::CoreError;
+pub use curve::Curve;
+pub use curve_point::CurvePoint;
+pub use exposed_parameter::ExposedParameter;
+pub use frame::Frame;
+pub use function_graph::FunctionGraph;
+pub use function_node::FunctionNode;
+pub use gradient::Gradient;
+pub use gradient_key::GradientKey;
+pub use graph::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2};
+pub use graph_index::GraphIndex;
+pub use graph_kind::GraphKind;
+pub use material_channel::MaterialChannel;
+pub use missing_node::{MISSING_NODE, missing_ports};
+pub use node::Node;
+pub use node_id::NodeId;
+pub use output_format::OutputFormat;
+pub use package::{PACKAGE_EXT, Package};
+pub use pattern_graph::PatternGraph;
+pub use pattern_node::PatternNode;
+pub use pattern_node_kind::PatternNodeKind;
+pub use pin::Pin;
+pub use preset::Preset;
+pub use resource::Resource;
+pub use resource_bytes::ResourceBytes;
+pub use size_mode::SizeMode;
+pub use value::Value;
+pub use value_type::ValueType;
pub type Result = std::result::Result;
+
+#[cfg(test)]
+mod value_tests;
diff --git a/crates/core/src/material_channel.rs b/crates/core/src/material_channel.rs
new file mode 100644
index 00000000..d29a81bd
--- /dev/null
+++ b/crates/core/src/material_channel.rs
@@ -0,0 +1,50 @@
+use serde::{Deserialize, Serialize};
+
+/// Texture channels supported by the material preview
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum MaterialChannel {
+ BaseColor,
+ Normal,
+ Roughness,
+ Metallic,
+ Height,
+ AmbientOcclusion,
+ Emissive,
+ Opacity,
+}
+
+impl MaterialChannel {
+ pub const ALL: [Self; 8] =
+ [Self::BaseColor, Self::Normal, Self::Roughness, Self::Metallic, Self::Height, Self::AmbientOcclusion, Self::Emissive, Self::Opacity];
+
+ pub fn id(self) -> &'static str {
+ match self {
+ Self::BaseColor => "baseColor",
+ Self::Normal => "normal",
+ Self::Roughness => "roughness",
+ Self::Metallic => "metallic",
+ Self::Height => "height",
+ Self::AmbientOcclusion => "ambientOcclusion",
+ Self::Emissive => "emissive",
+ Self::Opacity => "opacity",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::BaseColor => "Base color",
+ Self::Normal => "Normal",
+ Self::Roughness => "Roughness",
+ Self::Metallic => "Metallic",
+ Self::Height => "Height",
+ Self::AmbientOcclusion => "Ambient occlusion",
+ Self::Emissive => "Emissive",
+ Self::Opacity => "Opacity",
+ }
+ }
+
+ pub fn from_id(id: &str) -> Option {
+ Self::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(id)).or_else(|| id.eq_ignore_ascii_case("diffuse").then_some(Self::BaseColor))
+ }
+}
diff --git a/crates/core/src/missing_node.rs b/crates/core/src/missing_node.rs
new file mode 100644
index 00000000..0991800e
--- /dev/null
+++ b/crates/core/src/missing_node.rs
@@ -0,0 +1,22 @@
+use crate::Node;
+use crate::Value;
+
+pub const MISSING_NODE: &str = "missing_node";
+
+pub fn missing_ports(node: &Node) -> (Vec, Vec<(String, bool)>) {
+ let list = |key: &str| -> Vec {
+ match node.params.get(key) {
+ Some(Value::Text(s)) => s.split(',').map(str::trim).filter(|p| !p.is_empty()).take(64).map(str::to_string).collect(),
+ _ => Vec::new(),
+ }
+ };
+
+ let outputs = list("outputs")
+ .into_iter()
+ .map(|o| match o.split_once(':') {
+ Some((id, kind)) => (id.to_string(), kind == "gray"),
+ None => (o, false),
+ })
+ .collect();
+ (list("inputs"), outputs)
+}
diff --git a/crates/core/src/node.rs b/crates/core/src/node.rs
new file mode 100644
index 00000000..3fa105d5
--- /dev/null
+++ b/crates/core/src/node.rs
@@ -0,0 +1,51 @@
+use serde::{Deserialize, Serialize};
+
+use crate::Value;
+use crate::{BaseParameters, NodeId};
+use std::collections::BTreeMap;
+
+/// A node instance: a catalog definition (`def`) with parameter overrides
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Node {
+ pub id: NodeId,
+ /// Catalog id, e.g. `blend`, `pixel_processor`, `output`, `input_color`, `graph_instance`
+ pub def: String,
+ /// User label; empty = the definition's label
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub label: String,
+ /// Graph-space position of the node's top-left corner
+ pub pos: [f32; 2],
+ /// Values that differ from the catalog defaults
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub params: BTreeMap,
+ /// Parameters driven by a graph input (param id → exposed input id)
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub bindings: BTreeMap,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub functions: BTreeMap,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub input_values: BTreeMap,
+ #[serde(default)]
+ pub base: BaseParameters,
+ /// A disabled node passes its first input through
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub disabled: bool,
+}
+
+impl Node {
+ pub fn new(id: NodeId, def: &str, pos: [f32; 2]) -> Node {
+ Node {
+ id,
+ def: def.into(),
+ label: String::new(),
+ pos,
+ params: BTreeMap::new(),
+ bindings: BTreeMap::new(),
+ functions: BTreeMap::new(),
+ input_values: BTreeMap::new(),
+ base: BaseParameters::default(),
+ disabled: false,
+ }
+ }
+}
diff --git a/crates/core/src/node_id.rs b/crates/core/src/node_id.rs
new file mode 100644
index 00000000..9ec90cc0
--- /dev/null
+++ b/crates/core/src/node_id.rs
@@ -0,0 +1,4 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+pub struct NodeId(pub u64);
diff --git a/crates/core/src/output_format.rs b/crates/core/src/output_format.rs
new file mode 100644
index 00000000..c1eae1cc
--- /dev/null
+++ b/crates/core/src/output_format.rs
@@ -0,0 +1,38 @@
+use serde::{Deserialize, Serialize};
+
+/// The output bit depth ("Output format")
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum OutputFormat {
+ /// The main input's format; 16 bits for generators
+ #[default]
+ Inherit,
+ U8,
+ U16,
+ F16,
+ F32,
+}
+
+impl OutputFormat {
+ pub const ALL: [OutputFormat; 5] = [OutputFormat::Inherit, OutputFormat::U8, OutputFormat::U16, OutputFormat::F16, OutputFormat::F32];
+
+ pub fn label(self) -> &'static str {
+ match self {
+ OutputFormat::Inherit => "Relative to input",
+ OutputFormat::U8 => "8 bits per channel",
+ OutputFormat::U16 => "16 bits per channel",
+ OutputFormat::F16 => "16 bits per channel float (HDR)",
+ OutputFormat::F32 => "32 bits per channel float (HDR)",
+ }
+ }
+
+ /// The suffix of a node's size label: `8`, `16`, `16F`, `32F`
+ pub fn bits(self) -> &'static str {
+ match self {
+ OutputFormat::Inherit | OutputFormat::U16 => "16",
+ OutputFormat::U8 => "8",
+ OutputFormat::F16 => "16F",
+ OutputFormat::F32 => "32F",
+ }
+ }
+}
diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs
index 046df379..60021b0d 100644
--- a/crates/core/src/package.rs
+++ b/crates/core/src/package.rs
@@ -1,96 +1,8 @@
-//! Packages: the document. A package holds graphs and the resources (bitmaps) they use.
-
-use std::hash::{DefaultHasher, Hash, Hasher};
-use std::sync::Arc;
-
+use crate::Resource;
+use crate::{CoreError, Graph, Result};
use serde::{Deserialize, Serialize};
-use crate::{CoreError, Graph, Result};
-
-/// The native package extension (a zip: `package.json` plus `resources/`).
-pub const PACKAGE_EXT: &str = "mcraft";
-
-/// An embedded file: a bitmap a Bitmap node shows, or an SVG.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Resource {
- /// Unique name, referenced by nodes (`resource` parameter).
- pub name: String,
- /// File name inside the package's `resources/` folder.
- pub file: String,
- /// The file's bytes (stored in the zip, not in `package.json`).
- #[serde(skip)]
- pub bytes: ResourceBytes,
- /// A linked resource: the file it is read from (relative to the package's folder when it
- /// lies inside it), reloaded by "Reload resources". `None` = embedded in the package.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub link: Option,
-}
-
-impl Resource {
- /// A resource named `name`, stored as `file` in the package.
- pub fn new(name: impl Into, file: impl Into, bytes: ResourceBytes) -> Resource {
- Resource { name: name.into(), file: file.into(), bytes, link: None }
- }
-
- /// A resource that stays on disk at `link` and is read from there.
- pub fn linked(name: impl Into, file: impl Into, bytes: ResourceBytes, link: impl Into) -> Resource {
- Resource { name: name.into(), file: file.into(), bytes, link: Some(link.into()) }
- }
-}
-
-/// A resource's bytes with a hash of their whole content, computed once when the bytes are
-/// set, so caches can key on content (two files of one size are not the same image).
-#[derive(Clone, Debug)]
-pub struct ResourceBytes {
- bytes: Arc>,
- hash: u64,
-}
-
-impl ResourceBytes {
- /// Take ownership of `bytes` and hash them.
- pub fn new(bytes: Vec) -> ResourceBytes {
- let mut h = DefaultHasher::new();
- bytes.hash(&mut h);
- ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) }
- }
-
- /// The bytes.
- pub fn as_slice(&self) -> &[u8] {
- &self.bytes
- }
-
- /// Number of bytes.
- pub fn len(&self) -> usize {
- self.bytes.len()
- }
-
- /// Whether there are no bytes.
- pub fn is_empty(&self) -> bool {
- self.bytes.is_empty()
- }
-
- /// Hash of the whole content.
- pub fn content_hash(&self) -> u64 {
- self.hash
- }
-
- /// Whether both values share one allocation (cheap clones of one file).
- pub fn ptr_eq(&self, other: &ResourceBytes) -> bool {
- Arc::ptr_eq(&self.bytes, &other.bytes)
- }
-}
-
-impl Default for ResourceBytes {
- fn default() -> Self {
- ResourceBytes::new(Vec::new())
- }
-}
-
-impl PartialEq for ResourceBytes {
- fn eq(&self, other: &Self) -> bool {
- self.hash == other.hash && self.bytes == other.bytes
- }
-}
+pub const PACKAGE_EXT: &str = "sbs";
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Package {
@@ -98,7 +10,7 @@ pub struct Package {
pub graphs: Vec,
#[serde(default)]
pub resources: Vec,
- /// Format version of `package.json`.
+ /// Format version of `package.json`
#[serde(default = "version")]
pub version: u32,
}
@@ -137,20 +49,3 @@ impl Package {
(1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string())
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn same_length_same_prefix_bytes_hash_differently() {
- let a = vec![7u8; 200];
- let mut b = a.clone();
- b[150] = 8;
- let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b));
- assert_eq!(a.len(), b.len());
- assert_ne!(a.content_hash(), b.content_hash());
- assert_ne!(a, b);
- assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new()));
- }
-}
diff --git a/crates/core/src/pattern_graph.rs b/crates/core/src/pattern_graph.rs
new file mode 100644
index 00000000..d0275a82
--- /dev/null
+++ b/crates/core/src/pattern_graph.rs
@@ -0,0 +1,108 @@
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet};
+
+use crate::{PatternNode, PatternNodeKind};
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct PatternGraph {
+ pub nodes: Vec,
+ pub root: Option,
+}
+
+impl PatternGraph {
+ pub fn with_root(kind: PatternNodeKind) -> Self {
+ Self {
+ root: Some(1),
+ nodes: vec![PatternNode { id: 1, kind, children: vec![None; kind.child_count()], parameters: BTreeMap::new(), position: [0.0; 2] }],
+ }
+ }
+
+ pub fn add(&mut self, kind: PatternNodeKind) -> Result {
+ if self.nodes.len() >= 4096 {
+ return Err("pattern graph exceeds the 4096-node limit".into());
+ }
+
+ let mut occupied = [false; 4097];
+ for node in &self.nodes {
+ if let Some(slot) = occupied.get_mut(node.id.saturating_sub(1) as usize)
+ && node.id != 0
+ {
+ *slot = true;
+ }
+ }
+ let id = occupied.iter().position(|occupied| !occupied).ok_or("no available pattern node id")? as u32 + 1;
+ self.nodes.push(PatternNode {
+ id,
+ kind,
+ children: vec![None; kind.child_count()],
+ parameters: BTreeMap::new(),
+ position: [self.nodes.len() as f32 * 160.0, 0.0],
+ });
+ self.root.get_or_insert(id);
+ Ok(id)
+ }
+
+ pub fn validate(&self) -> Result<(), String> {
+ if self.nodes.len() > 4096 {
+ return Err("pattern graph exceeds the 4096-node limit".into());
+ }
+
+ let nodes: BTreeMap<_, _> = self.nodes.iter().map(|node| (node.id, node)).collect();
+ if nodes.len() != self.nodes.len() {
+ return Err("duplicate pattern node ids".into());
+ }
+ if self.root.is_some_and(|root| !nodes.contains_key(&root)) {
+ return Err("missing pattern root".into());
+ }
+
+ let mut active = BTreeSet::new();
+ let mut finished = BTreeSet::new();
+ for root in &self.nodes {
+ let mut pending = vec![(root.id, false)];
+ while let Some((id, visited)) = pending.pop() {
+ if finished.contains(&id) {
+ continue;
+ }
+
+ let node = nodes.get(&id).ok_or_else(|| format!("missing pattern node {id}"))?;
+ if node.children.len() != node.kind.child_count() {
+ return Err(format!("{} requires {} child slots", node.kind.label(), node.kind.child_count()));
+ }
+ if visited {
+ active.remove(&id);
+ finished.insert(id);
+ continue;
+ }
+ if !active.insert(id) {
+ return Err(format!("pattern cycle at node {id}"));
+ }
+
+ pending.push((id, true));
+ pending.extend(node.children.iter().rev().flatten().map(|child| (*child, false)));
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn allocation_reuses_the_lowest_hole_and_ignores_out_of_range_ids() {
+ let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ let template = graph.nodes[0].clone();
+ graph.nodes = [0, 2, 4097, u32::MAX].map(|id| PatternNode { id, ..template.clone() }).to_vec();
+ assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 1);
+ assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 3);
+ graph.nodes.retain(|node| node.id != 2);
+ assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 2);
+ assert_eq!(graph.root, Some(1));
+
+ graph.nodes.resize(4096, template);
+ let before = graph.clone();
+ assert!(graph.add(PatternNodeKind::Dot).is_err());
+ assert_eq!(graph, before);
+ }
+}
diff --git a/crates/core/src/pattern_node.rs b/crates/core/src/pattern_node.rs
new file mode 100644
index 00000000..a66afeed
--- /dev/null
+++ b/crates/core/src/pattern_node.rs
@@ -0,0 +1,13 @@
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+use crate::{PatternNodeKind, Value};
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct PatternNode {
+ pub id: u32,
+ pub kind: PatternNodeKind,
+ pub children: Vec>,
+ pub parameters: BTreeMap,
+ pub position: [f32; 2],
+}
diff --git a/crates/core/src/pattern_node_kind.rs b/crates/core/src/pattern_node_kind.rs
new file mode 100644
index 00000000..09d3f045
--- /dev/null
+++ b/crates/core/src/pattern_node_kind.rs
@@ -0,0 +1,50 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum PatternNodeKind {
+ #[serde(rename = "paramset")]
+ Quadrant,
+ #[serde(rename = "markov2")]
+ Switch,
+ #[serde(rename = "addnode")]
+ Iterate,
+ #[serde(rename = "passthrough")]
+ Dot,
+}
+
+impl PatternNodeKind {
+ pub const ALL: [Self; 4] = [Self::Quadrant, Self::Switch, Self::Iterate, Self::Dot];
+
+ pub fn native_id(self) -> &'static str {
+ match self {
+ Self::Quadrant => "paramset",
+ Self::Switch => "markov2",
+ Self::Iterate => "addnode",
+ Self::Dot => "passthrough",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Quadrant => "Quadrant",
+ Self::Switch => "Switch",
+ Self::Iterate => "Iterate",
+ Self::Dot => "Dot",
+ }
+ }
+
+ pub fn child_count(self) -> usize {
+ match self {
+ Self::Quadrant => 4,
+ Self::Switch | Self::Iterate => 2,
+ Self::Dot => 1,
+ }
+ }
+
+ pub fn child_port(self, slot: usize) -> Option<&'static str> {
+ if self == Self::Dot {
+ return (slot == 0).then_some("output");
+ }
+ ["output0", "output1", "output2", "output3"].get(..self.child_count())?.get(slot).copied()
+ }
+}
diff --git a/crates/core/src/pin.rs b/crates/core/src/pin.rs
new file mode 100644
index 00000000..58949ea2
--- /dev/null
+++ b/crates/core/src/pin.rs
@@ -0,0 +1,9 @@
+use serde::{Deserialize, Serialize};
+
+/// A named bookmark on the canvas (Previous/Next pin)
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Pin {
+ pub id: u64,
+ pub name: String,
+ pub pos: [f32; 2],
+}
diff --git a/crates/core/src/preset.rs b/crates/core/src/preset.rs
new file mode 100644
index 00000000..01a8d543
--- /dev/null
+++ b/crates/core/src/preset.rs
@@ -0,0 +1,11 @@
+use serde::{Deserialize, Serialize};
+
+use crate::Value;
+use std::collections::BTreeMap;
+
+/// A named set of input values (graph presets)
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Preset {
+ pub name: String,
+ pub values: BTreeMap,
+}
diff --git a/crates/core/src/resource.rs b/crates/core/src/resource.rs
new file mode 100644
index 00000000..4348c8e7
--- /dev/null
+++ b/crates/core/src/resource.rs
@@ -0,0 +1,30 @@
+use crate::ResourceBytes;
+use serde::{Deserialize, Serialize};
+
+/// An embedded file: a bitmap a Bitmap node shows, or an SVG
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Resource {
+ /// Unique name, referenced by nodes (`resource` parameter)
+ pub name: String,
+ /// File name inside the package's `resources/` folder
+ pub file: String,
+ /// The file's bytes (stored in the zip, not in `package.json`)
+ #[serde(skip)]
+ pub bytes: ResourceBytes,
+ /// A linked resource: the file it is read from (relative to the package's folder when it
+ /// lies inside it), reloaded by "Reload resources". `None` = embedded in the package
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub link: Option,
+}
+
+impl Resource {
+ /// A resource named `name`, stored as `file` in the package
+ pub fn new(name: impl Into, file: impl Into, bytes: ResourceBytes) -> Resource {
+ Resource { name: name.into(), file: file.into(), bytes, link: None }
+ }
+
+ /// A resource that stays on disk at `link` and is read from there
+ pub fn linked(name: impl Into, file: impl Into, bytes: ResourceBytes, link: impl Into) -> Resource {
+ Resource { name: name.into(), file: file.into(), bytes, link: Some(link.into()) }
+ }
+}
diff --git a/crates/core/src/resource_bytes.rs b/crates/core/src/resource_bytes.rs
new file mode 100644
index 00000000..a3efe3b9
--- /dev/null
+++ b/crates/core/src/resource_bytes.rs
@@ -0,0 +1,71 @@
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::sync::Arc;
+
+#[derive(Clone, Debug)]
+pub struct ResourceBytes {
+ bytes: Arc>,
+ hash: u64,
+}
+
+impl ResourceBytes {
+ /// Take ownership of `bytes` and hash them
+ pub fn new(bytes: Vec) -> ResourceBytes {
+ let mut h = DefaultHasher::new();
+ bytes.hash(&mut h);
+ ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) }
+ }
+
+ /// The bytes
+ pub fn as_slice(&self) -> &[u8] {
+ &self.bytes
+ }
+
+ /// Number of bytes
+ pub fn len(&self) -> usize {
+ self.bytes.len()
+ }
+
+ /// Whether there are no bytes
+ pub fn is_empty(&self) -> bool {
+ self.bytes.is_empty()
+ }
+
+ /// Hash of the whole content
+ pub fn content_hash(&self) -> u64 {
+ self.hash
+ }
+
+ /// Whether both values share one allocation (cheap clones of one file)
+ pub fn ptr_eq(&self, other: &ResourceBytes) -> bool {
+ Arc::ptr_eq(&self.bytes, &other.bytes)
+ }
+}
+
+impl Default for ResourceBytes {
+ fn default() -> Self {
+ ResourceBytes::new(Vec::new())
+ }
+}
+
+impl PartialEq for ResourceBytes {
+ fn eq(&self, other: &Self) -> bool {
+ self.hash == other.hash && self.bytes == other.bytes
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::*;
+
+ #[test]
+ fn same_length_same_prefix_bytes_hash_differently() {
+ let a = vec![7u8; 200];
+ let mut b = a.clone();
+ b[150] = 8;
+ let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b));
+ assert_eq!(a.len(), b.len());
+ assert_ne!(a.content_hash(), b.content_hash());
+ assert_ne!(a, b);
+ assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new()));
+ }
+}
diff --git a/crates/core/src/size_mode.rs b/crates/core/src/size_mode.rs
new file mode 100644
index 00000000..792eb56c
--- /dev/null
+++ b/crates/core/src/size_mode.rs
@@ -0,0 +1,14 @@
+use serde::{Deserialize, Serialize};
+
+/// How a node's output size follows its surroundings ("Output size" base parameter)
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SizeMode {
+ /// The size of the main (first connected) input; the graph size when none is connected
+ #[default]
+ RelativeToInput,
+ /// The graph ("parent") size
+ RelativeToParent,
+ /// `offset` is the absolute log2 size (e.g. 10 = 1024 px)
+ Absolute,
+}
diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs
index 033ab2d9..5fb0b821 100644
--- a/crates/core/src/value.rs
+++ b/crates/core/src/value.rs
@@ -1,126 +1,7 @@
-//! Parameter values: the typed data a node parameter, an exposed graph input or a function-graph
-//! constant holds.
-
+use crate::{Curve, CurvePoint, Gradient, GradientKey, parse_color};
use serde::{Deserialize, Serialize};
-/// One control point of a [`Curve`]: position and value, both 0..1.
-#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
-pub struct CurvePoint {
- pub x: f32,
- pub y: f32,
-}
-
-/// A monotone tone curve through sorted control points (linear when it has two points).
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Curve {
- pub points: Vec,
-}
-
-impl Default for Curve {
- fn default() -> Self {
- Curve { points: vec![CurvePoint { x: 0.0, y: 0.0 }, CurvePoint { x: 1.0, y: 1.0 }] }
- }
-}
-
-impl Curve {
- /// Value at `x` (0..1): monotone cubic (Fritsch–Carlson) through the points, clamped ends.
- pub fn eval(&self, x: f32) -> f32 {
- let p = &self.points;
- let n = p.len();
- match n {
- 0 => return x,
- 1 => return p[0].y,
- _ => {}
- }
- if x <= p[0].x {
- return p[0].y;
- }
- if x >= p[n - 1].x {
- return p[n - 1].y;
- }
- let mut i = 0;
- while i + 2 < n && x > p[i + 1].x {
- i += 1;
- }
- let slope = |a: usize| {
- let (l, r) = (a.saturating_sub(1), (a + 1).min(n - 1));
- let dx = p[r].x - p[l].x;
- if dx.abs() < 1e-6 { 0.0 } else { (p[r].y - p[l].y) / dx }
- };
- let (a, b) = (p[i], p[i + 1]);
- let h = (b.x - a.x).max(1e-6);
- let d = (b.y - a.y) / h;
- let (mut m0, mut m1) = (slope(i), slope(i + 1));
- if d == 0.0 {
- m0 = 0.0;
- m1 = 0.0;
- } else {
- // Keep the segment monotone.
- if m0 * d < 0.0 {
- m0 = 0.0;
- }
- if m1 * d < 0.0 {
- m1 = 0.0;
- }
- let (al, be) = (m0 / d, m1 / d);
- let s = al * al + be * be;
- if s > 9.0 {
- let t = 3.0 / s.sqrt();
- m0 = t * al * d;
- m1 = t * be * d;
- }
- }
- let t = (x - a.x) / h;
- let (t2, t3) = (t * t, t * t * t);
- (2.0 * t3 - 3.0 * t2 + 1.0) * a.y + (t3 - 2.0 * t2 + t) * h * m0 + (-2.0 * t3 + 3.0 * t2) * b.y + (t3 - t2) * h * m1
- }
-}
-
-/// One stop of a [`Gradient`]: position 0..1 and linear RGBA.
-#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
-pub struct GradientKey {
- pub pos: f32,
- pub color: [f32; 4],
-}
-
-/// A color ramp (gradient map).
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Gradient {
- pub keys: Vec,
-}
-
-impl Default for Gradient {
- fn default() -> Self {
- Gradient { keys: vec![GradientKey { pos: 0.0, color: [0.0, 0.0, 0.0, 1.0] }, GradientKey { pos: 1.0, color: [1.0, 1.0, 1.0, 1.0] }] }
- }
-}
-
-impl Gradient {
- /// Linear interpolation between the sorted keys.
- pub fn eval(&self, t: f32) -> [f32; 4] {
- let k = &self.keys;
- let Some(first) = k.first() else { return [t, t, t, 1.0] };
- if t <= first.pos {
- return first.color;
- }
- for w in k.windows(2) {
- if t <= w[1].pos {
- let span = (w[1].pos - w[0].pos).max(1e-6);
- let f = ((t - w[0].pos) / span).clamp(0.0, 1.0);
- let (a, b) = (w[0].color, w[1].color);
- return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f];
- }
- }
- k.last().map_or([t, t, t, 1.0], |l| l.color)
- }
-
- /// Keys sorted by position (call after editing).
- pub fn sort(&mut self) {
- self.keys.sort_by(|a, b| a.pos.total_cmp(&b.pos));
- }
-}
-
-/// A typed parameter value.
+/// A typed parameter value
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", content = "v", rename_all = "camelCase")]
pub enum Value {
@@ -130,16 +11,19 @@ pub enum Value {
Float4([f32; 4]),
Int(i32),
Int2([i32; 2]),
+ Int3([i32; 3]),
+ Int4([i32; 4]),
Bool(bool),
- /// Linear RGBA, 0..1.
+ /// Linear RGBA, 0..1
Color([f32; 4]),
- /// Index into the parameter's options.
+ /// Index into the parameter's options
Enum(u32),
Text(String),
Curve(Curve),
Gradient(Gradient),
- /// A function graph (pixel/value processors, dynamic parameters).
- Function(Box),
+ /// A function graph (pixel/value processors, dynamic parameters)
+ Function(Box),
+ PatternGraph(Box),
}
impl Value {
@@ -163,6 +47,8 @@ impl Value {
Value::Float(v) if v.is_finite() => Some(v.round() as i32),
Value::Bool(b) => Some(i32::from(*b)),
Value::Int2(v) => Some(v[0]),
+ Value::Int3(v) => Some(v[0]),
+ Value::Int4(v) => Some(v[0]),
_ => None,
}
}
@@ -176,7 +62,7 @@ impl Value {
}
}
- /// Up to four floats (missing ones are 0; a color keeps its alpha).
+ /// Up to four floats (missing ones are 0; a color keeps its alpha)
pub fn as_vec4(&self) -> Option<[f32; 4]> {
match self {
Value::Float(v) => Some([*v, *v, *v, 1.0]),
@@ -185,11 +71,13 @@ impl Value {
Value::Float4(v) | Value::Color(v) => Some(*v),
Value::Int(v) => Some([*v as f32; 4]),
Value::Int2(v) => Some([v[0] as f32, v[1] as f32, 0.0, 0.0]),
+ Value::Int3(v) => Some([v[0] as f32, v[1] as f32, v[2] as f32, 0.0]),
+ Value::Int4(v) => Some(v.map(|x| x as f32)),
_ => None,
}
}
- /// Short type name, for errors and inspect output.
+ /// Short type name, for errors and inspect output
pub fn type_name(&self) -> &'static str {
match self {
Value::Float(_) => "float",
@@ -198,6 +86,8 @@ impl Value {
Value::Float4(_) => "float4",
Value::Int(_) => "int",
Value::Int2(_) => "int2",
+ Value::Int3(_) => "int3",
+ Value::Int4(_) => "int4",
Value::Bool(_) => "bool",
Value::Color(_) => "color",
Value::Enum(_) => "enum",
@@ -205,10 +95,11 @@ impl Value {
Value::Curve(_) => "curve",
Value::Gradient(_) => "gradient",
Value::Function(_) => "function",
+ Value::PatternGraph(_) => "patternGraph",
}
}
- /// Coerce a JSON value (from a command or MCP call) into the type of `self`.
+ /// Coerce a JSON value (from a command or MCP call) into the type of `self`
pub fn coerce_json(&self, j: &serde_json::Value) -> Option {
use serde_json::Value as J;
let f = |v: &J| v.as_f64().map(|x| x as f32).filter(|x| x.is_finite());
@@ -219,12 +110,12 @@ impl Value {
_ => None,
}
};
- // A typed value as the API writes it ({"t": .., "v": ..}).
+ // A typed value as the API writes it ({"t": .., "v": ..})
if let Ok(v) = serde_json::from_value::(j.clone()) {
if v.type_name() == self.type_name() {
return Some(v);
}
- // Another type (a float input bound to an int parameter): coerce its payload.
+ // Another type (a float input bound to an int parameter): coerce its payload
return j.get("v").and_then(|p| self.coerce_json(p));
}
Some(match self {
@@ -242,104 +133,50 @@ impl Value {
Value::Float4([a[0], a[1], a[2], a[3]])
}
Value::Color(_) => Value::Color(parse_color(j)?),
- Value::Int(_) => Value::Int(f(j)?.round() as i32),
- Value::Int2(_) => {
- let a = arr(2)?;
- Value::Int2([a[0].round() as i32, a[1].round() as i32])
- }
+ Value::Int(_) => Value::Int(match j.as_i64() {
+ Some(value) => i32::try_from(value).ok()?,
+ None => {
+ let value = j.as_f64()?.round();
+ if !value.is_finite() || value < i32::MIN as f64 || value > i32::MAX as f64 {
+ return None;
+ }
+ value as i32
+ }
+ }),
+ Value::Int2(_) => Value::Int2(parse_integers(j)?),
+ Value::Int3(_) => Value::Int3(parse_integers(j)?),
+ Value::Int4(_) => Value::Int4(parse_integers(j)?),
Value::Bool(_) => Value::Bool(j.as_bool().or_else(|| f(j).map(|v| v != 0.0))?),
Value::Enum(_) => Value::Enum(u32::try_from(j.as_u64()?).ok()?),
Value::Text(_) => Value::Text(j.as_str()?.to_string()),
Value::Curve(_) => {
let pts: Vec<[f32; 2]> = serde_json::from_value(j.clone()).ok()?;
let mut points: Vec =
- pts.into_iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| CurvePoint { x: p[0], y: p[1] }).collect();
+ pts.into_iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| CurvePoint::new(p[0], p[1])).collect();
points.sort_by(|a, b| a.x.total_cmp(&b.x));
Value::Curve(Curve { points })
}
Value::Gradient(_) => {
let keys: Vec<(f32, serde_json::Value)> = serde_json::from_value(j.clone()).ok()?;
- let mut g = Gradient { keys: keys.iter().filter_map(|(p, c)| Some(GradientKey { pos: *p, color: parse_color(c)? })).collect() };
+ let mut g = Gradient { keys: keys.iter().filter_map(|(p, c)| Some(GradientKey::new(*p, parse_color(c)?))).collect() };
g.sort();
Value::Gradient(g)
}
- Value::Function(_) => return None,
+ Value::Function(_) | Value::PatternGraph(_) => return None,
})
}
}
-/// `[r, g, b(, a)]` linear floats, a single gray number, or `"#rrggbb(aa)"` (sRGB, converted to linear).
-pub fn parse_color(j: &serde_json::Value) -> Option<[f32; 4]> {
- use serde_json::Value as J;
- match j {
- J::Array(a) if a.len() >= 3 => {
- let v: Vec = a.iter().take(4).filter_map(|x| x.as_f64().map(|x| x as f32)).filter(|x| x.is_finite()).collect();
- if v.len() < 3 {
- return None;
- }
- Some([v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)])
- }
- J::Number(n) => n.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).map(|v| [v, v, v, 1.0]),
- J::String(s) => {
- let s = s.trim_start_matches('#');
- if s.len() != 6 && s.len() != 8 {
- return None;
- }
- let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0);
- let a = if s.len() == 8 { c(6)? } else { 1.0 };
- Some([srgb_to_linear(c(0)?), srgb_to_linear(c(2)?), srgb_to_linear(c(4)?), a])
- }
- _ => None,
- }
-}
-
-/// sRGB transfer function, encoded → linear.
-pub fn srgb_to_linear(v: f32) -> f32 {
- if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
-}
-
-/// sRGB transfer function, linear → encoded.
-pub fn linear_to_srgb(v: f32) -> f32 {
- if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn curve_identity_and_monotone() {
- let c = Curve::default();
- for i in 0..=10 {
- let x = i as f32 / 10.0;
- assert!((c.eval(x) - x).abs() < 1e-4);
- }
- let s =
- Curve { points: vec![CurvePoint { x: 0.0, y: 0.0 }, CurvePoint { x: 0.3, y: 0.1 }, CurvePoint { x: 0.7, y: 0.9 }, CurvePoint { x: 1.0, y: 1.0 }] };
- let mut last = -1.0;
- for i in 0..=100 {
- let v = s.eval(i as f32 / 100.0);
- assert!(v >= last - 1e-5);
- last = v;
- }
+fn parse_integers(value: &serde_json::Value) -> Option<[i32; COUNT]> {
+ let components = value.as_array()?;
+ if components.len() != COUNT {
+ return None;
}
- #[test]
- fn coerce_from_json() {
- assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(0.5)), Some(Value::Float(0.5)));
- assert_eq!(Value::Color([0.0; 4]).coerce_json(&serde_json::json!("#ffffff")), Some(Value::Color([1.0, 1.0, 1.0, 1.0])));
- assert_eq!(Value::Float2([0.0; 2]).coerce_json(&serde_json::json!([1, 2])), Some(Value::Float2([1.0, 2.0])));
- assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!("x")), None);
- assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(f64::MAX)), None);
- // A typed value of another type converts through its payload.
- assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "float", "v": 8.6})), Some(Value::Int(9)));
- assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), None);
+ let mut result = [0; COUNT];
+ for (target, component) in result.iter_mut().zip(components) {
+ *target = i32::try_from(component.as_i64()?).ok()?;
}
- #[test]
- fn gradient_interpolates() {
- let g = Gradient::default();
- assert_eq!(g.eval(0.5), [0.5, 0.5, 0.5, 1.0]);
- assert_eq!(Gradient { keys: vec![] }.eval(0.25)[0], 0.25);
- }
+ Some(result)
}
diff --git a/crates/core/src/value_tests.rs b/crates/core/src/value_tests.rs
new file mode 100644
index 00000000..b3337cd8
--- /dev/null
+++ b/crates/core/src/value_tests.rs
@@ -0,0 +1,36 @@
+use crate::*;
+
+#[test]
+fn curve_identity_and_monotone() {
+ let c = Curve::default();
+ for i in 0..=10 {
+ let x = i as f32 / 10.0;
+ assert!((c.eval(x) - x).abs() < 1e-4);
+ }
+ let s = Curve { points: vec![CurvePoint::new(0.0, 0.0), CurvePoint::new(0.3, 0.1), CurvePoint::new(0.7, 0.9), CurvePoint::new(1.0, 1.0)] };
+ let mut last = -1.0;
+ for i in 0..=100 {
+ let v = s.eval(i as f32 / 100.0);
+ assert!(v >= last - 1e-5);
+ last = v;
+ }
+}
+
+#[test]
+fn coerce_from_json() {
+ assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(0.5)), Some(Value::Float(0.5)));
+ assert_eq!(Value::Color([0.0; 4]).coerce_json(&serde_json::json!("#ffffff")), Some(Value::Color([1.0, 1.0, 1.0, 1.0])));
+ assert_eq!(Value::Float2([0.0; 2]).coerce_json(&serde_json::json!([1, 2])), Some(Value::Float2([1.0, 2.0])));
+ assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!("x")), None);
+ assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(f64::MAX)), None);
+ // A typed value of another type converts through its payload
+ assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "float", "v": 8.6})), Some(Value::Int(9)));
+ assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), None);
+}
+
+#[test]
+fn gradient_interpolates() {
+ let g = Gradient::default();
+ assert_eq!(g.eval(0.5), [0.5, 0.5, 0.5, 1.0]);
+ assert_eq!(Gradient { keys: vec![] }.eval(0.25)[0], 0.25);
+}
diff --git a/crates/core/src/value_type.rs b/crates/core/src/value_type.rs
new file mode 100644
index 00000000..7de04904
--- /dev/null
+++ b/crates/core/src/value_type.rs
@@ -0,0 +1,72 @@
+use crate::Value;
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[repr(u32)]
+pub enum ValueType {
+ Boolean = 4,
+ Integer = 16,
+ Integer2 = 32,
+ Integer3 = 64,
+ Integer4 = 128,
+ Float = 256,
+ Float2 = 512,
+ Float3 = 1024,
+ Float4 = 2048,
+ String = 16384,
+}
+
+impl ValueType {
+ pub const ALL: [Self; 10] =
+ [Self::Float, Self::Float2, Self::Float3, Self::Float4, Self::Integer, Self::Integer2, Self::Integer3, Self::Integer4, Self::Boolean, Self::String];
+
+ pub fn from_code(code: u32) -> Option