diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index def2bd7..49ef237 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -10,9 +10,9 @@ on:
type: string
default: ""
-permissions:
- contents: write
- packages: write
+# Nothing by default; each job names what it needs. Only `release` and `freebsd-draft` write
+# (the draft GitHub Release, and the packages the shared release job publishes).
+permissions: {}
concurrency:
group: release-${{ github.ref }}
@@ -20,6 +20,9 @@ concurrency:
jobs:
release:
+ permissions:
+ contents: write
+ packages: write
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
@@ -299,6 +302,8 @@ jobs:
name: Add FreeBSD to the draft release
needs: [version, freebsd, release]
runs-on: ubuntu-latest
+ permissions:
+ contents: write
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
diff --git a/Cargo.lock b/Cargo.lock
index 5ed21fd..802807c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2601,7 +2601,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "materialcraft"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"craft-menu",
"craft-update",
@@ -2620,7 +2620,7 @@ dependencies = [
[[package]]
name = "materialcraft-automation"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -2641,7 +2641,7 @@ dependencies = [
[[package]]
name = "materialcraft-cli"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"materialcraft-automation",
"materialcraft-engine",
@@ -2652,7 +2652,7 @@ dependencies = [
[[package]]
name = "materialcraft-core"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"serde",
"serde_json",
@@ -2661,7 +2661,7 @@ dependencies = [
[[package]]
name = "materialcraft-engine"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"materialcraft-core",
"materialcraft-eval",
@@ -2676,17 +2676,18 @@ dependencies = [
[[package]]
name = "materialcraft-eval"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"materialcraft-core",
"materialcraft-image",
"materialcraft-nodes",
+ "serde",
"serde_json",
]
[[package]]
name = "materialcraft-formats"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"base64 0.22.1",
"bytemuck",
@@ -2709,7 +2710,7 @@ dependencies = [
[[package]]
name = "materialcraft-geom"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -2720,7 +2721,7 @@ dependencies = [
[[package]]
name = "materialcraft-image"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"rayon",
"thiserror 2.0.21",
@@ -2728,7 +2729,7 @@ dependencies = [
[[package]]
name = "materialcraft-nodes"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2737,7 +2738,7 @@ dependencies = [
[[package]]
name = "materialcraft-render"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"materialcraft-core",
"materialcraft-geom",
@@ -2747,7 +2748,7 @@ dependencies = [
[[package]]
name = "materialcraft-ui-egui"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"base64 0.22.1",
"craft-dialogs",
@@ -2777,7 +2778,7 @@ dependencies = [
[[package]]
name = "materialcraft-web"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"eframe",
"js-sys",
@@ -6022,7 +6023,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"serde_json",
]
diff --git a/Cargo.toml b/Cargo.toml
index c8c4da8..7daf64d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -35,7 +35,7 @@ default-members = [
]
[workspace.package]
-version = "0.3.0"
+version = "0.4.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
diff --git a/README.md b/README.md
index c983f39..b577b34 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,9 @@
+
+
+
@@ -122,7 +125,7 @@ ray-traced ambient occlusion and a shadowed key light).
with odd inputs in tests, undo from snapshots, and native SBS project files. Save `.sbs` with an
adjacent `resources/` folder, or a self-contained `.mcraft` ZIP with `package.sbs` and `resources/`.
- **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.
+ JPEG, TGA, 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
shelf as a portable `.mcmat`; painted onto a mesh there, its graph inputs stay live sliders and
colors, re-cooked by MaterialCraft at the texture set's resolution with the mesh's baked maps
diff --git a/assets/sbs/all_nodes.resources/test.bmp b/assets/sbs/all_nodes.resources/test.bmp
deleted file mode 100644
index 5a54b4a..0000000
Binary files a/assets/sbs/all_nodes.resources/test.bmp and /dev/null differ
diff --git a/assets/sbs/all_nodes.sbs b/assets/sbs/all_nodes.sbs
deleted file mode 100644
index dbb7cdb..0000000
--- a/assets/sbs/all_nodes.sbs
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs
index 0294f74..8574920 100644
--- a/assets/sbs/functions.sbs
+++ b/assets/sbs/functions.sbs
@@ -1 +1 @@
-
+
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 2ebafb0..582d8a9 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -185,13 +185,14 @@ impl Headless {
/// 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)?;
- let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth, size)?;
+ let request = materialcraft_engine::ExportRequest::from_params(&self.session, p)?;
+ let files = file_cmds::export_outputs(&self.session, &request)?;
self.create_dir_all(dir)?;
+
let mut written = Vec::new();
- for f in files {
- let path = if dir == "." { f.file.clone() } else { format!("{}/{}", dir.trim_end_matches('/'), f.file) };
- self.write(&path, &f.bytes)?;
+ for exported in files {
+ let path = if dir == "." { exported.file.clone() } else { format!("{}/{}", dir.trim_end_matches('/'), exported.file) };
+ self.write(&path, &exported.bytes)?;
written.push(path);
}
Ok(json!({"files": written}))
diff --git a/crates/automation/src/server/material_craft_mcp.rs b/crates/automation/src/server/material_craft_mcp.rs
index 0d42054..fb3614f 100644
--- a/crates/automation/src/server/material_craft_mcp.rs
+++ b/crates/automation/src/server/material_craft_mcp.rs
@@ -207,7 +207,7 @@ impl MaterialCraftMcp {
}
#[tool(
- description = "Save the package (path relative to the write root; omit to save to its own file). Writes .sbs XML with adjacent resources/ or a self-contained .mcraft ZIP."
+ description = "Save the package (path relative to the write root; omit to save to its own file). Writes .sbs XML with adjacent resources/ or a self-contained .mcraft ZIP. In bridge mode, saving without a path runs File > Save and returns an error while a dialog or prompt blocks it."
)]
async fn package_save(&self, Parameters(p): Parameters) -> Result {
to_result(self.call("package.save", params(&p)).await)
@@ -254,7 +254,9 @@ impl MaterialCraftMcp {
to_result(self.bridge_only("ui.inspect", json!({})).await)
}
- #[tool(description = "Bridge mode: activate a menu item by id like a click (may open a window). ui.menu.list lists ids.")]
+ #[tool(
+ description = "Bridge mode: activate a menu item by id like a click (may open a window); returns an error while a dialog or prompt blocks it. ui.menu.list lists ids and which are enabled."
+ )]
async fn ui_menu_invoke(&self, Parameters(p): Parameters) -> Result {
to_result(self.bridge_only("ui.menu.invoke", params(&p)).await)
}
diff --git a/crates/automation/src/server/parameter/export_params.rs b/crates/automation/src/server/parameter/export_params.rs
index 4000425..549d57d 100644
--- a/crates/automation/src/server/parameter/export_params.rs
+++ b/crates/automation/src/server/parameter/export_params.rs
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
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
+ /// png (default), jpg, tga, 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)`)
@@ -20,4 +20,10 @@ pub struct ExportParams {
/// Graph index (default: the open graph)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option,
+ /// Output identifiers to write (default: every connected output)
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub outputs: Option>,
+ /// Color space per output identifier: srgb, linear or raw (default: sRGB for color usages, raw for data)
+ #[serde(default, rename = "colorSpaces", skip_serializing_if = "Option::is_none")]
+ pub color_spaces: Option>,
}
diff --git a/crates/core/src/base_parameter.rs b/crates/core/src/base_parameter.rs
new file mode 100644
index 0000000..cbef563
--- /dev/null
+++ b/crates/core/src/base_parameter.rs
@@ -0,0 +1,140 @@
+use serde::{Deserialize, Serialize};
+
+use crate::{BaseParameters, OutputFormat, ParameterInheritance, SizeMode, Value, ValueType};
+
+/// Native base-parameter identities are distinct from node-specific parameter identifiers
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum BaseParameter {
+ OutputSize,
+ Format,
+ PixelSize,
+ PixelRatio,
+ Tiling,
+ RandomSeed,
+}
+
+impl BaseParameter {
+ pub const ALL: [Self; 6] = [Self::OutputSize, Self::Format, Self::PixelSize, Self::PixelRatio, Self::Tiling, Self::RandomSeed];
+
+ pub fn named(name: &str) -> Option {
+ Self::ALL.into_iter().find(|parameter| parameter.identifier() == name)
+ }
+
+ pub fn identifier(self) -> &'static str {
+ match self {
+ Self::OutputSize => "outputsize",
+ Self::Format => "format",
+ Self::PixelSize => "pixelsize",
+ Self::PixelRatio => "pixelratio",
+ Self::Tiling => "tiling",
+ Self::RandomSeed => "randomseed",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::OutputSize => "Output size",
+ Self::Format => "Output format",
+ Self::PixelSize => "Pixel size",
+ Self::PixelRatio => "Pixel ratio",
+ Self::Tiling => "Tiling mode",
+ Self::RandomSeed => "Random seed",
+ }
+ }
+
+ pub fn value_type(self) -> ValueType {
+ match self {
+ Self::OutputSize => ValueType::Integer2,
+ Self::PixelSize => ValueType::Float2,
+ _ => ValueType::Integer,
+ }
+ }
+
+ pub fn value(self, base: &BaseParameters) -> Value {
+ match self {
+ Self::OutputSize => Value::Int2(base.size),
+ Self::Format => Value::Int(match base.format {
+ OutputFormat::U8 => 0,
+ OutputFormat::Inherit | OutputFormat::U16 => 1,
+ OutputFormat::F16 => 2,
+ OutputFormat::F32 => 3,
+ }),
+ Self::PixelSize => Value::Float2(base.pixel_size),
+ Self::PixelRatio => Value::Int(base.pixel_ratio),
+ Self::Tiling => Value::Int(i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1)),
+ Self::RandomSeed => Value::Int(base.seed),
+ }
+ }
+
+ pub fn set_value(self, base: &mut BaseParameters, value: &Value) -> Result<(), String> {
+ if ValueType::of(value) != Some(self.value_type()) {
+ return Err(format!("{} requires {}", self.label(), self.value_type().label()));
+ }
+
+ match (self, value) {
+ (Self::OutputSize, Value::Int2(size)) => base.size = size.map(|component| component.clamp(-12, 13)),
+ (Self::Format, Value::Int(format)) => {
+ base.format = match format {
+ 0 => OutputFormat::U8,
+ 1 => OutputFormat::U16,
+ 2 => OutputFormat::F16,
+ 3 => OutputFormat::F32,
+ _ => return Err("Output format must be between 0 and 3".into()),
+ };
+ }
+ (Self::PixelSize, Value::Float2(size)) => {
+ if size.iter().any(|component| !component.is_finite() || *component <= 0.0 || *component > 8192.0) {
+ return Err("Pixel size components must be finite and between 0 and 8192, excluding zero".into());
+ }
+
+ base.pixel_size = *size;
+ }
+ (Self::PixelRatio, Value::Int(ratio)) if (0..=1).contains(ratio) => base.pixel_ratio = *ratio,
+ (Self::Tiling, Value::Int(tiling)) if (0..=3).contains(tiling) => base.tiling = [tiling & 1 != 0, tiling & 2 != 0],
+ (Self::RandomSeed, Value::Int(seed)) => base.seed = *seed,
+ _ => return Err(format!("{} is outside its supported range", self.label())),
+ }
+
+ Ok(())
+ }
+
+ pub fn inheritance(self, base: &BaseParameters) -> ParameterInheritance {
+ match self {
+ Self::OutputSize => match base.size_mode {
+ SizeMode::Absolute => ParameterInheritance::Absolute,
+ SizeMode::RelativeToInput => ParameterInheritance::RelativeToInput,
+ SizeMode::RelativeToParent => ParameterInheritance::RelativeToParent,
+ },
+ Self::Format if base.format == OutputFormat::Inherit => ParameterInheritance::RelativeToInput,
+ Self::Format => base.format_mode,
+ Self::PixelSize => base.pixel_size_mode,
+ Self::PixelRatio => base.pixel_ratio_mode,
+ Self::Tiling => base.tiling_mode,
+ Self::RandomSeed => base.seed_mode,
+ }
+ }
+
+ pub fn set_inheritance(self, base: &mut BaseParameters, inheritance: ParameterInheritance) {
+ match self {
+ Self::OutputSize => {
+ base.size_mode = match inheritance {
+ ParameterInheritance::Absolute => SizeMode::Absolute,
+ ParameterInheritance::RelativeToInput => SizeMode::RelativeToInput,
+ ParameterInheritance::RelativeToParent => SizeMode::RelativeToParent,
+ };
+ }
+ Self::Format => {
+ if base.format == OutputFormat::Inherit {
+ base.format = OutputFormat::U16;
+ }
+
+ base.format_mode = inheritance;
+ }
+ Self::PixelSize => base.pixel_size_mode = inheritance,
+ Self::PixelRatio => base.pixel_ratio_mode = inheritance,
+ Self::Tiling => base.tiling_mode = inheritance,
+ Self::RandomSeed => base.seed_mode = inheritance,
+ }
+ }
+}
diff --git a/crates/core/src/base_parameters.rs b/crates/core/src/base_parameters.rs
index ed0f58d..4db8979 100644
--- a/crates/core/src/base_parameters.rs
+++ b/crates/core/src/base_parameters.rs
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
-use crate::{OutputFormat, ParameterInheritance, SizeMode};
+use crate::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance, SizeMode};
+use std::collections::BTreeMap;
/// Parameters every node has ("Base parameters")
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -10,8 +11,14 @@ pub struct BaseParameters {
/// 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 format_mode: ParameterInheritance,
+ /// Added to the inherited seed, or used directly in absolute mode
pub seed: i32,
+ pub seed_mode: ParameterInheritance,
+ pub pixel_size: [f32; 2],
+ pub pixel_size_mode: ParameterInheritance,
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub functions: BTreeMap,
/// Whether sampling wraps at the edges (horizontal, vertical)
pub tiling: [bool; 2],
pub tiling_mode: ParameterInheritance,
@@ -26,7 +33,12 @@ impl Default for BaseParameters {
size_mode: SizeMode::RelativeToInput,
size: [0, 0],
format: OutputFormat::Inherit,
+ format_mode: ParameterInheritance::Absolute,
seed: 0,
+ seed_mode: ParameterInheritance::RelativeToInput,
+ pixel_size: [1.0; 2],
+ pixel_size_mode: ParameterInheritance::RelativeToInput,
+ functions: BTreeMap::new(),
tiling: [true, true],
tiling_mode: ParameterInheritance::default(),
pixel_ratio: 0,
diff --git a/crates/core/src/canvas_annotations.rs b/crates/core/src/canvas_annotations.rs
new file mode 100644
index 0000000..93b3af6
--- /dev/null
+++ b/crates/core/src/canvas_annotations.rs
@@ -0,0 +1,32 @@
+use crate::{Comment, Frame, Pin};
+use serde::{Deserialize, Serialize};
+
+/// Editable helpers belonging to one embedded graph canvas.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct CanvasAnnotations {
+ #[serde(default)]
+ pub frames: Vec,
+ #[serde(default)]
+ pub comments: Vec,
+ #[serde(default)]
+ pub pins: Vec,
+}
+
+impl CanvasAnnotations {
+ /// Whether the canvas has no frames, comments or pins.
+ pub fn is_empty(&self) -> bool {
+ self.frames.is_empty() && self.comments.is_empty() && self.pins.is_empty()
+ }
+
+ /// The next annotation id, or none when all ids have been exhausted.
+ pub fn next_id(&self) -> Option {
+ self.frames
+ .iter()
+ .map(|frame| frame.id)
+ .chain(self.comments.iter().map(|comment| comment.id))
+ .chain(self.pins.iter().map(|pin| pin.id))
+ .max()
+ .unwrap_or(0)
+ .checked_add(1)
+ }
+}
diff --git a/crates/core/src/exposed_parameter.rs b/crates/core/src/exposed_parameter.rs
index 43d663a..d8320b4 100644
--- a/crates/core/src/exposed_parameter.rs
+++ b/crates/core/src/exposed_parameter.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::Value;
+use crate::{ParameterEditor, Value};
/// The kind of value an exposed graph input carries
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -12,6 +12,14 @@ pub struct ExposedParameter {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub group: String,
pub default: Value,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub description: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub editor: Option,
+ #[serde(default)]
+ pub clamp: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub step: Option,
#[serde(default)]
pub min: f32,
#[serde(default = "one")]
@@ -24,3 +32,16 @@ pub struct ExposedParameter {
fn one() -> f32 {
1.0
}
+
+impl ExposedParameter {
+ pub fn editor(&self) -> ParameterEditor {
+ self.editor.filter(|editor| ParameterEditor::choices(&self.default).contains(editor)).unwrap_or_else(|| ParameterEditor::for_value(&self.default))
+ }
+
+ pub fn step(&self) -> f32 {
+ self.step.filter(|step| step.is_finite() && *step > 0.0).unwrap_or(match self.default {
+ Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_) | Value::Enum(_) => 1.0,
+ _ => 0.01,
+ })
+ }
+}
diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs
index c3f43bc..02eac7c 100644
--- a/crates/core/src/function_graph.rs
+++ b/crates/core/src/function_graph.rs
@@ -6,6 +6,8 @@ use crate::FunctionNode;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FunctionGraph {
+ #[serde(default, skip_serializing_if = "crate::CanvasAnnotations::is_empty")]
+ pub annotations: crate::CanvasAnnotations,
pub nodes: Vec,
#[serde(default)]
pub output: Option,
@@ -51,6 +53,38 @@ impl FunctionGraph {
graph
}
+ pub fn input(identifier: &str, value_type: crate::ValueType) -> FunctionGraph {
+ use crate::ValueType;
+
+ let operation = match value_type {
+ ValueType::Boolean => "get_bool",
+ ValueType::Integer => "get_integer1",
+ ValueType::Integer2 => "get_integer2",
+ ValueType::Integer3 => "get_integer3",
+ ValueType::Integer4 => "get_integer4",
+ ValueType::Float => "get_float1",
+ ValueType::Float2 => "get_float2",
+ ValueType::Float3 => "get_float3",
+ ValueType::Float4 => "get_float4",
+ ValueType::String => "get_string",
+ };
+ let mut graph = FunctionGraph::default();
+ graph.output = Some(graph.add(operation, &[], Some(Value::Text(identifier.into()))));
+ graph
+ }
+
+ pub fn input_identifier(&self) -> Option<&str> {
+ let output = self.node(self.output?)?;
+ if self.nodes.len() != 1 || !output.op.starts_with("get_") {
+ return None;
+ }
+
+ match &output.value {
+ Some(Value::Text(identifier)) => Some(identifier),
+ _ => None,
+ }
+ }
+
pub fn add_constant(&mut self, value: Value) -> u32 {
let operation = match &value {
Value::Float(_) => "const_float1",
diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs
index a277554..61a6a23 100644
--- a/crates/core/src/graph.rs
+++ b/crates/core/src/graph.rs
@@ -105,13 +105,19 @@ impl Graph {
/// All editable Function canvases, including processor and parameter functions
pub fn functions(&self) -> impl Iterator- {
- self.function.iter().chain(self.nodes.iter().flat_map(|node| node.functions.values().chain(node.params.values().flat_map(value_functions))))
+ self.function.iter().chain(
+ self.nodes
+ .iter()
+ .flat_map(|node| node.base.functions.values().chain(node.functions.values()).chain(node.params.values().flat_map(value_functions))),
+ )
}
pub fn functions_mut(&mut self) -> impl Iterator
- {
- self.function
- .iter_mut()
- .chain(self.nodes.iter_mut().flat_map(|node| node.functions.values_mut().chain(node.params.values_mut().flat_map(value_functions_mut))))
+ self.function.iter_mut().chain(
+ self.nodes.iter_mut().flat_map(|node| {
+ node.base.functions.values_mut().chain(node.functions.values_mut()).chain(node.params.values_mut().flat_map(value_functions_mut))
+ }),
+ )
}
pub fn instances(&self) -> impl Iterator
- {
@@ -125,8 +131,10 @@ impl Graph {
self.function.iter_mut().flat_map(|function| function.nodes.iter_mut().filter_map(|node| node.instance.as_mut())).chain(self.nodes.iter_mut().flat_map(
|node| {
node.instance.iter_mut().chain(
- node.functions
+ node.base
+ .functions
.values_mut()
+ .chain(node.functions.values_mut())
.chain(node.params.values_mut().flat_map(value_functions_mut))
.flat_map(|function| function.nodes.iter_mut().filter_map(|node| node.instance.as_mut())),
)
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 1810508..f9ac317 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -2,7 +2,9 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod attributes;
+mod base_parameter;
mod base_parameters;
+mod canvas_annotations;
mod color;
mod comment;
mod component_usage;
@@ -28,11 +30,13 @@ mod node;
mod node_id;
mod output_format;
mod package;
+mod parameter_editor;
mod parameter_inheritance;
mod pattern_graph;
mod pattern_node;
mod pattern_node_kind;
mod pin;
+pub use canvas_annotations::CanvasAnnotations;
mod preset;
mod resource;
mod resource_bytes;
@@ -41,6 +45,7 @@ mod value;
mod value_type;
pub use attributes::Attributes;
+pub use base_parameter::BaseParameter;
pub use base_parameters::BaseParameters;
pub use color::{linear_to_srgb, parse_color, srgb_to_linear};
pub use comment::Comment;
@@ -67,6 +72,7 @@ pub use node::Node;
pub use node_id::NodeId;
pub use output_format::OutputFormat;
pub use package::{PACKAGE_EXT, Package};
+pub use parameter_editor::ParameterEditor;
pub use parameter_inheritance::ParameterInheritance;
pub use pattern_graph::PatternGraph;
pub use pattern_node::PatternNode;
diff --git a/crates/core/src/parameter_editor.rs b/crates/core/src/parameter_editor.rs
new file mode 100644
index 0000000..b6db985
--- /dev/null
+++ b/crates/core/src/parameter_editor.rs
@@ -0,0 +1,43 @@
+use crate::Value;
+use serde::{Deserialize, Serialize};
+
+/// Presentation of an exposed value in Properties
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ParameterEditor {
+ Slider,
+ Input,
+ Color,
+ Dropdown,
+ Toggle,
+ Text,
+}
+
+impl ParameterEditor {
+ pub fn choices(value: &Value) -> &'static [Self] {
+ match value {
+ Value::Bool(_) => &[Self::Toggle],
+ Value::Text(_) => &[Self::Text],
+ Value::Enum(_) => &[Self::Dropdown],
+ Value::Color(_) => &[Self::Color, Self::Input],
+ Value::Float3(_) | Value::Float4(_) => &[Self::Slider, Self::Input, Self::Color],
+ Value::Float(_) | Value::Float2(_) | Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_) => &[Self::Slider, Self::Input],
+ _ => &[],
+ }
+ }
+
+ pub fn for_value(value: &Value) -> Self {
+ Self::choices(value).first().copied().unwrap_or(Self::Input)
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Slider => "Slider",
+ Self::Input => "Input field",
+ Self::Color => "Color",
+ Self::Dropdown => "Drop down list",
+ Self::Toggle => "Toggle",
+ Self::Text => "Text",
+ }
+ }
+}
diff --git a/crates/core/src/pattern_graph.rs b/crates/core/src/pattern_graph.rs
index d0275a8..d1c47bc 100644
--- a/crates/core/src/pattern_graph.rs
+++ b/crates/core/src/pattern_graph.rs
@@ -5,6 +5,8 @@ use crate::{PatternNode, PatternNodeKind};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PatternGraph {
+ #[serde(default, skip_serializing_if = "crate::CanvasAnnotations::is_empty")]
+ pub annotations: crate::CanvasAnnotations,
pub nodes: Vec,
pub root: Option,
}
@@ -12,6 +14,7 @@ pub struct PatternGraph {
impl PatternGraph {
pub fn with_root(kind: PatternNodeKind) -> Self {
Self {
+ annotations: Default::default(),
root: Some(1),
nodes: vec![PatternNode { id: 1, kind, children: vec![None; kind.child_count()], parameters: BTreeMap::new(), position: [0.0; 2] }],
}
diff --git a/crates/engine/src/annotation_commands.rs b/crates/engine/src/annotation_commands.rs
index 5825eca..e72f6df 100644
--- a/crates/engine/src/annotation_commands.rs
+++ b/crates/engine/src/annotation_commands.rs
@@ -8,13 +8,15 @@ pub(crate) fn specs() -> Vec {
"Select annotation",
[],
None,
- "{kind?: frame|comment, id?} clears node selection; omit kind to deselect",
+ "{kind?: frame|comment|pin, id?} clears node selection; omit kind to deselect",
has_graph,
select
)]
}
fn select(session: &mut Session, parameters: &Value) -> Result {
+ let target = crate::AnnotationTarget::resolve(session, parameters)?;
+ let items = target.items(session)?;
let selection = match strp(parameters, "kind") {
None => None,
Some(kind) => {
@@ -22,9 +24,10 @@ fn select(session: &mut Session, parameters: &Value) -> Result {
let selection = match kind {
"frame" => AnnotationSelection::Frame(id),
"comment" => AnnotationSelection::Comment(id),
- _ => return Err(bad("graph.annotation.select", "kind must be frame or comment")),
+ "pin" => AnnotationSelection::Pin(id),
+ _ => return Err(bad("graph.annotation.select", "kind must be frame, comment or pin")),
};
- if !selection.exists(session.graph()?) {
+ if !selection.exists(&items) {
return Err(bad("graph.annotation.select", "annotation does not exist"));
}
@@ -32,6 +35,7 @@ fn select(session: &mut Session, parameters: &Value) -> Result {
}
};
+ session.annotation_target = target;
session.annotation_selection = selection;
if selection.is_some() {
session.selection.clear();
diff --git a/crates/engine/src/annotation_selection.rs b/crates/engine/src/annotation_selection.rs
index 8385ca6..cd3b686 100644
--- a/crates/engine/src/annotation_selection.rs
+++ b/crates/engine/src/annotation_selection.rs
@@ -1,4 +1,4 @@
-use materialcraft_core::Graph;
+use materialcraft_core::CanvasAnnotations;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -6,13 +6,15 @@ use serde::{Deserialize, Serialize};
pub enum AnnotationSelection {
Frame(u64),
Comment(u64),
+ Pin(u64),
}
impl AnnotationSelection {
- pub fn exists(self, graph: &Graph) -> bool {
+ pub fn exists(self, graph: &CanvasAnnotations) -> 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),
+ Self::Pin(id) => graph.pins.iter().any(|pin| pin.id == id),
}
}
}
diff --git a/crates/engine/src/annotation_target.rs b/crates/engine/src/annotation_target.rs
new file mode 100644
index 0000000..255ff67
--- /dev/null
+++ b/crates/engine/src/annotation_target.rs
@@ -0,0 +1,150 @@
+use crate::{FrameContents, FunctionGraphTarget, Result, SelectionTarget, Session, commands::bad};
+use materialcraft_core::{CanvasAnnotations, Frame, NodeId, Value};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value as Json, json};
+
+/// Canvas that owns the selected frame, comment or navigation pin.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum AnnotationTarget {
+ #[default]
+ Graph,
+ Function {
+ target: FunctionGraphTarget,
+ },
+ Pattern {
+ owner: NodeId,
+ },
+}
+
+impl AnnotationTarget {
+ pub(crate) fn resolve(session: &Session, parameters: &Json) -> Result {
+ Ok(match SelectionTarget::resolve(session, parameters)? {
+ None | Some(SelectionTarget::Function(FunctionGraphTarget::Graph)) => Self::Graph,
+ Some(SelectionTarget::Function(target)) => Self::Function { target },
+ Some(SelectionTarget::Pattern(owner)) => Self::Pattern { owner },
+ })
+ }
+
+ /// Command parameters that address this canvas.
+ pub fn parameters(&self) -> Json {
+ match self {
+ Self::Graph => json!({}),
+ Self::Function { target } => json!({"function": target}),
+ Self::Pattern { owner } => json!({"pattern": owner.0}),
+ }
+ }
+
+ /// Copy the annotations owned by this canvas.
+ pub fn items(&self, session: &Session) -> Result {
+ Ok(match self {
+ Self::Graph => {
+ let graph = session.graph()?;
+ CanvasAnnotations { frames: graph.frames.clone(), comments: graph.comments.clone(), pins: graph.pins.clone() }
+ }
+ Self::Function { target } => target.current(session)?.annotations.clone(),
+ Self::Pattern { owner } => SelectionTarget::pattern(session, *owner)?.annotations.clone(),
+ })
+ }
+
+ pub(crate) fn replace(&self, session: &mut Session, items: CanvasAnnotations) -> Result<()> {
+ match self {
+ Self::Graph => {
+ let graph = session.graph_mut()?;
+ graph.next_id = graph.next_id.max(items.next_id().unwrap_or(u64::MAX));
+ graph.frames = items.frames;
+ graph.comments = items.comments;
+ graph.pins = items.pins;
+ }
+ Self::Function { target } => {
+ let mut function = target.current(session)?.clone();
+ function.annotations = items;
+ target.replace(session, function)?;
+ }
+ Self::Pattern { owner } => {
+ let mut graph = SelectionTarget::pattern(session, *owner)?.clone();
+ graph.annotations = items;
+ session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
+ }
+ }
+ Ok(())
+ }
+
+ pub(crate) fn next_id(&self, session: &Session, items: &CanvasAnnotations) -> Result {
+ let next = items.next_id().ok_or_else(|| bad("graph annotation", "no available annotation id"))?;
+ Ok(if *self == Self::Graph { next.max(session.graph()?.next_id) } else { next })
+ }
+
+ /// Node positions in this canvas, using the shared node-id representation.
+ pub fn positions(&self, session: &Session) -> Result> {
+ Ok(match self {
+ Self::Graph => {
+ let graph = session.graph()?;
+ match &graph.function {
+ Some(function) => function.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.pos)).collect(),
+ None => graph.nodes.iter().map(|node| (node.id, node.pos)).collect(),
+ }
+ }
+ Self::Function { target } => target.current(session)?.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.pos)).collect(),
+ Self::Pattern { owner } => {
+ SelectionTarget::pattern(session, *owner)?.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.position)).collect()
+ }
+ })
+ }
+
+ /// Capture the nodes and annotations moved with a frame.
+ pub fn capture_frame(&self, session: &Session, frame: &Frame) -> Result {
+ if *self == Self::Graph {
+ return Ok(FrameContents::capture(session.graph()?, frame));
+ }
+
+ let items = self.items(session)?;
+ let nodes: Vec<_> = self.positions(session)?.into_iter().filter(|(_, position)| frame.contains_position(*position)).map(|(id, _)| id).collect();
+ Ok(FrameContents {
+ function_nodes: nodes.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(),
+ nodes,
+ comments: items.comments.iter().filter(|comment| frame.contains_position(comment.pos)).map(|comment| comment.id).collect(),
+ frames: items.frames.iter().filter(|candidate| candidate.id == frame.id || frame.contains_rect(candidate.rect)).map(|frame| frame.id).collect(),
+ pins: items.pins.iter().filter(|pin| frame.contains_position(pin.pos)).map(|pin| pin.id).collect(),
+ })
+ }
+
+ pub(crate) fn move_contents(&self, session: &mut Session, contents: &FrameContents, offset: [f32; 2]) -> Result<()> {
+ if *self == Self::Graph {
+ contents.translate(session.graph_mut()?, offset);
+ return Ok(());
+ }
+
+ let translate = |position: [f32; 2]| crate::graph_grid::snap_position([position[0] + offset[0], position[1] + offset[1]], false);
+ match self {
+ Self::Function { target } => {
+ let mut graph = target.current(session)?.clone();
+ for node in graph.nodes.iter_mut().filter(|node| contents.function_nodes.contains(&node.id)) {
+ node.pos = translate(node.pos);
+ }
+ target.replace(session, graph)?;
+ }
+ Self::Pattern { owner } => {
+ let mut graph = SelectionTarget::pattern(session, *owner)?.clone();
+ for node in graph.nodes.iter_mut().filter(|node| contents.nodes.contains(&NodeId(u64::from(node.id)))) {
+ node.position = translate(node.position);
+ }
+ session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
+ }
+ Self::Graph => {}
+ }
+ let mut items = self.items(session)?;
+ for comment in items.comments.iter_mut().filter(|comment| contents.comments.contains(&comment.id)) {
+ comment.pos = translate(comment.pos);
+ }
+ for frame in items.frames.iter_mut().filter(|frame| contents.frames.contains(&frame.id)) {
+ let position = translate([frame.rect[0], frame.rect[1]]);
+ frame.rect[0] = position[0];
+ frame.rect[1] = position[1];
+ }
+ for pin in items.pins.iter_mut().filter(|pin| contents.pins.contains(&pin.id)) {
+ pin.pos = translate(pin.pos);
+ }
+ self.replace(session, items)
+ }
+}
diff --git a/crates/engine/src/color_space.rs b/crates/engine/src/color_space.rs
new file mode 100644
index 0000000..695cc4e
--- /dev/null
+++ b/crates/engine/src/color_space.rs
@@ -0,0 +1,48 @@
+use serde::{Deserialize, Serialize};
+
+/// How an exported output's values are written
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ColorSpace {
+ /// Color written through the sRGB curve
+ Srgb,
+ /// Color written as linear values
+ Linear,
+ /// Data written unchanged (normal, roughness, height…)
+ #[default]
+ Raw,
+}
+
+impl ColorSpace {
+ pub const ALL: [ColorSpace; 3] = [ColorSpace::Srgb, ColorSpace::Linear, ColorSpace::Raw];
+
+ /// The id `file.export` takes in `colorSpaces`
+ pub fn id(self) -> &'static str {
+ match self {
+ ColorSpace::Srgb => "srgb",
+ ColorSpace::Linear => "linear",
+ ColorSpace::Raw => "raw",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ ColorSpace::Srgb => "sRGB",
+ ColorSpace::Linear => "Linear",
+ ColorSpace::Raw => "Raw",
+ }
+ }
+
+ pub fn from_id(id: &str) -> Option {
+ ColorSpace::ALL.into_iter().find(|space| space.id().eq_ignore_ascii_case(id))
+ }
+
+ /// sRGB for the usages that carry color (base color, emissive…), raw for data maps
+ pub fn for_usage(usage: &str) -> ColorSpace {
+ if materialcraft_formats::material::srgb_usage(usage) { ColorSpace::Srgb } else { ColorSpace::Raw }
+ }
+
+ pub fn encodes_srgb(self) -> bool {
+ self == ColorSpace::Srgb
+ }
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index acc9729..b5f4582 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -60,6 +60,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::explorer_clipboard_commands::specs());
v.extend(crate::graph_instance_commands::specs());
v.extend(crate::function_library_commands::specs());
+ v.extend(crate::node_library_commands::specs());
v.extend(crate::node_info_commands::specs());
v.extend(crate::atomic_sample_commands::specs());
v.extend(crate::material_cmds::specs());
@@ -67,6 +68,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::document_history_commands::specs());
v.extend(crate::embedded_edit_commands::specs());
v.extend(crate::graph_cmds::specs());
+ v.extend(crate::exposed_input_commands::specs());
v.extend(crate::graph_property_commands::specs());
v.extend(crate::alignment_commands::specs());
v.extend(crate::annotation_commands::specs());
@@ -76,7 +78,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::function_variable_commands::specs());
v.extend(crate::evaluation_environment_commands::specs());
v.extend(crate::comment_commands::specs());
+ v.extend(crate::pin_commands::specs());
v.extend(crate::node_cmds::specs());
+ v.extend(crate::parameter_function_commands::specs());
v.extend(crate::node_graph_commands::specs());
v.extend(crate::pattern_graph_commands::specs());
v.extend(crate::connection_commands::specs());
@@ -100,7 +104,7 @@ pub fn execute(s: &mut Session, id: &str, params: &J) -> Result {
}
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
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))) {
+ if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.annotation_target.items(s).is_ok_and(|items| selection.exists(&items))) {
s.annotation_selection = None;
}
@@ -116,6 +120,8 @@ pub fn list(s: &Session, filter: Option<&str>) -> J {
.filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f)))
.map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": if crate::selection_commands::supports(c.id) {
format!("{}; optional function: FunctionGraphTarget or pattern: owner node id, graph: owning graph index; embedded targets use explicit ids; copy returns clip", c.params)
+ } else if c.id.starts_with("graph.annotation.") || c.id.starts_with("graph.frame.") || c.id.starts_with("graph.comment.") {
+ format!("{}; optional function: FunctionGraphTarget or pattern: owner node id", c.params)
} else { c.params.to_string() }, "enabled": crate::selection_commands::enabled(s, c.id, &J::Null).unwrap_or_else(|| (c.enabled)(s).is_ok())}))
.collect(),
)
diff --git a/crates/engine/src/comment_commands.rs b/crates/engine/src/comment_commands.rs
index 103091e..ca0113e 100644
--- a/crates/engine/src/comment_commands.rs
+++ b/crates/engine/src/comment_commands.rs
@@ -13,13 +13,16 @@ pub(crate) fn specs() -> Vec {
}
fn comment_add(session: &mut Session, parameters: &J) -> Result {
+ let target = crate::AnnotationTarget::resolve(session, parameters)?;
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] });
+ let mut items = target.items(session)?;
+ let id = target.next_id(session, &items)?;
+ items.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] });
+ target.replace(session, items)?;
+ session.annotation_target = target;
session.selection.clear();
session.annotation_selection = Some(AnnotationSelection::Comment(id));
Ok(json!({"id": id}))
@@ -27,11 +30,12 @@ fn comment_add(session: &mut Session, parameters: &J) -> Result {
}
fn comment_edit(session: &mut Session, parameters: &J) -> Result {
+ let target = crate::AnnotationTarget::resolve(session, parameters)?;
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}")))?;
+ session.edit_merged(&format!("comment:{target:?}:{id}"), "Edit comment", |session| {
+ let mut items = target.items(session)?;
+ let comment = items.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();
}
@@ -42,16 +46,20 @@ fn comment_edit(session: &mut Session, parameters: &J) -> Result {
comment.size = [size[0].max(40.0), size[1].max(24.0)];
}
+ target.replace(session, items)?;
Ok(J::Null)
})
}
fn comment_delete(session: &mut Session, parameters: &J) -> Result {
+ let target = crate::AnnotationTarget::resolve(session, parameters)?;
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.delete", "`id` is required"))?;
session.edit("Delete comment", |session| {
- session.graph_mut()?.comments.retain(|comment| comment.id != id);
+ let mut items = target.items(session)?;
+ items.comments.retain(|comment| comment.id != id);
+ target.replace(session, items)?;
Ok(J::Null)
})
}
diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs
index 60321be..7dc7e10 100644
--- a/crates/engine/src/edit_cmds.rs
+++ b/crates/engine/src/edit_cmds.rs
@@ -172,13 +172,16 @@ fn has_deletable_selection(session: &Session) -> std::result::Result<(), String>
fn delete_annotation(session: &mut Session) -> Result {
let selection = session.annotation_selection;
+ let target = session.annotation_target.clone();
+ let mut items = target.items(session)?;
+ match selection {
+ Some(crate::AnnotationSelection::Frame(id)) => items.frames.retain(|frame| frame.id != id),
+ Some(crate::AnnotationSelection::Comment(id)) => items.comments.retain(|comment| comment.id != id),
+ Some(crate::AnnotationSelection::Pin(id)) => items.pins.retain(|pin| pin.id != id),
+ None => {}
+ }
session.edit("Delete annotation", |session| {
- let graph = session.graph_mut()?;
- match selection {
- Some(crate::AnnotationSelection::Frame(id)) => graph.frames.retain(|frame| frame.id != id),
- Some(crate::AnnotationSelection::Comment(id)) => graph.comments.retain(|comment| comment.id != id),
- None => {}
- }
+ target.replace(session, items)?;
session.annotation_selection = None;
Ok(json!({"deleted": 1}))
})
diff --git a/crates/engine/src/export_request.rs b/crates/engine/src/export_request.rs
new file mode 100644
index 0000000..def6f7f
--- /dev/null
+++ b/crates/engine/src/export_request.rs
@@ -0,0 +1,143 @@
+use std::collections::HashMap;
+
+use serde_json::Value as J;
+
+use materialcraft_core::Graph;
+use materialcraft_formats::Depth;
+
+use crate::commands::{bad, strp, u64p};
+use crate::{ColorSpace, ExportSize, Result, Session};
+
+const CMD: &str = "file.export";
+
+/// What `file.export` cooks and writes
+#[derive(Clone, Debug, PartialEq)]
+pub struct ExportRequest {
+ pub graph: usize,
+ /// File extension, one of `EXPORT_FORMATS`
+ pub format: String,
+ /// File names with $(graph), $(identifier) and $(usage)
+ pub pattern: String,
+ /// `None` keeps each output's own format
+ pub depth: Option,
+ /// `None` keeps the graph's size
+ pub size: Option,
+ /// Output identifiers to write; `None` writes every connected output
+ pub outputs: Option>,
+ /// Color space per output identifier; outputs without one follow their usage
+ pub color_spaces: HashMap,
+}
+
+impl ExportRequest {
+ /// Every connected output of graph `graph` as PNG at the graph's size
+ pub fn new(graph: usize) -> Self {
+ Self { graph, format: "png".into(), pattern: "$(graph)_$(identifier)".into(), depth: None, size: None, outputs: None, color_spaces: HashMap::new() }
+ }
+
+ /// Read `file.export` params, checking them against the session's package
+ pub fn from_params(s: &Session, p: &J) -> Result {
+ let graph_index = u64p(p, "graph").map_or(s.graph, |index| index as usize);
+ let graph = s.pkg.graph(graph_index)?;
+
+ let format = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
+ if !materialcraft_formats::EXPORT_FORMATS.iter().any(|(extension, _)| *extension == format) {
+ return Err(bad(CMD, format!("unknown format `{format}`")));
+ }
+
+ let depth = match u64p(p, "depth") {
+ None => None,
+ Some(8) => Some(Depth::U8),
+ Some(16) => Some(Depth::U16),
+ Some(32) => Some(Depth::F32),
+ Some(depth) => return Err(bad(CMD, format!("depth must be 8, 16 or 32, not {depth}"))),
+ };
+
+ let identifiers = output_identifiers(graph);
+ let outputs = match p.get("outputs") {
+ None | Some(J::Null) => None,
+ Some(J::Array(items)) => Some(selected_outputs(items, &identifiers, &graph.name)?),
+ Some(_) => return Err(bad(CMD, "`outputs` must be a list of output identifiers")),
+ };
+
+ Ok(Self {
+ graph: graph_index,
+ format,
+ pattern: strp(p, "pattern").unwrap_or("$(graph)_$(identifier)").to_string(),
+ depth,
+ size: export_size(p.get("size"))?,
+ outputs,
+ color_spaces: color_spaces(p.get("colorSpaces"), &identifiers, &graph.name)?,
+ })
+ }
+
+ /// Whether the output named `identifier` is written
+ pub fn includes(&self, identifier: &str) -> bool {
+ self.outputs.as_ref().is_none_or(|outputs| outputs.iter().any(|output| output == identifier))
+ }
+
+ /// The color space output `identifier` with `usage` is written in
+ pub fn color_space(&self, identifier: &str, usage: &str) -> ColorSpace {
+ self.color_spaces.get(identifier).copied().unwrap_or_else(|| ColorSpace::for_usage(usage))
+ }
+}
+
+fn output_identifiers(graph: &Graph) -> Vec {
+ graph.nodes.iter().filter(|node| node.def == "output").map(materialcraft_eval::identifier).collect()
+}
+
+fn selected_outputs(items: &[J], identifiers: &[String], graph: &str) -> Result> {
+ if items.is_empty() {
+ return Err(bad(CMD, "no outputs selected"));
+ }
+
+ items
+ .iter()
+ .map(|item| {
+ let identifier = item.as_str().ok_or_else(|| bad(CMD, "`outputs` must be a list of output identifiers"))?;
+ known_output(identifier, identifiers, graph).map(str::to_string)
+ })
+ .collect()
+}
+
+fn color_spaces(value: Option<&J>, identifiers: &[String], graph: &str) -> Result> {
+ let entries = match value {
+ None | Some(J::Null) => return Ok(HashMap::new()),
+ Some(J::Object(entries)) => entries,
+ Some(_) => return Err(bad(CMD, "`colorSpaces` must map output identifiers to srgb, linear or raw")),
+ };
+
+ entries
+ .iter()
+ .map(|(identifier, space)| {
+ let space =
+ space.as_str().and_then(ColorSpace::from_id).ok_or_else(|| bad(CMD, format!("`{identifier}`: the color space must be srgb, linear or raw")))?;
+ Ok((known_output(identifier, identifiers, graph)?.to_string(), space))
+ })
+ .collect()
+}
+
+fn known_output<'a>(identifier: &'a str, identifiers: &[String], graph: &str) -> Result<&'a str> {
+ if identifiers.iter().any(|known| known == identifier) { Ok(identifier) } else { Err(bad(CMD, format!("graph `{graph}` has no output `{identifier}`"))) }
+}
+
+/// `size`: the larger side in pixels (0 = the graph's size) or `[width, height]`
+fn export_size(value: Option<&J>) -> Result