@@ -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 9a58e92..0e97d7b 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/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs
index 261ce77..04d93e1 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 ]
@@ -44,8 +42,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.
";
@@ -114,7 +111,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" {
@@ -127,7 +124,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())?;
@@ -183,6 +180,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())?;
@@ -199,6 +197,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);
@@ -242,6 +241,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,
@@ -256,6 +256,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}));
@@ -265,18 +266,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())?;
@@ -294,7 +295,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 4e9b18b..e71470e 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)]
@@ -38,14 +37,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}`")),
@@ -80,6 +79,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}");
@@ -90,8 +90,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() };
@@ -133,11 +132,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 0000000..93c7119
--- /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 0000000..7e2054e
--- /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 bda3b04..99f24a0 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;
@@ -10,51 +9,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: 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,
-}
-
-/// 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 +19,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 +39,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,7 +78,7 @@ 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)?;
@@ -130,7 +86,7 @@ impl Headless {
Ok(materialcraft_engine::execute(&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() {
@@ -143,7 +99,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();
@@ -162,21 +118,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();
@@ -184,7 +140,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)?;
@@ -199,7 +155,7 @@ impl Headless {
Ok(json!({"files": written}))
}
- /// Render the 3D view or a node's 2D output as PNG.
+ /// Render the 3D view or a node's 2D 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;
@@ -213,6 +169,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;
@@ -228,6 +185,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()))
@@ -243,6 +201,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) {
@@ -264,6 +223,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]) };
@@ -274,6 +234,7 @@ impl Headless {
}
_ => None,
};
+
if o.hq {
settings.supersample = 3;
settings.ao_rays = 8;
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index d50b55d..56aa9f4 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 0000000..318619f
--- /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 0000000..3297091
--- /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 1f04a4d..ca3e96b 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -1,14 +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?}`
-//! (workspace-scoped versions of the engine commands), `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};
@@ -67,7 +56,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")),
@@ -101,6 +90,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) }))
}
@@ -112,17 +102,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}`"))));
@@ -132,14 +123,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 {
@@ -151,11 +142,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()?);
@@ -186,20 +178,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);
@@ -209,6 +200,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;
@@ -248,7 +240,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"}]}}"#,
@@ -291,6 +283,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 0000000..0d250b7
--- /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.rs b/crates/automation/src/server/material_craft_mcp.rs
similarity index 56%
rename from crates/automation/src/server.rs
rename to crates/automation/src/server/material_craft_mcp.rs
index 429b57e..383a765 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server/material_craft_mcp.rs
@@ -1,6 +1,4 @@
-//! The MCP server (rmcp). Tool names are `snake_case`; each tool maps to one control-channel
-//! method (see [`crate::rpc`]), answered in process (headless) or by the running app (bridge).
-
+use super::{Backend, parameter::*};
use std::sync::{Arc, Mutex, PoisonError};
use base64::Engine as _;
@@ -8,8 +6,7 @@ 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 schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
+use serde::Serialize;
use serde_json::{Value, json};
use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text};
@@ -18,215 +15,12 @@ use crate::security::MAX_BATCH_STEPS;
use crate::workspace::authorize_command;
use crate::{AutomationError, BridgeClient, Headless, bad};
-/// Where tools run.
-pub enum Backend {
- /// An in-process session.
- Headless(Arc>),
- /// The running desktop app, over its control channel.
- Bridge(Arc),
-}
-
#[derive(Clone)]
-pub struct MaterialcraftMcp {
+pub struct MaterialCraftMcp {
backend: Arc,
tool_router: ToolRouter,
}
-// ---------------------------------------------------------------------------------------------
-// Parameters (serialized back to JSON as the control method's params)
-
-#[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,
-}
-
-#[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,
- /// Only nodes in this library category, e.g. "Noises", "Patterns", "Filters/Blurs".
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub category: Option,
-}
-
-#[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,
-}
-
-#[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,
-}
-
-#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
-pub struct NewGraphParams {
- /// Template id: empty, pbr (default: six material outputs), bricks, stone_tiles, wood, metal_plates, rusty_metal, lava, marble, wicker, fabric, ground.
- #[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,
-}
-
-#[derive(Debug, Deserialize, Serialize, JsonSchema)]
-pub struct NodeAddParams {
- /// Node definition id from `library_list`, e.g. `perlin_noise`, `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,
-}
-
-#[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,
-}
-
-#[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,
-}
-
-#[derive(Debug, Deserialize, Serialize, JsonSchema)]
-pub struct PathParams {
- /// Forward-slash path relative to the workspace root.
- pub path: String,
-}
-
-#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
-pub struct SaveParams {
- /// Forward-slash path relative to the write root (`.sbs` is appended unless it ends in `.sbs`
- /// or `.mcraft`). Omit to save to the package's own file.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub path: Option,
-}
-
-#[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,
-}
-
-#[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,
-}
-
-#[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,
-}
-
-#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
-pub struct ScreenshotParams {
- /// `3d` (default) or `2d`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub view: Option,
-}
-
-#[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,
-}
-
-#[derive(Debug, Deserialize, Serialize, JsonSchema)]
-pub struct InputParams {
- /// Input events in window points, applied in order on the next frames. Each is one of:
- /// {"type":"move","pos":[x,y]}, {"type":"down"|"up","pos":[x,y],"button":"left"|"right"|"middle"},
- /// {"type":"click"|"doubleClick","pos":[x,y],"button"?}, {"type":"drag","from":[x,y],"to":[x,y],"button"?,"steps"?},
- /// {"type":"scroll","pos":[x,y],"delta":[dx,dy]}, {"type":"key","key":"A"|"Enter"|"Space"|…,"modifiers"?:["ctrl","shift","alt"]},
- /// {"type":"text","text":"…"}.
- pub events: Vec,
-}
-
-// ---------------------------------------------------------------------------------------------
-// Results
-
fn ok_json(v: &Value) -> CallToolResult {
match json_text(v) {
Ok(text) => CallToolResult::success(vec![Content::text(text)]),
@@ -245,7 +39,7 @@ fn to_result(r: Result) -> 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()))?;
@@ -266,7 +60,7 @@ fn params(p: &T) -> Value {
serde_json::to_value(p).unwrap_or(Value::Null)
}
-impl MaterialcraftMcp {
+impl MaterialCraftMcp {
pub fn headless(h: Headless) -> Self {
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h))))
}
@@ -276,10 +70,10 @@ impl MaterialcraftMcp {
}
pub fn with_backend(backend: Backend) -> Self {
- MaterialcraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
+ MaterialCraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
}
- /// Serve MCP on stdin/stdout until the client disconnects.
+ /// 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()))?;
@@ -290,13 +84,12 @@ impl MaterialcraftMcp {
matches!(*self.backend, Backend::Bridge(_))
}
- /// One control-channel method on the backend.
+ /// 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.
+ // 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}`"))))
@@ -331,11 +124,10 @@ impl MaterialcraftMcp {
}
}
-// ---------------------------------------------------------------------------------------------
-// Tools
+// --------------------------------------------------------------------------------------------- Tools
#[tool_router]
-impl MaterialcraftMcp {
+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 {
@@ -408,15 +200,13 @@ impl MaterialcraftMcp {
}
#[tool(
- description = "Open an .sbs or .mcraft 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)."
+ 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 SBS (.sbs, the main format) unless the path ends in .mcraft."
- )]
+ #[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)
}
@@ -472,11 +262,11 @@ impl MaterialcraftMcp {
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: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \
+ (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 and outputs_export. Undo: command_run edit.undo."
)]
-impl ServerHandler for MaterialcraftMcp {}
+impl ServerHandler for MaterialCraftMcp {}
#[cfg(test)]
mod tests {
@@ -485,7 +275,7 @@ mod tests {
#[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 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 || {
diff --git a/crates/automation/src/server/mod.rs b/crates/automation/src/server/mod.rs
new file mode 100644
index 0000000..29444de
--- /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 0000000..0c8bff7
--- /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 0000000..8424dea
--- /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 0000000..ced3f35
--- /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 0000000..4000425
--- /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 0000000..be9d1f7
--- /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 0000000..1fea568
--- /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 0000000..26cfc86
--- /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/menu_params.rs b/crates/automation/src/server/parameter/menu_params.rs
new file mode 100644
index 0000000..dadf89c
--- /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 0000000..12aca9b
--- /dev/null
+++ b/crates/automation/src/server/parameter/mod.rs
@@ -0,0 +1,33 @@
+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;
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 0000000..cc4d5ce
--- /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 0000000..5a0832a
--- /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 0000000..271e728
--- /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 0000000..b21194e
--- /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 0000000..93876ed
--- /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 0000000..59bb5f9
--- /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 0000000..c5f15e2
--- /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 0000000..e2fc5b8
--- /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 61c1844..bd3917e 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,7 +64,7 @@ impl AuthorizedWorkspace {
Ok(())
}
- /// 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"))?;
@@ -87,7 +82,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() {
@@ -127,18 +122,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 {
@@ -234,12 +225,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/core/src/attributes.rs b/crates/core/src/attributes.rs
new file mode 100644
index 0000000..1dc3b2b
--- /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 0000000..2eba06c
--- /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 0000000..f7e34c0
--- /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 0000000..4027f6b
--- /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/connection.rs b/crates/core/src/connection.rs
new file mode 100644
index 0000000..1a201bf
--- /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 0000000..3964a22
--- /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 0000000..73e14e9
--- /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 0000000..e9d53f9
--- /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 0000000..43d663a
--- /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 0000000..f7e7473
--- /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.rs b/crates/core/src/function.rs
deleted file mode 100644
index 4e49aaf..0000000
--- a/crates/core/src/function.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-//! Function graphs: small typed expression graphs evaluated per pixel (pixel processor), once
-//! per cook (value processor) or to compute a parameter dynamically. The data lives here; the
-//! evaluator is `materialcraft_nodes::function`.
-
-use serde::{Deserialize, Serialize};
-
-use crate::Value;
-
-/// A node in a function graph.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct FnNode {
- pub id: u32,
- /// Operation id, e.g. `const_float`, `add`, `sample_gray`, `get_float2` (see the evaluator's
- /// catalog for the full list).
- pub op: String,
- /// Upstream node per input slot, in the op's slot order.
- #[serde(default)]
- pub inputs: Vec>,
- /// The constant (`const_*`), the variable name (`get_*`) or the input index (`sample_*`).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub value: Option,
- #[serde(default)]
- pub pos: [f32; 2],
-}
-
-/// A function graph: nodes plus the id of the node whose value is the result.
-#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
-pub struct FnGraph {
- pub nodes: Vec,
- #[serde(default)]
- pub output: Option,
-}
-
-impl FnGraph {
- pub fn node(&self, id: u32) -> Option<&FnNode> {
- self.nodes.iter().find(|n| n.id == id)
- }
-
- fn next_id(&self) -> u32 {
- self.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1)
- }
-
- /// Append a node and return its id.
- pub fn add(&mut self, op: &str, inputs: &[u32], value: Option) -> u32 {
- let id = self.next_id();
- let x = self.nodes.len() as f32 * 140.0;
- self.nodes.push(FnNode { id, op: op.into(), inputs: inputs.iter().map(|i| Some(*i)).collect(), value, pos: [x, 0.0] });
- id
- }
-
- /// A graph returning one constant.
- pub fn constant(v: Value) -> FnGraph {
- let op = match &v {
- Value::Float(_) => "const_float",
- Value::Float2(_) => "const_float2",
- Value::Float3(_) => "const_float3",
- Value::Float4(_) | Value::Color(_) => "const_float4",
- Value::Int(_) | Value::Enum(_) => "const_int",
- Value::Bool(_) => "const_bool",
- _ => "const_float",
- };
- let mut g = FnGraph::default();
- let id = g.add(op, &[], Some(v));
- g.output = Some(id);
- g
- }
-}
diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs
new file mode 100644
index 0000000..11f2aa7
--- /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 0000000..5497695
--- /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 0000000..38dcaf3
--- /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 0000000..aa13939
--- /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 ce31746..be25cac 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;
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,31 +20,29 @@ 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,
#[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;
@@ -289,7 +50,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(),
@@ -307,6 +68,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);
@@ -321,21 +86,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)?;
@@ -353,12 +116,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();
@@ -374,8 +137,6 @@ 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 {
@@ -401,7 +162,7 @@ impl Graph {
out
}
- /// 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];
@@ -416,7 +177,7 @@ impl Graph {
out
}
- /// 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];
@@ -431,12 +192,12 @@ impl Graph {
out
}
- /// 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)]
}
@@ -444,7 +205,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_kind.rs b/crates/core/src/graph_kind.rs
new file mode 100644
index 0000000..5f0551a
--- /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 caa14a9..71f876e 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -1,33 +1,71 @@
-//! # 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 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_kind;
+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 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_kind::GraphKind;
+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/missing_node.rs b/crates/core/src/missing_node.rs
new file mode 100644
index 0000000..0991800
--- /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 0000000..3fa105d
--- /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 0000000..9ec90cc
--- /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 0000000..c1eae1c
--- /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 e00541e..60021b0 100644
--- a/crates/core/src/package.rs
+++ b/crates/core/src/package.rs
@@ -1,87 +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,
-}
-
-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 }
- }
-}
-
-/// 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 {
@@ -89,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,
}
@@ -128,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 0000000..fcb8055
--- /dev/null
+++ b/crates/core/src/pattern_graph.rs
@@ -0,0 +1,78 @@
+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 id = (1..=4097).find(|id| self.nodes.iter().all(|node| node.id != *id)).ok_or("no available pattern node id")?;
+ 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(())
+ }
+}
diff --git a/crates/core/src/pattern_node.rs b/crates/core/src/pattern_node.rs
new file mode 100644
index 0000000..a66afee
--- /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 0000000..09d3f04
--- /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 0000000..58949ea
--- /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 0000000..01a8d54
--- /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 0000000..f754573
--- /dev/null
+++ b/crates/core/src/resource.rs
@@ -0,0 +1,21 @@
+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,
+}
+
+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 }
+ }
+}
diff --git a/crates/core/src/resource_bytes.rs b/crates/core/src/resource_bytes.rs
new file mode 100644
index 0000000..a3efe3b
--- /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 0000000..792eb56
--- /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 033ab2d..5fb0b82 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 0000000..b3337cd
--- /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 0000000..7de0490
--- /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 {
+ Self::ALL.into_iter().find(|value_type| *value_type as u32 == code)
+ }
+
+ pub fn of(value: &Value) -> Option {
+ Some(match value {
+ Value::Bool(_) => Self::Boolean,
+ Value::Int(_) | Value::Enum(_) => Self::Integer,
+ Value::Int2(_) => Self::Integer2,
+ Value::Int3(_) => Self::Integer3,
+ Value::Int4(_) => Self::Integer4,
+ Value::Float(_) => Self::Float,
+ Value::Float2(_) => Self::Float2,
+ Value::Float3(_) => Self::Float3,
+ Value::Float4(_) | Value::Color(_) => Self::Float4,
+ Value::Text(_) => Self::String,
+ _ => return None,
+ })
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Boolean => "Boolean",
+ Self::Integer => "Integer",
+ Self::Integer2 => "Integer2",
+ Self::Integer3 => "Integer3",
+ Self::Integer4 => "Integer4",
+ Self::Float => "Float",
+ Self::Float2 => "Float2",
+ Self::Float3 => "Float3",
+ Self::Float4 => "Float4",
+ Self::String => "String",
+ }
+ }
+
+ pub fn default_value(self) -> Value {
+ match self {
+ Self::Boolean => Value::Bool(false),
+ Self::Integer => Value::Int(0),
+ Self::Integer2 => Value::Int2([0; 2]),
+ Self::Integer3 => Value::Int3([0; 3]),
+ Self::Integer4 => Value::Int4([0; 4]),
+ Self::Float => Value::Float(0.0),
+ Self::Float2 => Value::Float2([0.0; 2]),
+ Self::Float3 => Value::Float3([0.0; 3]),
+ Self::Float4 => Value::Float4([0.0; 4]),
+ Self::String => Value::Text(String::new()),
+ }
+ }
+}
diff --git a/crates/engine/examples/atomic_sample.rs b/crates/engine/examples/atomic_sample.rs
new file mode 100644
index 0000000..9671f73
--- /dev/null
+++ b/crates/engine/examples/atomic_sample.rs
@@ -0,0 +1,7 @@
+fn main() -> Result<(), Box> {
+ let package = materialcraft_engine::atomic_sample()?;
+ let bytes = materialcraft_engine::formats::sbs::write_sbs(&package)?;
+ let path = std::env::args().nth(1).unwrap_or_else(|| "atomic_sample.sbs".into());
+ std::fs::write(path, bytes)?;
+ Ok(())
+}
diff --git a/crates/engine/src/annotation_commands.rs b/crates/engine/src/annotation_commands.rs
new file mode 100644
index 0000000..5825eca
--- /dev/null
+++ b/crates/engine/src/annotation_commands.rs
@@ -0,0 +1,41 @@
+use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
+use crate::{AnnotationSelection, Result, Session, cmd};
+use serde_json::{Value, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![cmd!(
+ "graph.annotation.select",
+ "Select annotation",
+ [],
+ None,
+ "{kind?: frame|comment, id?} clears node selection; omit kind to deselect",
+ has_graph,
+ select
+ )]
+}
+
+fn select(session: &mut Session, parameters: &Value) -> Result {
+ let selection = match strp(parameters, "kind") {
+ None => None,
+ Some(kind) => {
+ let id = u64p(parameters, "id").ok_or_else(|| bad("graph.annotation.select", "`id` is required"))?;
+ let selection = match kind {
+ "frame" => AnnotationSelection::Frame(id),
+ "comment" => AnnotationSelection::Comment(id),
+ _ => return Err(bad("graph.annotation.select", "kind must be frame or comment")),
+ };
+ if !selection.exists(session.graph()?) {
+ return Err(bad("graph.annotation.select", "annotation does not exist"));
+ }
+
+ Some(selection)
+ }
+ };
+
+ session.annotation_selection = selection;
+ if selection.is_some() {
+ session.selection.clear();
+ }
+
+ Ok(json!({"selection": selection}))
+}
diff --git a/crates/engine/src/annotation_selection.rs b/crates/engine/src/annotation_selection.rs
new file mode 100644
index 0000000..8385ca6
--- /dev/null
+++ b/crates/engine/src/annotation_selection.rs
@@ -0,0 +1,18 @@
+use materialcraft_core::Graph;
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "id", rename_all = "camelCase")]
+pub enum AnnotationSelection {
+ Frame(u64),
+ Comment(u64),
+}
+
+impl AnnotationSelection {
+ pub fn exists(self, graph: &Graph) -> bool {
+ match self {
+ Self::Frame(id) => graph.frames.iter().any(|frame| frame.id == id),
+ Self::Comment(id) => graph.comments.iter().any(|comment| comment.id == id),
+ }
+ }
+}
diff --git a/crates/engine/src/atomic_sample.rs b/crates/engine/src/atomic_sample.rs
new file mode 100644
index 0000000..6d24144
--- /dev/null
+++ b/crates/engine/src/atomic_sample.rs
@@ -0,0 +1,83 @@
+use crate::{EngineError, Result};
+use materialcraft_core::{FunctionGraph, Graph, Package, PatternGraph, PatternNodeKind, Value, ValueType};
+
+pub fn atomic_sample() -> Result {
+ let mut package = Package::new("Atomic sample");
+ let mut graph = Graph::new("Atomic_sample");
+ graph.size = [8, 8];
+ let input = graph.add_node("input_value", [0.0, 0.0]);
+ graph.node_mut(input)?.params.insert("default".into(), Value::Float(0.35));
+ graph.node_mut(input)?.params.insert("identifier".into(), Value::Text("brightness".into()));
+
+ let value = graph.add_node("value_processor", [200.0, 0.0]);
+ let mut function = FunctionGraph::default();
+ let get = function.add("get_float1", &[], Some(Value::Text("brightness".into())));
+ let two = function.add_constant(Value::Float(2.0));
+ function.output = Some(function.add("mul", &[get, two], None));
+ graph.node_mut(value)?.input_values.insert("brightness".into(), ValueType::Float);
+ graph.node_mut(value)?.params.insert("function".into(), Value::Function(Box::new(function)));
+ graph.connect(input, "output", value, "brightness")?;
+
+ let pixel = graph.add_node("pixel_processor", [400.0, 0.0]);
+ let mut function = FunctionGraph::default();
+ let position = function.add("get_float2", &[], Some(Value::Text("$pos".into())));
+ let horizontal = function.add("swizzle1", &[position], Some(Value::Int(0)));
+ let brightness = function.add("get_float1", &[], Some(Value::Text("brightness".into())));
+ function.output = Some(function.add("mul", &[horizontal, brightness], None));
+ graph.node_mut(pixel)?.params.insert("function".into(), Value::Function(Box::new(function)));
+ graph.node_mut(pixel)?.params.insert("color_mode".into(), Value::Bool(false));
+ graph.node_mut(pixel)?.input_values.insert("brightness".into(), ValueType::Float);
+ graph.connect(value, "output", pixel, "brightness")?;
+
+ let pattern = graph.add_node("fx_map", [400.0, 220.0]);
+ let mut patterns = PatternGraph::default();
+ let iterate = patterns.add(PatternNodeKind::Iterate).map_err(EngineError::Other)?;
+ let switch = patterns.add(PatternNodeKind::Switch).map_err(EngineError::Other)?;
+ let quadrant = patterns.add(PatternNodeKind::Quadrant).map_err(EngineError::Other)?;
+ for node in &mut patterns.nodes {
+ match node.kind {
+ PatternNodeKind::Dot => {}
+ PatternNodeKind::Iterate => {
+ node.position = [160.0, 0.0];
+ node.children = vec![Some(switch), Some(quadrant)];
+ node.parameters.insert("numberadded".into(), Value::Int(8));
+ }
+ PatternNodeKind::Switch => {
+ node.position = [0.0, 192.0];
+ node.children = vec![None, Some(quadrant)];
+ }
+ PatternNodeKind::Quadrant => {
+ node.position = [160.0, 384.0];
+ node.parameters.insert("patterntype".into(), Value::Int(3));
+ node.parameters.insert("patternsize".into(), Value::Float2([0.12; 2]));
+ node.parameters.insert("opacity".into(), Value::Float4([0.5, 0.5, 0.5, 1.0]));
+ let mut function = FunctionGraph::default();
+ let number = function.add("get_float1", &[], Some(Value::Text("$number".into())));
+ let step = function.add_constant(Value::Float(std::f32::consts::TAU / 8.0));
+ let angle = function.add("mul", &[number, step], None);
+ let radius = function.add_constant(Value::Float(0.3));
+ function.output = Some(function.add("cartesian", &[radius, angle], None));
+ node.parameters.insert("frameoffset".into(), Value::Function(Box::new(function)));
+ }
+ }
+ }
+ patterns.root = Some(iterate);
+ graph.node_mut(pattern)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(patterns)));
+ let blend = graph.add_node("blend", [600.0, 0.0]);
+ graph.node_mut(blend)?.params.insert("mode".into(), Value::Enum(1));
+ graph.connect(pattern, "output", blend, "foreground")?;
+ graph.connect(pixel, "output", blend, "background")?;
+ let blur = graph.add_node("blur", [800.0, 0.0]);
+ graph.node_mut(blur)?.params.insert("intensity".into(), Value::Float(1.5));
+ graph.connect(blend, "output", blur, "input")?;
+ let output = graph.add_node("output", [1000.0, 0.0]);
+ graph.node_mut(output)?.params.insert("usage".into(), Value::Enum(4));
+ graph.node_mut(output)?.params.insert("identifier".into(), Value::Text("height".into()));
+ graph.connect(blur, "output", output, "input")?;
+ let output = graph.add_node("output", [400.0, -200.0]);
+ graph.node_mut(output)?.params.insert("identifier".into(), Value::Text("brightness_value".into()));
+ graph.node_mut(output)?.params.insert("usage".into(), Value::Enum(9));
+ graph.connect(value, "output", output, "input")?;
+ package.graphs.push(graph);
+ Ok(package)
+}
diff --git a/crates/engine/src/atomic_sample_commands.rs b/crates/engine/src/atomic_sample_commands.rs
new file mode 100644
index 0000000..44e2b2d
--- /dev/null
+++ b/crates/engine/src/atomic_sample_commands.rs
@@ -0,0 +1,13 @@
+use crate::commands::{CommandSpec, always};
+use crate::{Result, Session, cmd};
+use serde_json::{Value, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![cmd!("file.newAtomicSample", "Atomic sample", ["File", "New"], None, "{} opens an original graph made only of native primitives", always, create)]
+}
+
+fn create(session: &mut Session, _: &Value) -> Result {
+ let package = crate::atomic_sample()?;
+ crate::file_cmds::replace_package(session, package, None);
+ Ok(json!({"graph": "Atomic_sample"}))
+}
diff --git a/crates/engine/src/clip.rs b/crates/engine/src/clip.rs
new file mode 100644
index 0000000..5669fd3
--- /dev/null
+++ b/crates/engine/src/clip.rs
@@ -0,0 +1,12 @@
+use materialcraft_core::{Connection, Node};
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct Clip {
+ pub nodes: Vec,
+ pub connections: Vec,
+ #[serde(default)]
+ pub inputs: Vec,
+ #[serde(skip)]
+ pub source_graph: Option,
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index e09b791..0d95597 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1,5 +1,4 @@
-//! The command registry. Every user-visible action is a command with a stable id; the menus,
-//! shortcuts, CLI, control channel and MCP server all dispatch them by id.
+//! The command registry. Every user-visible action is a command with a stable id; the menus, shortcuts, CLI, control channel and MCP server all dispatch them by id
use serde_json::{Value as J, json};
@@ -13,11 +12,11 @@ pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
- /// Menu placement, e.g. `["Edit"]`. Empty = not in menus.
+ /// Menu placement, e.g. `["Edit"]`. Empty = not in menus
pub menu: &'static [&'static str],
- /// Default shortcut in egui notation (`Ctrl+Shift+E`).
+ /// Default shortcut in egui notation (`Ctrl+Shift+E`)
pub shortcut: Option<&'static str>,
- /// Parameters, for humans and agents.
+ /// Parameters, for humans and agents
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
@@ -49,10 +48,19 @@ pub fn command_specs() -> &'static [CommandSpec] {
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(crate::file_cmds::specs());
+ v.extend(crate::atomic_sample_commands::specs());
v.extend(crate::material_cmds::specs());
v.extend(crate::edit_cmds::specs());
v.extend(crate::graph_cmds::specs());
+ v.extend(crate::annotation_commands::specs());
+ v.extend(crate::frame_commands::specs());
+ v.extend(crate::function_commands::specs());
+ v.extend(crate::comment_commands::specs());
v.extend(crate::node_cmds::specs());
+ v.extend(crate::node_graph_commands::specs());
+ v.extend(crate::pattern_graph_commands::specs());
+ v.extend(crate::connection_commands::specs());
+ v.extend(crate::value_input_commands::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::wire_cmds::specs());
v
@@ -63,14 +71,19 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
-/// Run a command by id with JSON params (empty params = defaults, never a dialog).
+/// Run a command by id with JSON params (empty params = defaults, never a dialog)
pub fn execute(s: &mut Session, id: &str, params: &J) -> Result {
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
- (spec.run)(s, params)
+ let result = (spec.run)(s, params)?;
+ if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) {
+ s.annotation_selection = None;
+ }
+
+ Ok(result)
}
-/// Every command, as JSON (for `commands` listings and MCP).
+/// Every command, as JSON (for `commands` listings and MCP)
pub fn list(s: &Session, filter: Option<&str>) -> J {
let f = filter.map(str::to_ascii_lowercase);
J::Array(
@@ -108,17 +121,18 @@ pub(crate) fn strp<'a>(p: &'a J, key: &str) -> Option<&'a str> {
p.get(key).and_then(J::as_str)
}
-/// A node id param (`key`), defaulting to the last selected node.
+/// A node id param (`key`), defaulting to the last selected node
pub(crate) fn node_param(s: &Session, cmd: &str, p: &J, key: &str) -> Result {
let id = match u64p(p, key) {
Some(id) => NodeId(id),
None => *s.selection.last().ok_or_else(|| bad(cmd, format!("no node selected and no `{key}` given")))?,
};
+
s.graph()?.node(id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?;
Ok(id)
}
-/// A list of node ids (`ids`), defaulting to the selection.
+/// A list of node ids (`ids`), defaulting to the selection
pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result> {
let ids: Vec = match p.get("ids").and_then(J::as_array) {
Some(a) => a.iter().filter_map(J::as_u64).map(NodeId).collect(),
@@ -127,6 +141,7 @@ pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result> {
None => s.selection.clone(),
},
};
+
let g = s.graph()?;
for id in &ids {
g.node(*id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?;
@@ -134,7 +149,7 @@ pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result> {
Ok(ids)
}
-/// A 2D point param (`[x, y]`).
+/// A 2D point param (`[x, y]`)
pub(crate) fn point(p: &J, key: &str) -> Option<[f32; 2]> {
let a = p.get(key)?.as_array()?;
let x = a.first()?.as_f64()? as f32;
diff --git a/crates/engine/src/comment_commands.rs b/crates/engine/src/comment_commands.rs
new file mode 100644
index 0000000..103091e
--- /dev/null
+++ b/crates/engine/src/comment_commands.rs
@@ -0,0 +1,57 @@
+use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
+use crate::graph_cmds::nodes_rect;
+use crate::{AnnotationSelection, Result, Session, cmd};
+use materialcraft_core::Comment;
+use serde_json::{Value as J, json};
+
+pub(crate) fn specs() -> Vec {
+ vec![
+ cmd!("graph.comment.add", "Add Comment", [], None, "{text?, at? [x, y]}", has_graph, comment_add),
+ cmd!("graph.comment.edit", "Edit comment", [], None, "{id, text?, at?, size?}", has_graph, comment_edit),
+ cmd!("graph.comment.delete", "Delete comment", [], None, "{id}", has_graph, comment_delete),
+ ]
+}
+
+fn comment_add(session: &mut Session, parameters: &J) -> Result {
+ let at = point(parameters, "at").or_else(|| nodes_rect(session, &session.selection).map(|rect| [rect[0], rect[1] - 90.0])).unwrap_or([0.0, -120.0]);
+ let text = strp(parameters, "text").unwrap_or("Comment").to_string();
+
+ session.edit("Add comment", |session| {
+ let graph = session.graph_mut()?;
+ let id = graph.alloc_id();
+ graph.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] });
+ session.selection.clear();
+ session.annotation_selection = Some(AnnotationSelection::Comment(id));
+ Ok(json!({"id": id}))
+ })
+}
+
+fn comment_edit(session: &mut Session, parameters: &J) -> Result {
+ let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.edit", "`id` is required"))?;
+
+ session.edit_merged(&format!("comment{id}"), "Edit comment", |session| {
+ let comment =
+ session.graph_mut()?.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?;
+ if let Some(text) = strp(parameters, "text") {
+ comment.text = text.into();
+ }
+ if let Some(position) = point(parameters, "at") {
+ comment.pos = position;
+ }
+ if let Some(size) = point(parameters, "size") {
+ comment.size = [size[0].max(40.0), size[1].max(24.0)];
+ }
+
+ Ok(J::Null)
+ })
+}
+
+fn comment_delete(session: &mut Session, parameters: &J) -> Result