Merge main into release for MaterialCraft v0.4.0

This commit is contained in:
FredApps committed 2026-11-11 16:35:50 +01:00
commit 683fa2183f
224 files changed
+10920 -1870

No files matched your search

+8 -3
View File
@@ -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:
Generated
+15 -14
View File
@@ -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",
]
+1 -1
View File
@@ -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"
+4 -1
View File
@@ -29,6 +29,9 @@
<img alt="Runs on macOS, Windows, Linux, FreeBSD and the web" src="https://img.shields.io/badge/runs%20on-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20Web-555555?style=flat-square">
<img alt="MCP server for agents" src="https://img.shields.io/badge/agents-MCP%20server-555555?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-555555?style=flat-square">
<br>
<a href="https://sonarcloud.io/project/overview?id=storytold_materialcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/materialcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
</p>
<p align="center">
@@ -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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

-1
View File
@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Unsaved Package"/><formatVersion v="1.1.0.202401"/><updaterVersion v="1.1.0.202401"/><fileUID v="{d761218c-6535-4012-a000-21216d08e74e}"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1584632780"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://3d_perlin_noise.sbs"/><uid v="1437570156"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://3d_simplex_noise.sbs"/><uid v="1311275138"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_voronoi.sbs"/><uid v="1440766644"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://3d_worley_noise.sbs"/><uid v="1217378548"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_anisotropic_noise.sbs"/><uid v="1584639338"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://blue_noise.sbs"/><uid v="1584639858"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_bnw_spots_1.sbs"/><uid v="1584639913"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_bnw_spots_2.sbs"/><uid v="1584640143"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_bnw_spots_3.sbs"/><uid v="1299276443"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_1.sbs"/><uid v="1584642533"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_2.sbs"/><uid v="1584642645"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_3.sbs"/><uid v="1584643037"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_4.sbs"/><uid v="1299276447"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_clouds_1.sbs"/><uid v="1584643174"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_clouds_2.sbs"/><uid v="1584643519"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_clouds_3.sbs"/><uid v="1584643869"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_creased.sbs"/><uid v="1584644203"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_crystal_1.sbs"/><uid v="1584644394"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_crystal_2.sbs"/><uid v="1584644622"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_1.sbs"/><uid v="1584645560"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_2.sbs"/><uid v="1584646017"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_3.sbs"/><uid v="1584646196"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_4.sbs"/><uid v="1584646656"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_scratches.sbs"/><uid v="1584646818"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_1.sbs"/><uid v="1299276460"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_2.sbs"/><uid v="1584646981"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_3.sbs"/><uid v="1584647143"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_4.sbs"/><uid v="1584647426"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_5.sbs"/><uid v="1584647603"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_gradient.sbs"/><uid v="1584647753"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_fluid.sbs"/><uid v="1584648733"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_fractal_sum_1.sbs"/><uid v="1584648924"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_fractal_sum_2.sbs"/><uid v="1584650329"/><type v="packageLine truncated
+1 -1
View File
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Functions"/><formatVersion v="1.1.0.202401"/><updaterVersion v="0.1.3"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><group><identifier v="Functions"/><uid v="1000000002"/><content><group><identifier v="Tonemappers"/><uid v="1000000003"/><content><function><identifier v="tonemap_Hejl"/><uid v="1000000039"/><attributes><category v="Functions/Tonemappers"/><description v="Evaluates the tonemap_Hejl function graph. Result type: Float3. Inputs: input."/><author v=""/><tags v=""/></attributes><paraminputs><paraminput><identifier v="input"/><uid v="1000000040"/><attributes><label v="input"/></attributes><type v="1024"/><defaultValue><constantValueFloat3 v="1 1 1"/></defaultValue><defaultWidget><name v="slider"/><options><option><name v="min"/><value v="0"/></option><option><name v="max"/><value v="1"/></option></options></defaultWidget></paraminput></paraminputs><type v="1024"/><paramValue><dynamicValue><rootnode v="1000000029"/><paramNodes><paramNode><uid v="1000000004"/><function v="max"/><type v="1024"/><GUILayout><gpos v="624 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000018"/></connection><connection><identifier v="b"/><connRef v="1000000011"/></connection></connections></paramNode><paramNode><uid v="1000000005"/><function v="add"/><type v="1024"/><GUILayout><gpos v="1184 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000028"/></connection><connection><identifier v="b"/><connRef v="1000000023"/></connection></connections></paramNode><paramNode><uid v="1000000006"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="scalar"/><connRef v="1000000012"/></connection></connections></paramNode><paramNode><uid v="1000000007"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 64 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="1.25"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000008"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="624 224 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000016"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000009"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="344 64 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000021"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000010"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000019"/></connection><connection><identifier v="scalar"/><connRef v="1000000007"/></connection></connections></paramNode><paramNode><uid v="1000000011"/><function v="const_float3"/><type v="1024"/><GUILayout><gpos v="64 224 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float3"/><constantValue><constantValueFloat3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000012"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 384 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.22"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000013"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000022"/></connection></connections></paramNode><paramNode><uid v="1000000014"/><function v="mul"/><type v="1024"/><GUILayout><gpos v="1464 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="b"/><connRef v="1000000005"/></connection></connections></paramNode><paramNode><uid v="1000000015"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 384 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000032"/></connection></connections></paramNode><paramNode><uid v="1000000016"/><function v="div"/><type v="256"/><GUILayout><gpos v="344 544 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000032"/></connection><connection><identifier v="b"/><connRef vLine truncated
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Functions"/><formatVersion v="1.1.0.202401"/><updaterVersion v="0.4.0"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><group><uid v="1000000002"/><identifier v="Functions"/><content><group><uid v="1000000003"/><identifier v="Tonemappers"/><content><function><identifier v="tonemap_Hejl"/><uid v="1000000039"/><attributes><description v="Evaluates the tonemap_Hejl function graph. Result type: Float3. Inputs: input."/><tags v="Color"/><label v="Hejl tonemapper"/></attributes><paraminputs><paraminput><identifier v="input"/><uid v="1000000040"/><attributes><label v="input"/><description v=""/></attributes><type v="1024"/><defaultValue><constantValueFloat3 v="1 1 1"/></defaultValue><defaultWidget><name v="slider"/><options><option><name v="min"/><value v="0"/></option><option><name v="max"/><value v="1"/></option><option><name v="clamp"/><value v="0"/></option><option><name v="step"/><value v="0.01"/></option></options></defaultWidget></paraminput></paraminputs><type v="1024"/><paramValue><dynamicValue><rootnode v="1000000029"/><paramNodes><paramNode><uid v="1000000004"/><function v="max"/><type v="1024"/><GUILayout><gpos v="624 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000018"/></connection><connection><identifier v="b"/><connRef v="1000000011"/></connection></connections></paramNode><paramNode><uid v="1000000005"/><function v="add"/><type v="1024"/><GUILayout><gpos v="1184 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000028"/></connection><connection><identifier v="b"/><connRef v="1000000023"/></connection></connections></paramNode><paramNode><uid v="1000000006"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="scalar"/><connRef v="1000000012"/></connection></connections></paramNode><paramNode><uid v="1000000007"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 64 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="1.25"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000008"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="624 224 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000016"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000009"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="344 64 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000021"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000010"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000019"/></connection><connection><identifier v="scalar"/><connRef v="1000000007"/></connection></connections></paramNode><paramNode><uid v="1000000011"/><function v="const_float3"/><type v="1024"/><GUILayout><gpos v="64 224 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float3"/><constantValue><constantValueFloat3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000012"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 384 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.22"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000013"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000022"/></connection></connections></paramNode><paramNode><uid v="1000000014"/><function v="mul"/><type v="1024"/><GUILayout><gpos v="1464 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="b"/><connRef v="1000000005"/></connection></connections></paramNode><paramNode><uid v="1000000015"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 384 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000032"/></connection></connections></paramNode><paramNode><uid v="1000000016"/><function v="div"/><type v="256"/><GUILayout><gpos v="344 544 0"/></GUILayout><connections><connectionLine truncated
+6 -5
View File
@@ -185,13 +185,14 @@ impl Headless {
/// Export every output of a graph into folder `dir`
pub fn export(&mut self, p: &Value) -> Result<Value, AutomationError> {
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}))
@@ -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<SaveParams>) -> Result<CallToolResult, McpError> {
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<MenuParams>) -> Result<CallToolResult, McpError> {
to_result(self.bridge_only("ui.menu.invoke", params(&p)).await)
}
@@ -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<String>,
/// 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<u32>,
/// Output identifiers to write (default: every connected output)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outputs: Option<Vec<String>>,
/// 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<std::collections::BTreeMap<String, String>>,
}
+140
View File
@@ -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> {
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,
}
}
}
+14 -2
View File
@@ -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<BaseParameter, FunctionGraph>,
/// 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,
+32
View File
@@ -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<Frame>,
#[serde(default)]
pub comments: Vec<Comment>,
#[serde(default)]
pub pins: Vec<Pin>,
}
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<u64> {
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)
}
}
+22 -1
View File
@@ -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<ParameterEditor>,
#[serde(default)]
pub clamp: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub step: Option<f32>,
#[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,
})
}
}
+34
View File
@@ -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<FunctionNode>,
#[serde(default)]
pub output: Option<u32>,
@@ -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",
+13 -5
View File
@@ -105,13 +105,19 @@ impl Graph {
/// All editable Function canvases, including processor and parameter functions
pub fn functions(&self) -> impl Iterator<Item = &crate::FunctionGraph> {
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<Item = &mut crate::FunctionGraph> {
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<Item = &crate::GraphInstance> {
@@ -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())),
)
+6
View File
@@ -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;
+43
View File
@@ -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",
}
}
}
+3
View File
@@ -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<PatternNode>,
pub root: Option<u32>,
}
@@ -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] }],
}
+7 -3
View File
@@ -8,13 +8,15 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"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<Value> {
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<Value> {
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<Value> {
}
};
session.annotation_target = target;
session.annotation_selection = selection;
if selection.is_some() {
session.selection.clear();
+4 -2
View File
@@ -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),
}
}
}
+150
View File
@@ -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<Self> {
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<CanvasAnnotations> {
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<u64> {
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<Vec<(NodeId, [f32; 2])>> {
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<FrameContents> {
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)
}
}
+48
View File
@@ -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> {
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
}
}
+7 -1
View File
@@ -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<J> {
}
(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(),
)
+15 -7
View File
@@ -13,13 +13,16 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
}
fn comment_add(session: &mut Session, parameters: &J) -> Result<J> {
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<J> {
}
fn comment_edit(session: &mut Session, parameters: &J) -> Result<J> {
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<J> {
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<J> {
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)
})
}
+9 -6
View File
@@ -172,13 +172,16 @@ fn has_deletable_selection(session: &Session) -> std::result::Result<(), String>
fn delete_annotation(session: &mut Session) -> Result<J> {
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}))
})
+143
View File
@@ -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<Depth>,
/// `None` keeps the graph's size
pub size: Option<ExportSize>,
/// Output identifiers to write; `None` writes every connected output
pub outputs: Option<Vec<String>>,
/// Color space per output identifier; outputs without one follow their usage
pub color_spaces: HashMap<String, ColorSpace>,
}
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<Self> {
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<String> {
graph.nodes.iter().filter(|node| node.def == "output").map(materialcraft_eval::identifier).collect()
}
fn selected_outputs(items: &[J], identifiers: &[String], graph: &str) -> Result<Vec<String>> {
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<HashMap<String, ColorSpace>> {
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<Option<ExportSize>> {
let pixels = |value: &J| value.as_u64().or_else(|| value.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64));
let clamp = |pixels: u64| pixels.min(u64::from(u32::MAX)) as u32;
match value {
None | Some(J::Null) => Ok(None),
Some(J::Array(sides)) => match sides.as_slice() {
[width, height] => match (pixels(width), pixels(height)) {
(Some(width), Some(height)) => Ok(Some(ExportSize::Exact([clamp(width), clamp(height)]))),
_ => Err(bad(CMD, "`size` [width, height] takes two pixel counts")),
},
_ => Err(bad(CMD, "`size` [width, height] takes two pixel counts")),
},
Some(value) => match pixels(value) {
Some(0) => Ok(None),
Some(side) => Ok(Some(ExportSize::LargerSide(clamp(side)))),
None => Err(bad(CMD, "`size` is a pixel count or [width, height]")),
},
}
}
+27
View File
@@ -0,0 +1,27 @@
/// The pixel size `file.export` cooks a graph at
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExportSize {
/// The larger side in pixels; the other keeps the graph's proportions
LargerSide(u32),
/// Width and height in pixels
Exact([u32; 2]),
}
impl ExportSize {
/// The graph's log2 size at this export size: pixels round down to powers of two from 16 to 8192
pub fn log2_size(self, graph_size: [u32; 2]) -> [u32; 2] {
match self {
ExportSize::LargerSide(pixels) => {
let target = log2_pixels(pixels);
let bounded = graph_size.map(|side| side.clamp(4, 13));
let larger = bounded[0].max(bounded[1]);
bounded.map(|side| (side + target).saturating_sub(larger).max(4))
}
ExportSize::Exact(pixels) => pixels.map(log2_pixels),
}
}
}
fn log2_pixels(pixels: u32) -> u32 {
31 - pixels.clamp(16, 8192).leading_zeros()
}
+180
View File
@@ -0,0 +1,180 @@
use crate::{
Result, Session, cmd,
commands::{CommandSpec, bad, has_graph, strp},
parameter_target::ParameterTarget,
};
use materialcraft_core::{ExposedParameter, FunctionGraph, ParameterEditor, Value, ValueType};
use serde_json::{Value as J, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.exposed.prepare",
"Prepare graph input",
[],
None,
"{bind: {node, param}, default?} returns input settings without changing the graph",
has_graph,
prepare
),
cmd!(
"graph.exposed.add",
"Expose parameter",
[],
None,
"{id?, label?, group?, description?, default?, min?, max?, editor?, clamp?, step?, bind?: {node, param}}",
has_graph,
add
),
]
}
fn prepare(session: &mut Session, parameters: &J) -> Result<J> {
let (input, _) = prepare_input(session, parameters)?;
Ok(json!(input))
}
fn add(session: &mut Session, parameters: &J) -> Result<J> {
let (input, target) = prepare_input(session, parameters)?;
let value_type = ValueType::of(&input.default).ok_or_else(|| bad("graph.exposed.add", "input must have a scalar or vector type"))?;
let identifier = input.id.clone();
session.edit("Expose parameter", |session| {
let graph = session.graph_mut()?;
graph.exposed.push(input);
if let Some(target) = target {
target.set_function(graph, FunctionGraph::input(&identifier, value_type))?;
}
Ok(json!({"id": identifier}))
})
}
fn number(parameters: &J, name: &str) -> Result<Option<f32>> {
parameters
.get(name)
.filter(|value| !value.is_null())
.map(|value| {
value
.as_f64()
.map(|value| value as f32)
.filter(|value| value.is_finite())
.ok_or_else(|| bad("graph.exposed.add", format!("{name} must be a finite number")))
})
.transpose()
}
fn prepare_input(session: &Session, parameters: &J) -> Result<(ExposedParameter, Option<ParameterTarget>)> {
let command = "graph.exposed.add";
let target = parameters
.get("bind")
.map(|binding| {
ParameterTarget::resolve(
session,
command,
&json!({
"id": binding.get("node"), "param": binding.get("param"), "base": binding.get("base").and_then(J::as_bool).unwrap_or(false)
}),
)
})
.transpose()?;
if matches!(target, Some(ParameterTarget::Base { .. })) {
return Err(bad(command, "only Specific Parameters can be exposed as graph inputs"));
}
let identifier = match strp(parameters, "id").map(str::trim).filter(|identifier| !identifier.is_empty()) {
Some(identifier) => {
if session.graph()?.exposed.iter().any(|input| input.id == identifier) {
return Err(bad(command, format!("an input is already called `{identifier}`")));
}
identifier.to_string()
}
None => {
let target = target.as_ref().ok_or_else(|| bad(command, "id is required"))?;
let graph = session.graph()?;
let base = target.identifier();
(0..=graph.exposed.len())
.map(|suffix| if suffix == 0 { base.to_string() } else { format!("{base}_{suffix}") })
.find(|candidate| !graph.exposed.iter().any(|input| input.id == *candidate))
.ok_or_else(|| bad(command, "cannot allocate an input identifier"))?
}
};
if !identifier.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
return Err(bad(command, "identifier must contain only letters, digits and underscores"));
}
let descriptor = target.as_ref().map(|target| target.descriptor(session, command)).transpose()?;
if descriptor.as_ref().is_some_and(|descriptor| !descriptor.supports_function) {
return Err(bad(command, "this parameter cannot be exposed"));
}
let default = if let Some(value) = parameters.get("default").filter(|value| !value.is_null()) {
let template = descriptor.as_ref().map_or(Value::Float(0.5), |descriptor| descriptor.default.clone());
serde_json::from_value::<Value>(value.clone()).ok().or_else(|| template.coerce_json(value)).ok_or_else(|| bad(command, "invalid default"))?
} else {
match (&target, &descriptor) {
(Some(target), Some(descriptor)) => target.current_value(session, descriptor)?,
_ => Value::Float(0.5),
}
};
let value_type = materialcraft_core::ValueType::of(&default).ok_or_else(|| bad(command, "input must have a scalar or vector type"))?;
if descriptor.as_ref().is_some_and(|descriptor| materialcraft_core::ValueType::of(&descriptor.default) != Some(value_type)) {
return Err(bad(command, "input type does not match the parameter"));
}
if default.as_vec4().is_some_and(|values| values.iter().any(|value| !value.is_finite())) {
return Err(bad(command, "default must be finite"));
}
let default = descriptor.as_ref().and_then(|descriptor| descriptor.default.coerce_json(&json!(default))).unwrap_or(default);
let source_input = target.as_ref().and_then(|target| {
let node = session.graph().ok()?.node(target.node()).ok()?;
let (_, source) = materialcraft_eval::instance_graph(&session.pkg, node)?;
source.exposed.iter().find(|input| input.id == target.identifier())
});
let editor = parameters
.get("editor")
.filter(|value| !value.is_null())
.map(|value| serde_json::from_value::<ParameterEditor>(value.clone()).map_err(|_| bad(command, "unknown parameter editor")))
.transpose()?
.or_else(|| source_input.and_then(|input| input.editor));
if editor.is_some_and(|editor| !ParameterEditor::choices(&default).contains(&editor)) {
return Err(bad(command, "editor does not support this parameter type"));
}
let default = if editor == Some(ParameterEditor::Color) {
match default {
Value::Float4(value) => Value::Color(value),
value => value,
}
} else {
default
};
let input = ExposedParameter {
id: identifier.clone(),
label: strp(parameters, "label").unwrap_or_else(|| descriptor.as_ref().map_or(identifier.as_str(), |descriptor| descriptor.label.as_str())).into(),
group: strp(parameters, "group").unwrap_or("").into(),
description: strp(parameters, "description")
.map(str::to_string)
.unwrap_or_else(|| source_input.map_or_else(String::new, |input| input.description.clone())),
editor: editor.filter(|editor| *editor != ParameterEditor::for_value(&default)),
clamp: parameters
.get("clamp")
.map(|value| value.as_bool().ok_or_else(|| bad(command, "clamp must be a boolean")))
.transpose()?
.unwrap_or_else(|| source_input.is_some_and(|input| input.clamp)),
step: number(parameters, "step")?.or_else(|| source_input.and_then(|input| input.step)),
default,
min: number(parameters, "min")?.unwrap_or_else(|| descriptor.as_ref().map_or(0.0, |descriptor| descriptor.min)),
max: number(parameters, "max")?.unwrap_or_else(|| descriptor.as_ref().map_or(1.0, |descriptor| descriptor.max)),
options: descriptor.map_or_else(Vec::new, |descriptor| descriptor.options),
};
if input.min > input.max {
return Err(bad(command, "minimum must not exceed maximum"));
}
if input.step.is_some_and(|step| step <= 0.0) {
return Err(bad(command, "step must be greater than zero"));
}
Ok((input, target))
}
+43 -60
View File
@@ -8,7 +8,7 @@ use materialcraft_formats::{Depth, encode, output_name};
use crate::commands::{CommandSpec, always, bad, has_graph, has_package, strp, u64p};
use crate::samples::{TEMPLATES, template};
use crate::{Result, Session, cmd};
use crate::{ExportRequest, Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
@@ -38,7 +38,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"Export outputs...",
["File"],
Some("Ctrl+Shift+E"),
"{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, rounded down to a power of two, 16..8192; default the graph's size, keeping its proportions), graph?} cooks the graph at full size and writes every output",
"{dir, format? (png|jpg|tga|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, or [width, height]; rounded down to powers of two, 16..8192; default the graph's size, keeping its proportions), outputs? ([identifier]: default every connected output), colorSpaces? ({identifier: srgb|linear|raw}: default sRGB for color usages, raw for data; linear and raw write values unchanged), graph?} cooks the graph at full size and writes the outputs",
has_graph,
export
),
@@ -301,80 +301,63 @@ fn save(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.save", "the browser saves with a download"))
}
/// Cook graph `gi` at full size and encode every output (`pattern` names files)
pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option<Depth>, size: Option<u32>) -> Result<Vec<Exported>> {
let mut pkg = s.pkg.clone();
if let Some(px) = size {
let g = pkg.graph_mut(gi)?;
// The larger side becomes `px`; the other keeps its proportion
let target = 31 - px.clamp(16, 8192).leading_zeros();
let bounded = g.size.map(|l| l.clamp(4, 13));
let larger = bounded[0].max(bounded[1]);
g.size = bounded.map(|l| (l + target).saturating_sub(larger).max(4));
/// Cook the requested graph at full size and encode its requested outputs (`pattern` names files)
pub fn export_outputs(s: &Session, request: &ExportRequest) -> Result<Vec<Exported>> {
let mut package = s.pkg.clone();
if let Some(size) = request.size {
let graph = package.graph_mut(request.graph)?;
graph.size = size.log2_size(graph.size);
}
let g = pkg.graph(gi)?;
let dec = s.resource_decoder();
let mut options = materialcraft_eval::Options::new(&dec);
let graph = package.graph(request.graph)?;
let decoder = s.resource_decoder();
let mut options = materialcraft_eval::Options::new(&decoder);
options.environment = s.environment;
let cooked = materialcraft_eval::cook(&pkg, gi, &options, &s.cache);
let mut out = Vec::new();
let cooked = materialcraft_eval::cook(&package, request.graph, &options, &s.cache);
let mut files = Vec::new();
let mut names = std::collections::HashSet::new();
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
let Some(img) = img else { continue };
let file = format!("{}.{}", output_name(pattern, &g.name, &ident, usage), ext.trim_start_matches('.'));
for (id, usage, identifier, image) in materialcraft_eval::outputs(graph, &cooked) {
let Some(image) = image.filter(|_| request.includes(&identifier)) else { continue };
let file = format!("{}.{}", output_name(&request.pattern, &graph.name, &identifier, usage), request.format);
if !names.insert(file.to_lowercase()) {
return Err(bad("file.export", format!("duplicate export filename `{file}`: use unique output identifiers or a different filename pattern")));
}
let node = g.node(id)?;
let depth = depth
.unwrap_or_else(|| Depth::from_format(if node.base.format == materialcraft_core::OutputFormat::Inherit { g.format } else { node.base.format }));
let bytes = encode(img, ext, depth, materialcraft_formats::material::srgb_usage(usage))?;
out.push(Exported { file, bytes });
}
if out.is_empty() {
return Err(bad("file.export", "the graph has no connected output nodes"));
}
Ok(out)
}
/// Export params: (graph index, extension, pattern, depth, size)
pub type ExportArgs = (usize, String, String, Option<Depth>, Option<u32>);
pub fn export_params(s: &Session, p: &J) -> Result<ExportArgs> {
let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize);
s.pkg.graph(gi)?;
let ext = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
if !materialcraft_formats::EXPORT_FORMATS.iter().any(|(e, _)| *e == ext) {
return Err(bad("file.export", format!("unknown format `{ext}`")));
let node = graph.node(id)?;
let output_format = if node.base.format == materialcraft_core::OutputFormat::Inherit { graph.format } else { node.base.format };
let depth = request.depth.unwrap_or_else(|| Depth::from_format(output_format));
let bytes = encode(image, &request.format, depth, request.color_space(&identifier, usage).encodes_srgb())?;
files.push(Exported { file, bytes });
}
let pattern = strp(p, "pattern").unwrap_or("$(graph)_$(identifier)").to_string();
let depth = match u64p(p, "depth") {
None => None,
Some(8) => Some(Depth::U8),
Some(16) => Some(Depth::U16),
Some(32) => Some(Depth::F32),
Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))),
};
let size = u64p(p, "size").filter(|&px| px > 0).map(|px| px.min(u64::from(u32::MAX)) as u32);
Ok((gi, ext, pattern, depth, size))
if files.is_empty() {
let reason = if request.outputs.is_some() { "the selected outputs are not connected" } else { "the graph has no connected output nodes" };
return Err(bad("file.export", reason));
}
Ok(files)
}
#[cfg(not(target_arch = "wasm32"))]
fn export(s: &mut Session, p: &J) -> Result<J> {
let dir = strp(p, "dir").ok_or_else(|| bad("file.export", "`dir` is required"))?;
let (gi, ext, pattern, depth, size) = export_params(s, p)?;
let files = export_outputs(s, gi, &ext, &pattern, depth, size)?;
std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?;
for f in &files {
if std::path::Path::new(dir).join(&f.file).exists() {
return Err(bad("file.export", format!("duplicate export filename `{}`: use unique output identifiers or a different filename pattern", f.file)));
}
let files = export_outputs(s, &ExportRequest::from_params(s, p)?)?;
let folder = std::path::Path::new(dir);
std::fs::create_dir_all(folder).map_err(|error| bad("file.export", format!("{dir}: {error}")))?;
// Check every name first so a rejected export leaves the folder untouched
if let Some(existing) = files.iter().find(|exported| folder.join(&exported.file).exists()) {
return Err(bad(
"file.export",
format!("duplicate export filename `{}`: use unique output identifiers or a different filename pattern", existing.file),
));
}
let mut written = Vec::new();
for f in files {
let path = std::path::Path::new(dir).join(&f.file);
materialcraft_formats::write_atomic(&path, &f.bytes)?;
for exported in files {
let path = folder.join(&exported.file);
materialcraft_formats::write_atomic(&path, &exported.bytes)?;
written.push(path.display().to_string());
}
s.log(format!("Exported {} files to {dir}", written.len()));
+23 -14
View File
@@ -1,6 +1,6 @@
use crate::commands::{CommandSpec, bad, boolp, has_graph, point, strp, u64p};
use crate::graph_cmds::nodes_rect;
use crate::{AnnotationSelection, FrameContents, Result, Session, cmd};
use crate::{AnnotationSelection, Result, Session, cmd};
use materialcraft_core::Frame;
use serde_json::{Value as J, json};
@@ -32,6 +32,7 @@ fn color_of(parameters: &J) -> Option<[f32; 4]> {
}
fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
let target = crate::AnnotationTarget::resolve(session, parameters)?;
let rect = match rect_of(parameters) {
Some(rect) => rect,
None => nodes_rect(session, &session.selection)
@@ -45,9 +46,11 @@ fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
let description = strp(parameters, "description").unwrap_or("").to_string();
session.edit("Add frame", |session| {
let graph = session.graph_mut()?;
let id = graph.alloc_id();
graph.frames.push(Frame { id, title, title_visible, description, rect, color });
let mut items = target.items(session)?;
let id = target.next_id(session, &items)?;
items.frames.push(Frame { id, title, title_visible, description, rect, color });
target.replace(session, items)?;
session.annotation_target = target;
session.selection.clear();
session.annotation_selection = Some(AnnotationSelection::Frame(id));
Ok(json!({"id": id}))
@@ -55,10 +58,12 @@ fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
}
fn frame_edit(session: &mut Session, parameters: &J) -> Result<J> {
let target = crate::AnnotationTarget::resolve(session, parameters)?;
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.edit", "`id` is required"))?;
session.edit_merged(&format!("frame{id}"), "Edit frame", |session| {
let frame = session.graph_mut()?.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?;
session.edit_merged(&format!("frame:{target:?}:{id}"), "Edit frame", |session| {
let mut items = target.items(session)?;
let frame = items.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?;
if let Some(text) = strp(parameters, "title") {
frame.title = text.into();
}
@@ -75,35 +80,39 @@ fn frame_edit(session: &mut Session, parameters: &J) -> Result<J> {
frame.color = color;
}
target.replace(session, items)?;
Ok(J::Null)
})
}
fn frame_delete(session: &mut Session, parameters: &J) -> Result<J> {
let target = crate::AnnotationTarget::resolve(session, parameters)?;
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.delete", "`id` is required"))?;
session.edit("Delete frame", |session| {
let graph = session.graph_mut()?;
let previous_count = graph.frames.len();
graph.frames.retain(|frame| frame.id != id);
if previous_count == graph.frames.len() {
let mut items = target.items(session)?;
let previous_count = items.frames.len();
items.frames.retain(|frame| frame.id != id);
if previous_count == items.frames.len() {
return Err(bad("graph.frame.delete", format!("no frame {id}")));
}
target.replace(session, items)?;
Ok(J::Null)
})
}
fn frame_move(session: &mut Session, parameters: &J) -> Result<J> {
let target = crate::AnnotationTarget::resolve(session, parameters)?;
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.move", "`id` is required"))?;
let offset = point(parameters, "by").ok_or_else(|| bad("graph.frame.move", "`by` is required"))?;
let offset = crate::graph_grid::snap_position(offset, boolp(parameters, "snapToGrid").unwrap_or(false));
let graph = session.graph()?;
let frame = graph.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?;
let contents = FrameContents::capture(graph, frame);
let items = target.items(session)?;
let frame = items.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?;
let contents = target.capture_frame(session, frame)?;
session.edit("Move frame and contents", |session| {
contents.translate(session.graph_mut()?, offset);
target.move_contents(session, &contents, offset)?;
Ok(J::Null)
})
+17 -6
View File
@@ -1,5 +1,5 @@
use crate::{Result, Session, commands::bad};
use materialcraft_core::{FunctionGraph, NodeId, Value};
use materialcraft_core::{BaseParameter, FunctionGraph, NodeId, Value};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -15,6 +15,10 @@ pub enum FunctionGraphTarget {
node: NodeId,
parameter: String,
},
Base {
node: NodeId,
parameter: BaseParameter,
},
Pattern {
owner: NodeId,
node: u32,
@@ -27,10 +31,9 @@ impl FunctionGraphTarget {
crate::function_variables::suggestions(self, session, id)
}
pub fn available_operations(&self, session: &Session) -> impl Iterator<Item = &'static materialcraft_nodes::function::FunctionDefinition> + use<> {
let value_processor = matches!(self, Self::Parameter { node, parameter }
if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor"));
materialcraft_nodes::function::FUNCTIONS.iter().filter(move |operation| !value_processor || !matches!(operation.id, "samplelum" | "samplecol"))
/// All function targets accept the native catalog, including samplers for processor image inputs.
pub fn available_operations(&self, _session: &Session) -> impl Iterator<Item = &'static materialcraft_nodes::function::FunctionDefinition> + use<> {
materialcraft_nodes::function::FUNCTIONS.iter()
}
pub fn current<'a>(&self, session: &'a Session) -> Result<&'a FunctionGraph> {
@@ -40,6 +43,9 @@ impl FunctionGraphTarget {
Self::Dynamic { node, parameter } => {
return document.node(*node)?.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing parameter function"));
}
Self::Base { node, parameter } => {
return document.node(*node)?.base.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing base parameter function"));
}
Self::Parameter { node, parameter } => {
let node = document.node(*node)?;
node.params.get(parameter).or_else(|| materialcraft_nodes::find(&node.def)?.param(parameter).map(|parameter| &parameter.default))
@@ -65,7 +71,12 @@ impl FunctionGraphTarget {
match self {
Self::Graph => document.function = Some(function),
Self::Dynamic { node, parameter } => {
document.node_mut(*node)?.functions.insert(parameter.clone(), function);
let owner = document.node_mut(*node)?;
owner.bindings.remove(parameter);
owner.functions.insert(parameter.clone(), function);
}
Self::Base { node, parameter } => {
document.node_mut(*node)?.base.functions.insert(*parameter, function);
}
Self::Parameter { node, parameter } => {
document.node_mut(*node)?.params.insert(parameter.clone(), Value::Function(Box::new(function)));
+3
View File
@@ -24,6 +24,9 @@ pub fn warnings(graph: &Graph) -> Vec<(FunctionGraphTarget, Vec<String>)> {
}
for node in &graph.nodes {
for (parameter, function) in &node.base.functions {
inspect(FunctionGraphTarget::Base { node: node.id, parameter: *parameter }, function);
}
for (parameter, function) in &node.functions {
inspect(FunctionGraphTarget::Dynamic { node: node.id, parameter: parameter.clone() }, function);
}
+1 -20
View File
@@ -1,21 +1,2 @@
use materialcraft_core::Package;
use std::{collections::BTreeMap, sync::Arc};
/// The bundled function library every session loads (see `node_library`)
pub(crate) const STANDARD_PACKAGE: &str = "sbs://functions.sbs";
pub(crate) struct FunctionLibrary {
pub packages: BTreeMap<String, Arc<Package>>,
pub warnings: Vec<String>,
}
pub(crate) fn load() -> Result<FunctionLibrary, String> {
let bytes = materialcraft_formats::sbs::library::read(STANDARD_PACKAGE)?;
let mut read =
materialcraft_formats::sbs::read_sbs(&bytes, STANDARD_PACKAGE, &crate::file_cmds::linked_files(STANDARD_PACKAGE)).map_err(|error| error.to_string())?;
crate::linked_files::normalize_references(&mut read.pkg, STANDARD_PACKAGE);
read.warnings.extend(crate::linked_files::load(&mut read.pkg));
let mut packages = std::mem::take(&mut read.pkg.dependencies);
packages.insert(STANDARD_PACKAGE.into(), Arc::new(read.pkg));
Ok(FunctionLibrary { packages, warnings: read.warnings })
}
+9 -1
View File
@@ -6,8 +6,16 @@ pub fn expected_type(document: &Graph, target: &FunctionGraphTarget) -> Option<V
FunctionGraphTarget::Graph => None,
FunctionGraphTarget::Dynamic { node, parameter } => {
let node = document.node(*node).ok()?;
ValueType::of(&materialcraft_nodes::find(&node.def)?.param(parameter)?.default)
let default = if node.def == "graph_instance" {
node.instance.as_ref()?.defaults.get(parameter)?
} else if node.def == "input_value" && parameter == "default" {
node.params.get(parameter).unwrap_or(&materialcraft_nodes::find(&node.def)?.param(parameter)?.default)
} else {
&materialcraft_nodes::find(&node.def)?.param(parameter)?.default
};
ValueType::of(default)
}
FunctionGraphTarget::Base { parameter, .. } => Some(parameter.value_type()),
FunctionGraphTarget::Parameter { node, parameter } => {
let node = document.node(*node).ok()?;
if node.def != "pixel_processor" || parameter != "function" {
+1 -1
View File
@@ -44,7 +44,7 @@ pub(crate) fn suggestions(target: &FunctionGraphTarget, session: &Session, id: u
}
let owner = match target {
FunctionGraphTarget::Parameter { node, .. } | FunctionGraphTarget::Dynamic { node, .. } => Some(*node),
FunctionGraphTarget::Parameter { node, .. } | FunctionGraphTarget::Dynamic { node, .. } | FunctionGraphTarget::Base { node, .. } => Some(*node),
FunctionGraphTarget::Pattern { owner, .. } => Some(*owner),
FunctionGraphTarget::Graph => None,
};
+32 -98
View File
@@ -2,9 +2,9 @@
use serde_json::{Value as J, json};
use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value};
use materialcraft_core::{MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value};
use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, point, strp, u64p};
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_selection, i64p, ids_param, strp, u64p};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
@@ -22,17 +22,14 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
})
}),
cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32, graph?, document?}", always, format),
cmd!("graph.cook", "Compute graph", [], None, "{full?: bool} cooks now; returns per-node timings and errors", has_graph, cook),
cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, at? [x, y]}", has_graph, pin_add),
cmd!("graph.pin.delete", "Delete pin", [], None, "{id}", has_graph, pin_delete),
cmd!(
"graph.exposed.add",
"Expose parameter",
"graph.cook",
"Compute graph",
[],
None,
"{id (optional with bind: then named after the parameter and kept unique), label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}",
"{full?: bool, graph?: index (another graph of the package cooks at full size into the cache)} cooks now; returns per-node timings and errors",
has_graph,
exposed_add
cook
),
cmd!("graph.exposed.set", "Set input value", [], None, "{id, value}", has_graph, exposed_set),
cmd!("graph.exposed.delete", "Delete input", [], None, "{id}", has_graph, exposed_delete),
@@ -153,8 +150,19 @@ fn format(s: &mut Session, p: &J) -> Result<J> {
}
fn cook(s: &mut Session, p: &J) -> Result<J> {
let cooked = if boolp(p, "full") == Some(true) { s.cook_full(s.graph) } else { s.cook().clone() };
let g = s.graph()?;
let index = match p.get("graph").filter(|graph| !graph.is_null()) {
None => s.graph,
Some(graph) => {
let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?;
let graph = s.pkg.graph(index)?;
if graph.function.is_some() {
return Err(bad("graph.cook", "a Function Graph has no outputs to compute"));
}
index
}
};
let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() };
let g = s.pkg.graph(index)?;
Ok(json!({
"ms": cooked.ms,
"nodes": cooked.nodes.iter().map(|(id, r)| {
@@ -175,85 +183,6 @@ pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> {
(r[0] < f32::MAX).then(|| [r[0], r[1], r[2] - r[0], r[3] - r[1]])
}
fn pin_add(s: &mut Session, p: &J) -> Result<J> {
let at = point(p, "at").unwrap_or([0.0, 0.0]);
s.edit("Add pin", |s| {
let g = s.graph_mut()?;
let id = g.alloc_id();
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| format!("Pin {}", g.pins.len() + 1));
g.pins.push(Pin { id, name, pos: at });
Ok(json!({"id": id}))
})
}
fn pin_delete(s: &mut Session, p: &J) -> Result<J> {
let id = u64p(p, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?;
s.edit("Delete pin", |s| {
s.graph_mut()?.pins.retain(|c| c.id != id);
Ok(J::Null)
})
}
fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
// From a bound node parameter: its value, range and options become the input's
let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string())));
let id = match strp(p, "id").map(str::trim).filter(|i| !i.is_empty()) {
Some(id) => {
if s.graph()?.exposed.iter().any(|e| e.id == id) {
return Err(bad("graph.exposed.add", format!("an input is already called `{id}`")));
}
id.to_string()
}
// Without an `id`, a bound input is named after its parameter, kept unique across nodes
None => {
let (_, param) = bind.as_ref().ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?;
unique_exposed_id(s.graph()?, param)
}
};
let mut default = Value::Float(0.5);
let (mut min, mut max, mut options) = (0.0f32, 1.0f32, Vec::new());
if let Some((node, param)) = &bind {
let g = s.graph()?;
let n = g.node(*node).map_err(|_| bad("graph.exposed.add", format!("no node {}", node.0)))?;
let def = materialcraft_nodes::find(&n.def).ok_or_else(|| bad("graph.exposed.add", "unknown node type"))?;
let pd = def.param(param).ok_or_else(|| bad("graph.exposed.add", format!("`{}` has no parameter `{param}`", n.def)))?;
default = n.params.get(param.as_str()).cloned().unwrap_or_else(|| pd.default.clone());
(min, max) = (pd.min, pd.max);
options = pd.options.iter().map(|o| o.to_string()).collect();
}
if let Some(d) = p.get("default") {
default =
serde_json::from_value::<Value>(d.clone()).ok().or_else(|| default.coerce_json(d)).ok_or_else(|| bad("graph.exposed.add", "bad `default`"))?;
}
let ep = ExposedParameter {
id: id.clone(),
label: strp(p, "label").unwrap_or(&id).to_string(),
group: strp(p, "group").unwrap_or("").to_string(),
default,
min: f32p(p, "min").unwrap_or(min),
max: f32p(p, "max").unwrap_or(max),
options,
};
s.edit("Expose parameter", |s| {
let g = s.graph_mut()?;
g.exposed.push(ep);
if let Some((node, param)) = bind {
g.node_mut(node)?.bindings.insert(param, id.clone());
}
Ok(json!({"id": id}))
})
}
/// An input id not used in `graph`: `base`, `base_1`, `base_2`…
fn unique_exposed_id(graph: &Graph, base: &str) -> String {
let taken = |id: &str| graph.exposed.iter().any(|e| e.id == id);
if !taken(base) {
return base.to_string();
}
(1..).map(|i| format!("{base}_{i}")).find(|id| !taken(id)).unwrap_or_else(|| base.to_string())
}
fn exposed_set(s: &mut Session, p: &J) -> Result<J> {
let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.set", "`id` is required"))?.to_string();
let v = p.get("value").ok_or_else(|| bad("graph.exposed.set", "`value` is required"))?;
@@ -265,15 +194,20 @@ fn exposed_set(s: &mut Session, p: &J) -> Result<J> {
})
}
fn exposed_delete(s: &mut Session, p: &J) -> Result<J> {
let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.delete", "`id` is required"))?.to_string();
s.edit("Delete input", |s| {
let g = s.graph_mut()?;
g.exposed.retain(|e| e.id != id);
g.inputs.remove(&id);
for n in &mut g.nodes {
n.bindings.retain(|_, v| *v != id);
fn exposed_delete(session: &mut Session, parameters: &J) -> Result<J> {
let identifier = strp(parameters, "id").ok_or_else(|| bad("graph.exposed.delete", "`id` is required"))?.to_string();
session.edit("Delete input", |session| {
let graph = session.graph_mut()?;
graph.exposed.retain(|input| input.id != identifier);
graph.inputs.remove(&identifier);
for node in &mut graph.nodes {
node.bindings.retain(|_, input| *input != identifier);
// Detach direct input links without discarding user-authored function logic
node.functions.retain(|_, function| function.input_identifier() != Some(identifier.as_str()));
node.base.functions.retain(|_, function| function.input_identifier() != Some(identifier.as_str()));
}
Ok(J::Null)
})
}
+77 -73
View File
@@ -4,91 +4,95 @@ use serde_json::{Value as J, json};
use crate::Session;
pub fn session(s: &Session, graph: Option<usize>) -> J {
let gi = graph.unwrap_or(s.graph);
let g = s.pkg.graphs.get(gi);
let cooked = (gi == s.graph).then_some(&s.cooked);
let graph_json = g.map(|g| {
pub fn session(session: &Session, requested_graph: Option<usize>) -> J {
let graph_index = requested_graph.unwrap_or(session.graph);
let graph = session.pkg.graphs.get(graph_index);
let cooked = (graph_index == session.graph).then_some(&session.cooked);
let graph_json = graph.map(|graph| {
let mut result = json!({
"index": gi,
"name": g.name,
"path": g.sbs_path(),
"kind": g.kind(),
"function": g.function,
"functionWarnings": crate::function_inspection::warnings(g).into_iter().map(|(target, messages)| json!({"target": target, "messages": messages})).collect::<Vec<_>>(),
"size": g.size_px(),
"format": g.format,
"seed": g.seed,
"attributes": g.attributes,
"exposed": g.exposed,
"presets": g.presets,
"inputs": g.inputs,
"inputImages": g.input_images,
"inputImagesLinear": g.input_images_linear,
"nodes": g.nodes.iter().map(|n| {
let r = cooked.and_then(|c| c.nodes.get(&n.id));
let (ins, outs) = materialcraft_eval::ports(&s.pkg, g, n);
"index": graph_index,
"name": graph.name,
"path": graph.sbs_path(),
"kind": graph.kind(),
"function": graph.function,
"functionWarnings": crate::function_inspection::warnings(graph).into_iter().map(|(target, messages)| json!({"target": target, "messages": messages})).collect::<Vec<_>>(),
"size": graph.size_px(),
"format": graph.format,
"seed": graph.seed,
"attributes": graph.attributes,
"exposed": graph.exposed,
"presets": graph.presets,
"inputs": graph.inputs,
"inputImages": graph.input_images,
"inputImagesLinear": graph.input_images_linear,
"nodes": graph.nodes.iter().map(|node| {
let entry = cooked.and_then(|cooked| cooked.nodes.get(&node.id));
let (inputs, outputs) = materialcraft_eval::ports(&session.pkg, graph, node);
let node_cooked = entry.map(|entry| json!({
"error": entry.error, "ms": entry.ms, "cached": entry.cached,
"base": entry.base, "baseValues": entry.base_values, "parameters": entry.parameters,
"value": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value),
"size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.w, image.h]),
"kind": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| if image.is_gray() { "gray" } else { "color" }),
"mean": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| image.mean()),
}));
json!({
"id": n.id.0,
"def": n.def,
"instance": n.instance,
"label": if n.label.is_empty() { materialcraft_nodes::find(&n.def).map_or(n.def.as_str(), |d| d.label).to_string() } else { n.label.clone() },
"pos": n.pos,
"params": n.params,
"bindings": n.bindings,
"functions": n.functions,
"inputValues": n.input_values,
"base": n.base,
"disabled": n.disabled,
"inputs": ins.iter().map(|p| &p.id).collect::<Vec<_>>(),
"outputs": outs.iter().map(|p| &p.id).collect::<Vec<_>>(),
"cooked": r.map(|r| json!({
"error": r.error, "ms": r.ms, "cached": r.cached,
"value": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value),
"size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h]),
"kind": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| if i.is_gray() { "gray" } else { "color" }),
"mean": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| i.mean()),
})),
"id": node.id.0,
"def": node.def,
"instance": node.instance,
"label": if node.label.is_empty() { materialcraft_nodes::find(&node.def).map_or(node.def.as_str(), |definition| definition.label).to_string() } else { node.label.clone() },
"pos": node.pos,
"params": node.params,
"bindings": node.bindings,
"functions": node.functions,
"inputValues": node.input_values,
"base": node.base,
"disabled": node.disabled,
"inputs": inputs.iter().map(|port| &port.id).collect::<Vec<_>>(),
"outputs": outputs.iter().map(|port| &port.id).collect::<Vec<_>>(),
"cooked": node_cooked,
})
}).collect::<Vec<_>>(),
"connections": g.connections,
"frames": g.frames,
"comments": g.comments,
"pins": g.pins,
"connections": graph.connections,
"frames": graph.frames,
"comments": graph.comments,
"pins": graph.pins,
});
result["physicalSize"] = json!(g.physical_size);
result["pixelRatio"] = json!(g.pixel_ratio);
result["pixelRatioMode"] = json!(g.pixel_ratio_mode);
result["tiling"] = json!(g.tiling);
result["tilingMode"] = json!(g.tiling_mode);
result["physicalSize"] = json!(graph.physical_size);
result["pixelRatio"] = json!(graph.pixel_ratio);
result["pixelRatioMode"] = json!(graph.pixel_ratio_mode);
result["tiling"] = json!(graph.tiling);
result["tilingMode"] = json!(graph.tiling_mode);
result
});
json!({
"documents": s.inspect_documents(),
"package": s.has_package().then(|| json!({"name": s.pkg.name, "path": s.path, "modified": s.modified, "folders": s.pkg.folder_paths(), "folderDescriptions": s.pkg.folder_descriptions, "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "folder": r.folder, "file": r.file, "missing": r.bytes.is_empty(), "bytes": r.bytes.len()})).collect::<Vec<_>>()})),
"graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "path": g.sbs_path(), "nodes": g.nodes.len(), "kind": g.kind()})).collect::<Vec<_>>(),
"openGraph": g.map(|_| s.graph),
"documents": session.inspect_documents(),
"package": session.has_package().then(|| json!({"name": session.pkg.name, "path": session.path, "modified": session.modified, "folders": session.pkg.folder_paths(), "folderDescriptions": session.pkg.folder_descriptions, "warnings": session.load_warnings, "resources": session.pkg.resources.iter().map(|entry| json!({"name": entry.name, "folder": entry.folder, "file": entry.file, "missing": entry.bytes.is_empty(), "bytes": entry.bytes.len()})).collect::<Vec<_>>()})),
"graphs": session.pkg.graphs.iter().enumerate().map(|(index, graph)| json!({"index": index, "name": graph.name, "path": graph.sbs_path(), "nodes": graph.nodes.len(), "kind": graph.kind()})).collect::<Vec<_>>(),
"openGraph": graph.map(|_| session.graph),
"graph": graph_json,
"annotationSelection": s.annotation_selection,
"selection": s.selection.iter().map(|i| i.0).collect::<Vec<_>>(),
"view2d": s.view2d,
"view3d": s.view3d,
"annotationSelection": session.annotation_selection,
"annotationTarget": session.annotation_target,
"selection": session.selection.iter().map(|index| index.0).collect::<Vec<_>>(),
"view2d": session.view2d,
"view3d": session.view3d,
"material3d": {
"assignments": s.material_preview,
"channels": s.material_preview.sources(&s.pkg).into_iter().map(|(channel, source)| {
let image = s.material_image(&source);
"assignments": session.material_preview,
"channels": session.material_preview.sources(&session.pkg).into_iter().map(|(channel, source)| {
let image = session.material_image(&source);
json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())})
}).collect::<Vec<_>>(),
},
"previewSize": s.preview_size,
"camera": s.camera,
"environment": s.environment,
"cookMs": s.cooked.ms,
"dirty": s.dirty,
"history": s.history(),
"historyPreferences": s.history_prefs,
"canUndo": s.can_undo(),
"canRedo": s.can_redo(),
"log": s.log.iter().rev().take(20).collect::<Vec<_>>(),
"previewSize": session.preview_size,
"camera": session.camera,
"environment": session.environment,
"cookMs": session.cooked.ms,
"dirty": session.dirty,
"history": session.history(),
"historyPreferences": session.history_prefs,
"canUndo": session.can_undo(),
"canRedo": session.can_redo(),
"log": session.log.iter().rev().take(20).collect::<Vec<_>>(),
})
}
+19
View File
@@ -1,6 +1,9 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(test)]
extern crate self as materialcraft_engine;
mod document_path;
mod evaluation_environment_commands;
mod explorer_clipboard;
@@ -11,6 +14,9 @@ mod folder_property_commands;
pub use explorer_clipboard::ExplorerClipboard;
mod function_library;
mod function_library_commands;
pub mod node_library;
mod node_library_commands;
pub use node_library::{LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary};
mod function_variable;
mod function_variable_commands;
mod function_variables;
@@ -67,8 +73,14 @@ pub mod wire_swap;
pub use commands::{CommandSpec, command_specs, execute, find};
pub use session::{CameraPrefs, Session, View2d, View3d, WARNING_PREFIX};
mod clip;
mod color_space;
mod connection_commands;
mod export_request;
mod export_size;
pub use clip::Clip;
pub use color_space::ColorSpace;
pub use export_request::ExportRequest;
pub use export_size::ExportSize;
pub use materialcraft_core as core;
pub use materialcraft_eval as eval;
@@ -99,12 +111,15 @@ pub use exported::Exported;
mod annotation_commands;
mod annotation_selection;
mod annotation_target;
pub use annotation_target::AnnotationTarget;
mod comment_commands;
mod frame_commands;
mod frame_contents;
mod function_commands;
mod node_graph_commands;
mod pattern_graph_commands;
mod pin_commands;
mod snapshot;
pub use annotation_selection::AnnotationSelection;
pub use frame_contents::FrameContents;
@@ -116,7 +131,11 @@ mod function_graph_target;
mod function_info_commands;
pub mod function_inspection;
pub mod function_output;
mod parameter_function_commands;
mod parameter_target;
mod pattern_edit;
pub use function_edit::FunctionEdit;
pub use function_graph_target::FunctionGraphTarget;
pub use pattern_edit::PatternEdit;
mod exposed_input_commands;
+23
View File
@@ -37,6 +37,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap<String, Arc<Package>>) -
if node.def != "graph_instance" {
return None;
}
let materialcraft_core::Value::Text(name) = node.params.get("graph")? else { return None };
Some(GraphInstance {
label: String::new(),
@@ -52,7 +53,9 @@ fn interfaces(package: &mut Package, sources: &BTreeMap<String, Arc<Package>>) -
if graph.function.is_some() {
return None;
}
let (mut inputs, mut outputs) = materialcraft_nodes::graph_interface::graph_ports(graph);
// Keep connected missing ports so saving cannot silently discard the user's wires
for port in &instance.inputs {
if owner.connections.iter().any(|wire| wire.to == node.id && wire.to_port == port.identifier)
@@ -68,18 +71,23 @@ fn interfaces(package: &mut Package, sources: &BTreeMap<String, Arc<Package>>) -
outputs.push(port.clone());
}
}
instance.inputs = inputs;
instance.outputs = outputs;
instance.defaults =
graph.exposed.iter().map(|parameter| (parameter.id.clone(), graph.input_value(&parameter.id).unwrap_or(&parameter.default).clone())).collect();
instance.label = graph.display_name().into();
(node.instance.as_ref() != Some(&instance)).then_some((graph_index, node_index, instance))
})
.collect();
let mut changed = !updates.is_empty();
for (graph, node, instance) in updates {
if let Some(node) = package.graphs.get_mut(graph).and_then(|graph| graph.nodes.get_mut(node)) {
node.instance = Some(instance);
}
}
let local = package.clone();
for function in package.graphs.iter_mut().flat_map(|graph| graph.functions_mut()) {
if function.nodes.iter().any(|node| node.instance.is_some()) {
@@ -88,6 +96,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap<String, Arc<Package>>) -
changed |= *function != previous;
}
}
changed
}
@@ -97,8 +106,15 @@ impl Session {
self.refresh_links_from(BTreeSet::new());
}
/// Refresh linked interfaces and retain ownership of installed library snapshots.
pub(crate) fn refresh_links_from(&mut self, mut changed: BTreeSet<String>) {
// Replaced snapshots belong to the caller, even when their library alias is unchanged
self.library_sources.retain(|path, owned| self.linked_sources.get(path).is_some_and(|source| Arc::ptr_eq(source, owned)));
let open_paths: BTreeSet<_> = self.open_packages().into_iter().filter_map(|(_, _, path, _)| path.map(str::to_string)).collect();
self.library_sources.retain(|path, _| !open_paths.contains(path));
let mut sources = self.linked_sources.clone();
// Interface types can propagate through several files; the workspace has at most 64 open packages
for _ in 0..64 {
for (_, package, path, _) in self.open_packages() {
@@ -142,6 +158,13 @@ impl Session {
}
document.pkg.dependencies = sources.clone();
}
// Interface refreshes replace Arcs without changing who owns the source
for (path, owned) in &mut self.library_sources {
if let Some(source) = sources.get(path) {
*owned = source.clone();
}
}
self.linked_sources = sources;
}
}
+66 -111
View File
@@ -30,29 +30,18 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
[],
None,
"{id?, param, value} (numbers, [x, y], \"#rrggbb\", enum index, typed {t, v})",
has_selection,
has_graph,
set_param
),
cmd!("graph.node.reset", "Reset parameters", [], None, "{id?, param? (default: all)}", has_selection, reset),
cmd!(
"graph.node.base",
"Set base parameters",
[],
None,
"{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling?: bool|[bool,bool], pixelRatio?: 0|1, tilingMode?, pixelRatioMode? (relativeToInput|relativeToParent|absolute)}",
has_selection,
"{id?, param?: outputsize|format|pixelsize|pixelratio|tiling|randomseed, value?, inheritance?: relativeToInput|relativeToParent|absolute}; legacy fields: {sizeMode?, size?: [w, h] (log2), format?: inherit|u8|u16|f16|f32, seed?, tiling?: bool|[bool,bool], pixelRatio?: 0|1, tilingMode?, pixelRatioMode?}",
has_graph,
base
),
cmd!("graph.node.bind", "Bind parameter to input", [], None, "{id?, param, input (exposed id); input null unbinds}", has_selection, bind),
cmd!(
"graph.node.function",
"Set parameter function",
[],
None,
"{id?, param, function?: {nodes, output} (default: a constant of the current value), remove?: bool} drives a parameter with a function graph of the graph's inputs",
has_selection,
set_function
),
]
}
@@ -166,71 +155,83 @@ fn disable(s: &mut Session, p: &J) -> Result<J> {
})
}
fn set_param(s: &mut Session, p: &J) -> Result<J> {
let id = node_param(s, "graph.node.param", p, "id")?;
let param = strp(p, "param").ok_or_else(|| bad("graph.node.param", "`param` is required"))?.to_string();
let v = p.get("value").ok_or_else(|| bad("graph.node.param", "`value` is required"))?;
let node = s.graph()?.node(id)?.clone();
let value = if node.def == "input_value" && param == "default" {
fn set_param(session: &mut Session, parameters: &J) -> Result<J> {
let id = node_param(session, "graph.node.param", parameters, "id")?;
let parameter = strp(parameters, "param").ok_or_else(|| bad("graph.node.param", "`param` is required"))?.to_string();
let supplied = parameters.get("value").ok_or_else(|| bad("graph.node.param", "`value` is required"))?;
let node = session.graph()?.node(id)?.clone();
let value = if node.def == "input_value" && parameter == "default" {
let current = node.params.get("default").cloned().unwrap_or(Value::Float(0.0));
serde_json::from_value::<Value>(v.clone())
serde_json::from_value::<Value>(supplied.clone())
.ok()
.or_else(|| current.coerce_json(v))
.or_else(|| current.coerce_json(supplied))
.filter(|value| materialcraft_core::ValueType::of(value).is_some())
.ok_or_else(|| bad("graph.node.param", "default must be a scalar or vector value"))?
} else if node.def == "graph_instance" {
// Instance parameters: the sub-graph's exposed inputs (and `graph`)
if param == "graph" {
Value::Text(v.as_str().ok_or_else(|| bad("graph.node.param", "`graph` is a graph name"))?.into())
// Instance parameters come from the source graph's exposed inputs
if parameter == "graph" {
Value::Text(supplied.as_str().ok_or_else(|| bad("graph.node.param", "`graph` is a graph name"))?.into())
} else {
let sub =
materialcraft_eval::instance_graph(&s.pkg, &node).map(|(_, g)| g).ok_or_else(|| bad("graph.node.param", "the instanced graph is missing"))?;
let e = sub.exposed.iter().find(|e| e.id == param).ok_or_else(|| bad("graph.node.param", format!("the graph has no input `{param}`")))?;
e.default.coerce_json(v).ok_or_else(|| bad("graph.node.param", format!("`{param}` takes a {}", e.default.type_name())))?
let source = materialcraft_eval::instance_graph(&session.pkg, &node)
.map(|(_, g)| g)
.ok_or_else(|| bad("graph.node.param", "the instanced graph is missing"))?;
let input = source
.exposed
.iter()
.find(|input| input.id == parameter)
.ok_or_else(|| bad("graph.node.param", format!("the graph has no input `{parameter}`")))?;
input.default.coerce_json(supplied).ok_or_else(|| bad("graph.node.param", format!("`{parameter}` takes a {}", input.default.type_name())))?
}
} else {
let def = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.param", format!("unknown node `{}`", node.def)))?;
let pd = def.param(&param).ok_or_else(|| bad("graph.node.param", format!("`{}` has no parameter `{param}`", node.def)))?;
let mut v = pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.param", format!("`{param}` takes a {}", pd.default.type_name())))?;
if let Value::Enum(i) = &mut v
&& !pd.options.is_empty()
let definition = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.param", format!("unknown node `{}`", node.def)))?;
let descriptor = definition.param(&parameter).ok_or_else(|| bad("graph.node.param", format!("`{}` has no parameter `{parameter}`", node.def)))?;
let mut value = descriptor
.default
.coerce_json(supplied)
.ok_or_else(|| bad("graph.node.param", format!("`{parameter}` takes a {}", descriptor.default.type_name())))?;
if let Value::Enum(i) = &mut value
&& !descriptor.options.is_empty()
{
*i = (*i).min(pd.options.len() as u32 - 1);
*i = (*i).min(descriptor.options.len() as u32 - 1);
}
v
value
};
crate::graph_validation::value(&value).map_err(|error| bad("graph.node.param", error))?;
s.edit_merged(&format!("param:{}:{param}", id.0), "Set parameter", |s| {
s.graph_mut()?.node_mut(id)?.params.insert(param.clone(), value);
Ok(J::Null)
})
}
fn reset(s: &mut Session, p: &J) -> Result<J> {
let id = node_param(s, "graph.node.reset", p, "id")?;
let param = strp(p, "param").map(str::to_string);
s.edit("Reset parameters", |s| {
let n = s.graph_mut()?.node_mut(id)?;
match &param {
Some(k) => {
n.params.remove(k);
n.bindings.remove(k);
n.functions.remove(k);
}
None => {
n.params.retain(|k, _| k == "graph" || k == "identifier");
n.bindings.clear();
n.functions.clear();
}
}
session.edit_merged(&format!("param:{}:{parameter}", id.0), "Set parameter", |session| {
let node = session.graph_mut()?.node_mut(id)?;
node.functions.remove(&parameter);
node.bindings.remove(&parameter);
node.params.insert(parameter.clone(), value);
Ok(J::Null)
})
}
fn base(session: &mut Session, parameters: &J) -> Result<J> {
let id = node_param(session, "graph.node.base", parameters, "id")?;
if let Some(identifier) = strp(parameters, "param") {
let parameter = materialcraft_core::BaseParameter::named(identifier).ok_or_else(|| bad("graph.node.base", "unknown base parameter"))?;
let mut base = session.graph()?.node(id)?.base.clone();
let inheritance = parameter.inheritance(&base);
if let Some(value) = parameters.get("value") {
let value = parameter.value(&base).coerce_json(value).ok_or_else(|| bad("graph.node.base", "incorrect base parameter type"))?;
parameter.set_value(&mut base, &value).map_err(|error| bad("graph.node.base", error))?;
parameter.set_inheritance(&mut base, inheritance);
base.functions.remove(&parameter);
}
if let Some(inheritance) = parameters.get("inheritance") {
let inheritance = serde_json::from_value(inheritance.clone()).map_err(|error| bad("graph.node.base", format!("invalid inheritance: {error}")))?;
parameter.set_inheritance(&mut base, inheritance);
}
return session.edit_merged(&format!("base:{}:{identifier}", id.0), "Set base parameter", |session| {
session.graph_mut()?.node_mut(id)?.base = base;
Ok(J::Null)
});
}
let mode = match strp(parameters, "sizeMode") {
None => None,
Some("relativeToInput") => Some(SizeMode::RelativeToInput),
@@ -283,15 +284,20 @@ fn base(session: &mut Session, parameters: &J) -> Result<J> {
}
if let Some(size) = size {
base.size = size;
base.functions.remove(&materialcraft_core::BaseParameter::OutputSize);
}
if let Some(format) = format {
base.format = format;
base.format_mode = materialcraft_core::ParameterInheritance::Absolute;
base.functions.remove(&materialcraft_core::BaseParameter::Format);
}
if let Some(seed) = seed {
base.seed = seed;
base.functions.remove(&materialcraft_core::BaseParameter::RandomSeed);
}
if let Some(tiling) = tiling {
base.tiling = tiling;
base.functions.remove(&materialcraft_core::BaseParameter::Tiling);
base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute;
}
if let Some(mode) = tiling_mode {
@@ -299,6 +305,7 @@ fn base(session: &mut Session, parameters: &J) -> Result<J> {
}
if let Some(value) = pixel_ratio {
base.pixel_ratio = value;
base.functions.remove(&materialcraft_core::BaseParameter::PixelRatio);
base.pixel_ratio_mode = materialcraft_core::ParameterInheritance::Absolute;
}
if let Some(mode) = pixel_ratio_mode {
@@ -308,55 +315,3 @@ fn base(session: &mut Session, parameters: &J) -> Result<J> {
Ok(J::Null)
})
}
fn bind(s: &mut Session, p: &J) -> Result<J> {
let id = node_param(s, "graph.node.bind", p, "id")?;
let param = strp(p, "param").ok_or_else(|| bad("graph.node.bind", "`param` is required"))?.to_string();
let input = strp(p, "input").map(str::to_string);
if let Some(i) = &input
&& !s.graph()?.exposed.iter().any(|e| &e.id == i)
{
return Err(bad("graph.node.bind", format!("no input `{i}`")));
}
s.edit("Bind parameter", |s| {
let n = s.graph_mut()?.node_mut(id)?;
match input {
Some(i) => n.bindings.insert(param, i),
None => n.bindings.remove(&param),
};
Ok(J::Null)
})
}
fn set_function(s: &mut Session, p: &J) -> Result<J> {
let id = node_param(s, "graph.node.function", p, "id")?;
let param = strp(p, "param").ok_or_else(|| bad("graph.node.function", "`param` is required"))?.to_string();
let node = s.graph()?.node(id)?.clone();
let def = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.function", "unknown node type"))?;
let pd = def.param(&param).ok_or_else(|| bad("graph.node.function", format!("`{}` has no parameter `{param}`", node.def)))?;
if matches!(pd.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_)) {
return Err(bad("graph.node.function", format!("`{param}` is a {} and can't take a function", pd.default.type_name())));
}
if boolp(p, "remove") == Some(true) {
return s.edit("Remove parameter function", |s| {
s.graph_mut()?.node_mut(id)?.functions.remove(&param);
Ok(J::Null)
});
}
let f = match p.get("function") {
Some(f) if !f.is_null() => {
serde_json::from_value::<materialcraft_core::FunctionGraph>(f.clone()).map_err(|e| bad("graph.node.function", format!("bad function: {e}")))?
}
_ => match node.functions.get(&param) {
Some(f) => f.clone(),
None => materialcraft_core::FunctionGraph::constant(node.params.get(&param).cloned().unwrap_or_else(|| pd.default.clone())),
},
};
crate::graph_validation::function(&f).map_err(|error| bad("graph.node.function", error))?;
s.edit_merged(&format!("fn:{}:{param}", id.0), "Set parameter function", |s| {
s.graph_mut()?.node_mut(id)?.functions.insert(param.clone(), f);
Ok(J::Null)
})
}
+458
View File
@@ -0,0 +1,458 @@
//! The node library. Every SBS package in the library folder (`assets/sbs`, or the bundled copies)
//! is loaded once per process and lends its graphs: function graphs go under Functions (sorted by
//! their classification tags, with folder fallbacks), other graphs under their attribute category. Native nodes, function operations,
//! FX-Map nodes and graph items fill the rest of the tree. A package whose titled frames are library
//! categories ("Filters - Blurs") can also lay the library out: each node inside a frame becomes an
//! entry in that category, listed as missing until a package provides it.
mod library_canvas;
mod library_entry;
mod library_item;
mod library_placement;
pub use library_canvas::LibraryCanvas;
pub use library_entry::LibraryEntry;
pub use library_item::LibraryItem;
use library_placement::LibraryPlacement;
use materialcraft_core::{Package, PatternNodeKind};
use materialcraft_formats::sbs::{LayoutItem, library};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex};
/// The library tree in display order: top-level categories and their sub-categories. The UI adds
/// Favorites above it
pub const CATEGORIES: &[(&str, &[&str])] = &[
("Graph items", &[]),
("Atomic nodes", &[]),
("FxMap nodes", &[]),
("Function nodes", &["Constant", "Vector", "Variables", "Samplers", "Cast", "Operator", "Logical", "Comparison", "Function", "Control"]),
("Texture generators", &["Noises", "Patterns"]),
("Filters", &["Adjustments", "Blending", "Blurs", "Channels", "Effects", "Normal map", "Tiling", "Transforms"]),
("Material filters", &["1-click", "Effects", "Transforms", "Blending", "PBR utilities", "Scan processing"]),
("Mesh-based generators", &["Mask generators", "Weathering", "Utilities"]),
("Spline & Path tools", &["Spline tools", "Path tools"]),
("MCF functions", &["Primitives", "Operators", "Transforms"]),
("Functions", &["Color", "Comparison", "Constant", "Conversion", "Maths", "Parity", "Random", "Transformation", "Various", "Easings"]),
("3D view", &["HDRI environments", "HDRI tools"]),
("PBR materials", &["Bricks", "Concrete", "Fabric", "Ground", "Metal", "Paper", "Pavement", "Tiles", "Wood", "Stone"]),
("Values", &["Constant"]),
];
/// Older layouts name categories MaterialCraft has renamed: (old, current)
const RENAMED: &[(&str, &str)] = &[("SDF functions", "MCF functions")];
/// Words that place a material in a sub-category when its layout frame names only the top level
const SUB_KEYWORDS: &[(&str, &str, &[&str])] = &[
("PBR materials", "Bricks", &["brick"]),
("PBR materials", "Concrete", &["concrete", "cement"]),
("PBR materials", "Fabric", &["fabric", "cloth", "textile", "leather"]),
("PBR materials", "Ground", &["ground", "gravel", "soil", "sand", "dirt", "grass", "mud"]),
("PBR materials", "Metal", &["metal", "steel", "iron", "copper", "rust"]),
("PBR materials", "Paper", &["paper", "cardboard"]),
("PBR materials", "Pavement", &["pavement", "paving", "cobble", "asphalt"]),
("PBR materials", "Tiles", &["tile"]),
("PBR materials", "Wood", &["wood", "plank", "bark"]),
("PBR materials", "Stone", &["stone", "rock", "marble", "granite"]),
];
/// Everything loaded from the library folder
#[derive(Debug, Default)]
pub struct NodeLibrary {
/// Library packages (layouts excluded) and their own dependencies, by `sbs://` path
pub packages: BTreeMap<String, Arc<Package>>,
/// The `sbs://` files that laid the library out
pub layouts: Vec<String>,
pub warnings: Vec<String>,
placements: Vec<LibraryPlacement>,
}
static SHARED: Mutex<Option<Arc<NodeLibrary>>> = Mutex::new(None);
impl NodeLibrary {
/// The process's library, loaded on first use
pub fn shared() -> Arc<NodeLibrary> {
let mut shared = SHARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
shared.get_or_insert_with(|| Arc::new(Self::load(&library::files()))).clone()
}
/// Read the library folder again (after packages were added or changed on disk)
pub fn reload() -> Arc<NodeLibrary> {
let library = Arc::new(Self::load(&library::files()));
*SHARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(library.clone());
library
}
/// Load `files` (`sbs://` paths)
pub fn load(files: &[String]) -> NodeLibrary {
let mut out = NodeLibrary::default();
for uri in files {
let bytes = match library::read(uri) {
Ok(bytes) => bytes,
Err(error) => {
out.warnings.push(format!("Library package {uri}: {error}"));
continue;
}
};
// A layout's frames name library categories; anything else is a package of graphs
let placements = match materialcraft_formats::sbs::read_layout(&bytes, uri) {
Ok(frames) => placements(&frames),
Err(error) => {
out.warnings.push(format!("Library package {uri}: {error}"));
continue;
}
};
if !placements.is_empty() {
out.placements.extend(placements);
out.layouts.push(uri.clone());
continue;
}
match materialcraft_formats::sbs::read_sbs(&bytes, uri, &crate::file_cmds::linked_files(uri)) {
Ok(mut read) => {
crate::linked_files::normalize_references(&mut read.pkg, uri);
read.warnings.extend(crate::linked_files::load(&mut read.pkg));
out.warnings.extend(read.warnings);
for (path, package) in std::mem::take(&mut read.pkg.dependencies) {
out.packages.entry(path).or_insert(package);
}
out.packages.insert(uri.clone(), Arc::new(read.pkg));
}
Err(error) => out.warnings.push(format!("Library package {uri}: {error}")),
}
}
out
}
/// Every entry, resolved against `dependencies` (a session's loaded packages): layout
/// placements first, then graph items and native nodes no layout placed, then graphs of
/// `sbs://` packages no layout placed
pub fn entries(&self, dependencies: &BTreeMap<String, Arc<Package>>) -> Vec<LibraryEntry> {
let mut out = Vec::new();
let mut ids = BTreeSet::new();
let mut placed_graphs = BTreeSet::new();
let mut push = |out: &mut Vec<LibraryEntry>, mut entry: LibraryEntry| {
// Reroute nodes are placed through the shared Graph items entry
if matches!(&entry.item, LibraryItem::Operation { operation } if operation == "passthrough")
|| matches!(&entry.item, LibraryItem::Pattern { kind: PatternNodeKind::Dot })
|| matches!(&entry.item, LibraryItem::Node { def } if def == "dot" && entry.category != "Graph items")
{
return;
}
// The same node may sit in two categories; the id keeps each placement apart
if !ids.insert(entry.id.clone()) {
entry.id = format!("{}@{}", entry.id, entry.category);
if !ids.insert(entry.id.clone()) {
return;
}
}
out.push(entry);
};
for (item, category) in [(LibraryItem::Comment, "Comment"), (LibraryItem::Frame, "Frame"), (LibraryItem::Pin, "Pin")] {
let id = format!("item:{}", category.to_ascii_lowercase());
push(&mut out, entry(id, category, "Graph items", "", item, None));
}
push(&mut out, entry("node:dot".into(), "Dot node", "Graph items", "A reroute point for wires.", LibraryItem::Node { def: "dot".into() }, None));
for placement in &self.placements {
if let LayoutItem::Instance { package, graph, .. } | LayoutItem::FunctionInstance { package, graph } = &placement.item {
placed_graphs.insert((package.clone(), graph.clone()));
}
if let Some(entry) = resolve(placement, dependencies) {
push(&mut out, entry);
}
}
let listed: BTreeSet<String> = out.iter().map(|entry| entry.id.clone()).collect();
for definition in materialcraft_nodes::catalog() {
let id = format!("node:{}", definition.id);
if definition.id == "graph_instance" || listed.contains(&id) {
continue;
}
let item = LibraryItem::Node { def: definition.id.into() };
// Graph inputs and outputs sit with the atomic nodes; Graph items holds annotations and the Dot
let category =
if matches!(definition.id, "input_color" | "input_grayscale" | "input_value" | "output") { "Atomic nodes" } else { definition.category };
push(&mut out, entry(id, definition.label, category, definition.description, item, None));
}
for operation in materialcraft_nodes::function::FUNCTIONS {
let id = format!("function:{}", operation.id);
if operation.id == "passthrough" || listed.contains(&id) {
continue;
}
let category = category_path("Function nodes", Some(operation.category));
push(&mut out, entry(id, operation.label, &category, "", LibraryItem::Operation { operation: operation.id.into() }, None));
}
for kind in PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot) {
let id = format!("pattern:{}", kind.native_id());
push(&mut out, entry(id, kind.label(), "FxMap nodes", "", LibraryItem::Pattern { kind }, None));
}
for (path, package) in dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")) {
for graph in &package.graphs {
let name = graph.sbs_path();
if placed_graphs.contains(&(path.clone(), name.clone())) {
continue;
}
if graph.function.is_some() {
for category in function_categories(graph) {
let placement = LibraryPlacement { category, item: LayoutItem::FunctionInstance { package: path.clone(), graph: name.clone() } };
if let Some(entry) = resolve(&placement, dependencies) {
push(&mut out, entry);
}
}
continue;
}
let placement = if graph.nodes.iter().any(|node| node.def == "output") {
let category = known_category(&graph.attributes.category).unwrap_or_else(|| "Other".into());
LibraryPlacement { category, item: LayoutItem::Instance { package: path.clone(), graph: name, outputs: Vec::new() } }
} else {
continue;
};
if let Some(entry) = resolve(&placement, dependencies) {
push(&mut out, entry);
}
}
}
out
}
}
/// Build an entry with a canvas derived from its item kind.
fn entry(id: String, label: &str, category: &str, description: &str, item: LibraryItem, missing: Option<String>) -> LibraryEntry {
let canvas = item.canvas();
LibraryEntry { id, label: label.into(), category: category.into(), description: description.into(), item, canvas, missing, warning: None }
}
/// A layout item as an entry, its label and availability taken from the loaded packages
fn resolve(placement: &LibraryPlacement, dependencies: &BTreeMap<String, Arc<Package>>) -> Option<LibraryEntry> {
let category = placement.category.as_str();
Some(match &placement.item {
LayoutItem::Atomic { node: Some(def), .. } | LayoutItem::Node(def) => {
let definition = materialcraft_nodes::find(def)?;
entry(format!("node:{def}"), definition.label, category, definition.description, LibraryItem::Node { def: def.to_string() }, None)
}
LayoutItem::Atomic { filter, node: None } => {
let item = LibraryItem::Node { def: filter.clone() };
entry(format!("atomic:{filter}"), &humanize(filter), category, "", item, Some(format!("The atomic `{filter}` node is not in MaterialCraft yet")))
}
LayoutItem::Operation(operation) => {
let definition = materialcraft_nodes::function::FUNCTIONS.iter().find(|definition| definition.id == operation);
let label = definition.map_or_else(|| humanize(operation), |definition| definition.label.to_string());
let missing = definition.is_none().then(|| format!("The `{operation}` function node is not in MaterialCraft yet"));
entry(format!("function:{operation}"), &label, category, "", LibraryItem::Operation { operation: operation.clone() }, missing)
}
LayoutItem::Instance { package, graph, .. } | LayoutItem::FunctionInstance { package, graph } => {
let function = matches!(placement.item, LayoutItem::FunctionInstance { .. });
let source = dependencies.get(package).and_then(|source| source.graph_by_name(graph)).map(|(_, graph)| graph);
let source = source.filter(|source| source.function.is_some() == function);
let label = source.map_or_else(|| humanize(graph), |source| source.display_name().to_string());
let description = source.map(|source| source.attributes.description.clone()).unwrap_or_default();
let missing = source.is_none().then(|| format!("Not in MaterialCraft yet: needs {graph} from {package}"));
let item = if function {
LibraryItem::FunctionInstance { package: package.clone(), graph: graph.clone() }
} else {
LibraryItem::Instance { package: package.clone(), graph: graph.clone() }
};
let mut out = entry(format!("{package}#{graph}"), &label, category, &description, item, missing);
out.category = sub_category(category, graph);
out.warning = source
.and_then(|source| source.function.as_ref())
.filter(|function| function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some()))
.map(|_| "This function uses nodes MaterialCraft does not have yet".to_string());
out
}
// A bitmap anywhere but the 3D view stands for the atomic Bitmap node, not its image
LayoutItem::Bitmap { .. } if !category.starts_with("3D view") => {
let definition = materialcraft_nodes::find("bitmap")?;
entry("node:bitmap".into(), definition.label, category, definition.description, LibraryItem::Node { def: "bitmap".into() }, None)
}
LayoutItem::Bitmap { resource } => {
let name = resource.rsplit('/').next().unwrap_or(resource);
let missing = Some(format!("Not in MaterialCraft yet: the {} image is not bundled", humanize(name)));
entry(format!("bitmap:{resource}"), &humanize(name), category, "", LibraryItem::Bitmap { resource: resource.clone() }, missing)
}
})
}
/// The categories of a layout's frames, and what each places
fn placements(frames: &[materialcraft_formats::sbs::LayoutFrame]) -> Vec<LibraryPlacement> {
let mut out = Vec::new();
for frame in frames {
let native = frame.items.iter().any(|item| matches!(item, LayoutItem::Operation(_)));
let Some(category) = frame_category(&frame.title, frame.function, native) else { continue };
out.extend(frame.items.iter().map(|item| LibraryPlacement { category: category.clone(), item: item.clone() }));
}
out
}
/// Letters and digits, lower case: "Spline &amp; Path Tools", "spline & path tools" and
/// "Spline-and-path tools" differ, but "1 click" and "1-click" match
fn key(text: &str) -> String {
text.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect()
}
/// `Top/Sub` for a frame title. Graph frames read "Top - Sub" (or "Top"); function frames name
/// only the sub-category, under Function nodes when they hold native operations and Functions
/// otherwise
pub fn frame_category(title: &str, function: bool, native_operations: bool) -> Option<String> {
if function {
let top = if native_operations { "Function nodes" } else { "Functions" };
let (_, subs) = CATEGORIES.iter().find(|(name, _)| *name == top)?;
let sub = subs.iter().find(|sub| key(sub) == key(title))?;
return Some(category_path(top, Some(sub)));
}
let (top, sub) = title.split_once(" - ").map_or((title, None), |(top, sub)| (top, Some(sub)));
let top = RENAMED.iter().find(|(old, _)| key(old) == key(top)).map_or(top, |(_, current)| current);
let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?;
match sub {
None => Some((*top).to_string()),
Some(sub) => subs.iter().find(|name| key(name) == key(sub)).map(|sub| category_path(top, Some(sub))),
}
}
/// A category text from a graph's attributes, when it names a library category
fn known_category(text: &str) -> Option<String> {
let mut parts = text.split('/');
let top = parts.next()?;
let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?;
// A sub-category the tree doesn't have names no category ("Functions/colorValues" is a folder)
let sub = match parts.next() {
None => None,
Some(sub) => Some(*subs.iter().find(|name| key(name) == key(sub))?),
};
Some(category_path(top, sub))
}
/// Function tags select filters; explicit category paths and package paths remain fallbacks.
fn function_categories(graph: &materialcraft_core::Graph) -> Vec<String> {
let subcategories = CATEGORIES.iter().find(|(name, _)| *name == "Functions").map_or(&[][..], |(_, subcategories)| *subcategories);
let mut categories = Vec::new();
for tag in graph.attributes.tags.split([',', ';']) {
let tag = key(tag);
let tag = if tag == "easing" { "easings" } else { tag.as_str() };
if let Some(subcategory) = subcategories.iter().find(|subcategory| key(subcategory) == tag) {
let category = category_path("Functions", Some(subcategory));
if !categories.contains(&category) {
categories.push(category);
}
}
}
if categories.is_empty() {
categories.push(known_category(&graph.attributes.category).unwrap_or_else(|| function_category(&graph.sbs_path())));
}
categories
}
/// Join a top-level category with its optional subcategory.
fn category_path(top: &str, sub: Option<&str>) -> String {
match sub {
Some(sub) => format!("{top}/{sub}"),
None => top.to_string(),
}
}
/// The sub-category a graph's name suggests, for layouts that name only a top level
fn sub_category(category: &str, graph: &str) -> String {
if category.contains('/') {
return category.to_string();
}
let name = graph.rsplit('/').next().unwrap_or(graph).to_ascii_lowercase();
SUB_KEYWORDS
.iter()
.find(|(top, _, words)| *top == category && words.iter().any(|word| name.contains(word)))
.map_or_else(|| category.to_string(), |(top, sub, _)| category_path(top, Some(sub)))
}
/// Function graphs whose name decides their Functions sub-category
const FUNCTION_NAMES: &[(&str, &str)] = &[
("Pi", "Constant"),
("2Pi", "Constant"),
("deg_to_rad", "Conversion"),
("Degrees_to_Turn", "Conversion"),
("Curve_Function", "Various"),
("Roughness", "Various"),
];
/// Name prefixes that decide a function graph's sub-category
const FUNCTION_PREFIXES: &[(&str, &str)] = &[("Equality_", "Comparison"), ("NotEqual_", "Comparison")];
/// Library folders (below `Functions/`) and the Functions sub-category of the graphs in them; the
/// first folder that holds the graph wins
const FUNCTION_FOLDERS: &[(&str, &str)] = &[
("colorValues", "Color"),
("Tonemappers", "Color"),
("easings", "Easings"),
("Math/Parity", "Parity"),
("Random", "Random"),
("Ranges", "Conversion"),
("typeConverters", "Conversion"),
("Transforms", "Transformation"),
("switch", "Various"),
("Various", "Various"),
("Cycles", "Various"),
("Math", "Maths"),
];
/// The Functions sub-category of a function graph, from its path in the library package
/// (`Functions/Math/Pi` → `Functions/Constant`); `Functions` when nothing matches
pub fn function_category(path: &str) -> String {
let (folder, name) = path.rsplit_once('/').unwrap_or(("", path));
let folder = folder.strip_prefix("Functions").map_or(folder, |rest| rest.trim_start_matches('/'));
let sub = FUNCTION_NAMES
.iter()
.find(|(known, _)| *known == name)
.or_else(|| FUNCTION_PREFIXES.iter().find(|(prefix, _)| name.starts_with(prefix)))
.or_else(|| FUNCTION_FOLDERS.iter().find(|(known, _)| folder == *known || folder.strip_prefix(known).is_some_and(|rest| rest.starts_with('/'))))
.map(|(_, sub)| *sub);
category_path("Functions", sub)
}
/// A readable label from an SBS identifier: `3D_perlin_noise` → "3D Perlin Noise"
pub fn humanize(identifier: &str) -> String {
const WORDS: &[(&str, &str)] = &[
("2d", "2D"),
("3d", "3D"),
("acescg", "ACEScg"),
("ao", "AO"),
("bnw", "BnW"),
("hdr", "HDR"),
("hdri", "HDRI"),
("hq", "HQ"),
("id", "ID"),
("mg", "MG"),
("pbr", "PBR"),
("rgb", "RGB"),
("rgba", "RGBA"),
("rgb-a", "RGB-A"),
("srgb", "sRGB"),
("uv", "UV"),
];
let name = identifier.rsplit('/').next().unwrap_or(identifier);
name.split(['_', ' '])
.filter(|word| !word.is_empty())
.map(|word| {
let lower = word.to_ascii_lowercase();
if let Some((_, known)) = WORDS.iter().find(|(from, _)| *from == lower) {
return (*known).to_string();
}
let mut chars = word.chars();
chars.next().map_or_else(String::new, |first| first.to_uppercase().chain(chars).collect())
})
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(test)]
#[path = "node_library.test.rs"]
mod tests;
+173
View File
@@ -0,0 +1,173 @@
use super::*;
use materialcraft_core::Graph;
#[path = "../tests/support/node_library.rs"]
mod fixture;
/// Category aliases and frame kinds resolve only to recognized categories.
#[test]
fn frame_titles_map_to_library_categories() {
assert_eq!(frame_category("Texture Generators - Noises", false, false).as_deref(), Some("Texture generators/Noises"));
assert_eq!(frame_category("Spline & Path tools - Path tools", false, false).as_deref(), Some("Spline & Path tools/Path tools"));
assert_eq!(frame_category("Material Filters - 1 click", false, false).as_deref(), Some("Material filters/1-click"));
assert_eq!(frame_category("Mesh-based generators - Weathering", false, false).as_deref(), Some("Mesh-based generators/Weathering"));
assert_eq!(frame_category("PBR Materials", false, false).as_deref(), Some("PBR materials"));
assert_eq!(frame_category("Atomic Nodes", false, false).as_deref(), Some("Atomic nodes"));
// The category MaterialCraft renamed still reads from older layouts
assert_eq!(frame_category("SDF functions - Primitives", false, false).as_deref(), Some("MCF functions/Primitives"));
assert_eq!(frame_category("Functions Inside", false, false), None);
assert_eq!(frame_category("Filters - Nowhere", false, false), None);
assert_eq!(frame_category("Comparison", true, true).as_deref(), Some("Function nodes/Comparison"));
assert_eq!(frame_category("Comparison", true, false).as_deref(), Some("Functions/Comparison"));
assert_eq!(frame_category("Unknown", true, true), None);
}
/// Identifier labels preserve recognized acronyms and omit empty words.
#[test]
fn identifiers_read_as_labels() {
assert_eq!(humanize("3D_perlin_noise"), "3D Perlin Noise");
assert_eq!(humanize("bnw_spots_1"), "BnW Spots 1");
assert_eq!(humanize("rgb-a_merge"), "RGB-A Merge");
assert_eq!(humanize("Functions/Math/acescg_to_srgb"), "ACEScg To sRGB");
assert_eq!(humanize("__"), "");
}
/// Function categories use exact path segments and known name overrides.
#[test]
fn functions_sort_into_sub_categories_by_folder_and_name() {
assert_eq!(function_category("Functions/Math/Pi"), "Functions/Constant");
assert_eq!(function_category("Functions/Math/Equality_Float2"), "Functions/Comparison");
assert_eq!(function_category("Functions/Math/Parity/EvenCount"), "Functions/Parity");
assert_eq!(function_category("Functions/Math/Trigo/acos"), "Functions/Maths");
assert_eq!(function_category("Functions/Math/Trigo/deg_to_rad"), "Functions/Conversion");
assert_eq!(function_category("Functions/easings/sine/ease_in_sine"), "Functions/Easings");
assert_eq!(function_category("Functions/switch/Float2/switch_float2_4_inputs"), "Functions/Various");
assert_eq!(function_category("Functions/Tonemappers/tonemap_ACES"), "Functions/Color");
assert_eq!(function_category("Functions/Mathematics/x"), "Functions", "a folder name must match whole");
assert_eq!(function_category("Loose"), "Functions");
}
/// The isolated bundled catalog has unique entries in recognized categories.
#[test]
fn the_bundled_library_fills_the_tree_with_what_materialcraft_has() {
let library = fixture::library();
assert!(library.layouts.is_empty());
assert!(library.packages.contains_key("sbs://functions.sbs"));
let entries = library.entries(&library.packages);
let ids: BTreeSet<_> = entries.iter().map(|entry| entry.id.as_str()).collect();
assert_eq!(ids.len(), entries.len(), "ids are unique");
assert!(entries.iter().all(|entry| entry.missing.is_none()), "everything listed can be added");
let known = |category: &str| {
let mut parts = category.split('/');
let top = parts.next().unwrap_or("");
CATEGORIES.iter().any(|(name, subs)| *name == top && parts.next().is_none_or(|sub| subs.contains(&sub)))
};
for entry in &entries {
assert!(known(&entry.category), "{} sits in unknown category {}", entry.id, entry.category);
}
let count = |category: &str| entries.iter().filter(|entry| entry.category == category).count();
let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap_or_else(|| panic!("no entry {id}"));
for top in ["Function nodes", "Functions"] {
let (_, subs) = CATEGORIES.iter().find(|(name, _)| *name == top).unwrap();
for sub in *subs {
assert!(count(&format!("{top}/{sub}")) > 0, "{top}/{sub} is empty");
}
}
// Every bundled function has a sub-category
let functions = library.packages["sbs://functions.sbs"].graphs.iter().filter(|graph| graph.function.is_some()).count();
assert_eq!(entries.iter().filter(|entry| entry.category.starts_with("Functions/")).count(), functions);
assert_eq!(count("Functions"), 0);
assert_eq!(find("sbs://functions.sbs#Functions/Tonemappers/tonemap_ACES").category, "Functions/Color");
assert_eq!(
entries.iter().filter(|entry| entry.category == "Graph items").map(|entry| entry.label.as_str()).collect::<Vec<_>>(),
["Comment", "Frame", "Pin", "Dot node"]
);
for id in ["node:blur", "node:bitmap", "node:output", "node:input_color", "node:input_value"] {
assert_eq!(find(id).category, "Atomic nodes", "{id}");
}
assert_eq!(find("function:add").category, "Function nodes/Operator");
assert_eq!(find("pattern:paramset").category, "FxMap nodes");
let pi = find("sbs://functions.sbs#Functions/Math/Pi");
assert_eq!((pi.label.as_str(), pi.category.as_str()), ("Pi", "Functions/Constant"));
assert_eq!(find("sbs://functions.sbs#Functions/Math/Equality_Float2").category, "Functions/Comparison");
}
/// A layout that places a library node MaterialCraft doesn't have yet, a function and a sub-category
/// the PBR keywords decide
const LAYOUT: &str = r#"<package><dependencies>
<dependency><filename v="sbs://3d_perlin_noise.sbs"/><uid v="2"/></dependency>
<dependency><filename v="sbs://materials/bricks_001.sbs"/><uid v="3"/></dependency></dependencies>
<content><graph><identifier v="Layout"/><compNodes>
<compNode><uid v="10"/><GUILayout><gpos v="20 40 0"/></GUILayout><compImplementation><compInstance><path v="pkg:///3D_perlin_noise?dependency=2"/></compInstance></compImplementation></compNode>
<compNode><uid v="11"/><GUILayout><gpos v="220 40 0"/></GUILayout><compImplementation><compInstance><path v="pkg:///bricks_001?dependency=3"/></compInstance></compImplementation></compNode>
</compNodes><GUIObjects>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="160 200"/></GUILayout><title v="Texture Generators - Noises"/></GUIObject>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="200 0 0"/><size v="160 200"/></GUILayout><title v="PBR Materials"/></GUIObject>
</GUIObjects></graph></content></package>"#;
/// A missing layout entry becomes available when its package is supplied.
#[test]
fn a_layout_lists_what_it_places_and_a_library_package_makes_it_available() {
let frames = materialcraft_formats::sbs::read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap();
let library = NodeLibrary { placements: placements(&frames), ..Default::default() };
let entries = library.entries(&BTreeMap::new());
let perlin = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#3D_perlin_noise").unwrap();
assert_eq!((perlin.label.as_str(), perlin.category.as_str()), ("3D Perlin Noise", "Texture generators/Noises"));
assert!(perlin.missing.is_some(), "a placed node whose package is absent is listed but not addable");
let bricks = entries.iter().find(|entry| entry.id == "sbs://materials/bricks_001.sbs#bricks_001").unwrap();
assert_eq!(bricks.category, "PBR materials/Bricks");
let mut graph = Graph::new("3D_perlin_noise");
graph.add_node("uniform", [0.0; 2]);
graph.add_node("output", [200.0, 0.0]);
let mut package = Package::new("3d_perlin_noise");
package.graphs.push(graph.clone());
graph.name = "Loose".into();
graph.attributes.category = "Filters/Blurs".into();
package.graphs.push(graph);
let dependencies = BTreeMap::from([("sbs://3d_perlin_noise.sbs".to_string(), Arc::new(package))]);
let entries = library.entries(&dependencies);
let perlin = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#3D_perlin_noise").unwrap();
assert!(perlin.missing.is_none());
assert_eq!(perlin.category, "Texture generators/Noises");
let loose = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#Loose").unwrap();
assert_eq!((loose.category.as_str(), loose.canvas), ("Filters/Blurs", LibraryCanvas::Material));
}
/// Invalid library files produce warnings while native entries remain usable.
#[test]
fn unreadable_library_files_warn_instead_of_failing() {
let library = NodeLibrary::load(&["sbs://does_not_exist.sbs".into(), "sbs://../escape.sbs".into()]);
assert!(library.packages.is_empty() && library.layouts.is_empty());
assert_eq!(library.warnings.len(), 2);
let entries = library.entries(&BTreeMap::new());
assert!(entries.iter().any(|entry| entry.id == "node:blur" && entry.category == "Atomic nodes"));
assert!(entries.iter().any(|entry| entry.id == "function:add" && entry.category == "Function nodes/Operator"));
}
/// Classification tags take precedence over package folders and support multiple placements.
#[test]
fn function_tags_choose_library_filters_before_path_fallbacks() {
let mut package = Package::new("Functions");
for (name, category, tags) in [("Pi", "Function", "Maths"), ("Tagged", "", "Comparison; Easing"), ("Fallback", "", "Unknown")] {
let mut graph = Graph::new(name);
graph.folder = "Functions/Math".into();
graph.function = Some(Default::default());
graph.attributes.category = category.into();
graph.attributes.tags = tags.into();
package.graphs.push(graph);
}
let dependencies = BTreeMap::from([("sbs://classification.sbs".to_string(), Arc::new(package))]);
let entries = NodeLibrary::default().entries(&dependencies);
let categories = |name: &str| entries.iter().filter(|entry| entry.label == name).map(|entry| entry.category.as_str()).collect::<Vec<_>>();
assert_eq!(categories("Pi"), ["Functions/Maths"]);
assert_eq!(categories("Tagged"), ["Functions/Comparison", "Functions/Easings"]);
assert_eq!(categories("Fallback"), ["Functions/Maths"]);
}
@@ -0,0 +1,11 @@
use serde::Serialize;
/// The graph kind that can take an entry
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum LibraryCanvas {
Any,
Material,
Function,
Pattern,
}
@@ -0,0 +1,22 @@
use super::{LibraryCanvas, LibraryItem};
use serde::Serialize;
/// One selectable library entry and its availability on a destination canvas.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct LibraryEntry {
/// Stable id, e.g. `node:blur`, `function:add`, `sbs://functions.sbs#Functions/Math/Pi`
pub id: String,
pub label: String,
/// `Top` or `Top/Sub`, from [`super::CATEGORIES`]
pub category: String,
pub description: String,
#[serde(flatten)]
pub item: LibraryItem,
pub canvas: LibraryCanvas,
/// Why the entry can't be added yet (the package it needs is not in MaterialCraft)
#[serde(skip_serializing_if = "Option::is_none")]
pub missing: Option<String>,
/// It can be added, but is incomplete (it uses operations MaterialCraft lacks)
#[serde(skip_serializing_if = "Option::is_none")]
pub warning: Option<String>,
}
@@ -0,0 +1,51 @@
use super::LibraryCanvas;
use materialcraft_core::PatternNodeKind;
use serde::Serialize;
/// What adding an entry puts in the graph
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum LibraryItem {
/// A native node, by catalog id
Node {
def: String,
},
Comment,
Frame,
Pin,
/// An instance of a graph from a library package
Instance {
package: String,
graph: String,
},
/// A native function operation
Operation {
operation: String,
},
/// An instance of a function graph from a library package
FunctionInstance {
package: String,
graph: String,
},
/// An FX-Map node
Pattern {
kind: PatternNodeKind,
},
/// An environment image
Bitmap {
resource: String,
},
}
impl LibraryItem {
/// Return the canvas that accepts this item.
pub fn canvas(&self) -> LibraryCanvas {
match self {
Self::Comment | Self::Frame | Self::Pin => LibraryCanvas::Any,
Self::Node { def } if def == "dot" => LibraryCanvas::Any,
Self::Operation { .. } | Self::FunctionInstance { .. } => LibraryCanvas::Function,
Self::Pattern { .. } => LibraryCanvas::Pattern,
_ => LibraryCanvas::Material,
}
}
}
@@ -0,0 +1,8 @@
use materialcraft_formats::sbs::LayoutItem;
/// A layout placement, before it is resolved against the loaded packages
#[derive(Clone, Debug)]
pub(super) struct LibraryPlacement {
pub(super) category: String,
pub(super) item: LayoutItem,
}
+194
View File
@@ -0,0 +1,194 @@
//! Library commands: list the categorized library, add an entry to the open graph, and read the
//! library folder again
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, point, strp};
use crate::node_library::{CATEGORIES, LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary};
use crate::{FunctionGraphTarget, Result, Session, cmd};
use serde_json::{Value, json};
use std::collections::BTreeSet;
const ADD: &str = "library.add";
/// Register catalog queries, insertion and library reload commands.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"library.tree",
"Library categories",
[],
None,
"{filter?, category? (Top or Top/Sub), canvas? (material|function|pattern)} the library tree and its entries: id, label, category, type, canvas, missing (not addable yet), warning",
always,
tree
),
cmd!(
"library.add",
"Add library entry",
[],
None,
"{entry (id from library.tree), at? [x, y], snapToGrid?, function?: FunctionGraphTarget, pattern?: owner node id} adds a library entry to the open graph (function entries to a Function canvas)",
has_graph,
add
),
cmd!("library.reload", "Reload library", [], None, "{} reads the SBS library folder again", always, reload),
]
}
impl Session {
/// The library's entries, resolved against this session's loaded packages
pub fn library_entries(&self) -> Vec<LibraryEntry> {
self.library.entries(&self.pkg.dependencies)
}
}
/// List entries that match the requested text, category and destination canvas.
fn tree(session: &mut Session, parameters: &Value) -> Result<Value> {
let filter = strp(parameters, "filter").unwrap_or("").to_lowercase();
let category = strp(parameters, "category").unwrap_or("");
let canvas = match strp(parameters, "canvas") {
None => None,
Some("material") => Some(LibraryCanvas::Material),
Some("function") => Some(LibraryCanvas::Function),
Some("pattern") => Some(LibraryCanvas::Pattern),
Some(other) => return Err(bad("library.tree", format!("unknown canvas `{other}`: material, function or pattern"))),
};
let entries: Vec<_> = session
.library_entries()
.into_iter()
.filter(|entry| category.is_empty() || entry.category == category || entry.category.starts_with(&format!("{category}/")))
.filter(|entry| canvas.is_none_or(|canvas| entry.canvas == LibraryCanvas::Any || entry.canvas == canvas))
.filter(|entry| filter.is_empty() || entry.label.to_lowercase().contains(&filter) || entry.id.to_lowercase().contains(&filter))
.collect();
let categories: Vec<_> = CATEGORIES.iter().map(|(name, subcategories)| json!({"name": name, "subcategories": subcategories})).collect();
Ok(json!({"categories": categories, "layouts": session.library.layouts, "entries": entries}))
}
/// Validate an entry and dispatch its insertion through the destination graph command.
fn add(session: &mut Session, parameters: &Value) -> Result<Value> {
let id = strp(parameters, "entry").ok_or_else(|| bad(ADD, "`entry` is required (an id from library.tree)"))?;
let entry = session.library_entries().into_iter().find(|entry| entry.id == id).ok_or_else(|| bad(ADD, format!("no library entry `{id}`")))?;
if let Some(missing) = &entry.missing {
return Err(bad(ADD, format!("{}: {missing}", entry.label)));
}
let at = point(parameters, "at").unwrap_or([0.0, 0.0]);
let snap = boolp(parameters, "snapToGrid").unwrap_or(false);
let function_graph = session.graph()?.function.is_some();
let target = parameters.get("function").cloned().filter(|target| !target.is_null());
if entry.canvas == LibraryCanvas::Any {
let destination = crate::AnnotationTarget::resolve(session, parameters)?;
let mut arguments = destination.parameters();
arguments["at"] = json!(at);
let command = match &entry.item {
LibraryItem::Comment => "graph.comment.add",
LibraryItem::Frame => {
arguments["rect"] = json!([at[0], at[1], 400.0, 260.0]);
"graph.frame.add"
}
LibraryItem::Pin => "graph.pin.add",
LibraryItem::Node { def } if def == "dot" => match crate::SelectionTarget::resolve(session, parameters)? {
Some(crate::SelectionTarget::Function(target)) => {
arguments = json!({"target": target, "edit": {"action": "add", "operation": "passthrough", "at": at, "snap": snap}});
"graph.function.edit"
}
Some(crate::SelectionTarget::Pattern(owner)) => {
arguments = json!({"id": owner.0, "edit": {"action": "add", "kind": "passthrough", "at": at, "snap": snap}});
"graph.pattern.edit"
}
None => {
arguments = json!({"def": "dot", "at": at, "snapToGrid": snap});
"graph.node.add"
}
},
_ => return Err(bad(ADD, "unknown graph item")),
};
let result = crate::execute(session, command, &arguments)?;
if matches!(&entry.item, LibraryItem::Node { .. }) {
session.annotation_selection = None;
}
return Ok(json!({"entry": entry.id, "result": result}));
}
if entry.canvas == LibraryCanvas::Function {
let target = match target {
Some(target) => serde_json::from_value::<FunctionGraphTarget>(target).map_err(|error| bad(ADD, error.to_string()))?,
None if function_graph => FunctionGraphTarget::Graph,
None => return Err(bad(ADD, format!("{} goes in a Function canvas: open a Function Graph or pass `function`", entry.label))),
};
let target = serde_json::to_value(target).map_err(|error| bad(ADD, error.to_string()))?;
let result = match &entry.item {
LibraryItem::Operation { operation } => crate::execute(
session,
"graph.function.edit",
&json!({"target": target, "edit": {"action": "add", "operation": operation, "at": at, "snap": snap}}),
)?,
LibraryItem::FunctionInstance { package, graph } => {
crate::execute(session, "library.function.add", &json!({"package": package, "graph": graph, "function": target, "at": at, "snapToGrid": snap}))?
}
_ => return Err(bad(ADD, "unexpected function entry")),
};
return Ok(json!({"entry": entry.id, "result": result}));
}
if entry.canvas == LibraryCanvas::Pattern {
return Err(bad(ADD, format!("{} is an FX-Map node: add it with graph.pattern.edit", entry.label)));
}
if function_graph || target.is_some() || parameters.get("pattern").is_some() {
return Err(bad(ADD, format!("{} goes in a material graph, not a Function Graph", entry.label)));
}
let result = match &entry.item {
LibraryItem::Node { def } => crate::execute(session, "graph.node.add", &json!({"def": def, "at": at, "snapToGrid": snap}))?,
LibraryItem::Comment => crate::execute(session, "graph.comment.add", &json!({"at": at}))?,
LibraryItem::Frame => crate::execute(session, "graph.frame.add", &json!({"rect": [at[0], at[1], 400.0, 260.0]}))?,
LibraryItem::Pin => crate::execute(session, "graph.pin.add", &json!({"at": at}))?,
LibraryItem::Instance { package, graph } => {
crate::execute(session, "graph.instance.add", &json!({"package": package, "graph": graph, "at": at, "snapToGrid": snap}))?
}
_ => return Err(bad(ADD, format!("{} can't be added to a graph", entry.label))),
};
Ok(json!({"entry": entry.id, "result": result}))
}
/// Replace library-owned snapshots while retaining explicit user dependencies.
fn replace_library(session: &mut Session, library: std::sync::Arc<NodeLibrary>) {
let mut changed = BTreeSet::new();
session.library_sources.retain(|path, owned| session.linked_sources.get(path).is_some_and(|source| std::sync::Arc::ptr_eq(source, owned)));
for path in session.library_sources.keys() {
if !library.packages.contains_key(path) {
session.linked_sources.remove(path);
changed.insert(path.clone());
}
}
session.library_sources.retain(|path, _| library.packages.contains_key(path));
for (path, package) in &library.packages {
if session.linked_sources.contains_key(path) && !session.library_sources.contains_key(path) {
continue;
}
if session.linked_sources.get(path).is_none_or(|current| current.as_ref() != package.as_ref()) {
session.linked_sources.insert(path.clone(), package.clone());
changed.insert(path.clone());
}
if let Some(source) = session.linked_sources.get(path) {
session.library_sources.insert(path.clone(), source.clone());
}
}
for warning in &library.warnings {
session.warn(warning.clone());
}
session.library = library;
session.refresh_links_from(changed);
}
/// Reload the installed library and report the catalog visible to this session.
fn reload(session: &mut Session, _: &Value) -> Result<Value> {
replace_library(session, NodeLibrary::reload());
let entries = session.library_entries();
Ok(json!({"entries": entries.len(), "available": entries.iter().filter(|entry| entry.missing.is_none()).count(), "layouts": session.library.layouts}))
}
#[cfg(test)]
#[path = "node_library_commands.test.rs"]
mod tests;
@@ -0,0 +1,46 @@
use super::*;
use materialcraft_core::{FunctionGraph, Graph, Package};
use std::sync::Arc;
/// Build a small library with one reusable function and no filesystem dependencies.
fn library(name: &str) -> Arc<NodeLibrary> {
let mut function = Graph::new(name);
function.function = Some(FunctionGraph::default());
let mut package = Package::new("Custom library");
package.graphs.push(function);
let mut library = NodeLibrary::default();
library.packages.insert("sbs://custom.sbs".into(), Arc::new(package));
Arc::new(library)
}
/// Reload replaces owned sources and removes sources no longer installed.
#[test]
fn reload_updates_and_removes_library_owned_sources() {
let mut session = Session::with_library(Package::new("Project"), library("Before"));
replace_library(&mut session, library("After"));
assert!(session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#After"));
assert!(!session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#Before"));
replace_library(&mut session, Arc::new(NodeLibrary::default()));
assert!(!session.pkg.dependencies.contains_key("sbs://custom.sbs"));
assert!(!session.library_entries().iter().any(|entry| entry.id.starts_with("sbs://custom.sbs#")));
assert!(!session.modified);
}
/// Opening a package transfers dependency ownership even after initial session construction.
#[test]
fn reload_keeps_dependencies_supplied_by_later_opened_packages() {
let mut session = Session::with_library(Package::new("First"), library("Original"));
let custom = library("User_function");
let mut package = Package::new("Second");
package.dependencies = custom.packages.clone();
session.open_package(package, None).unwrap();
replace_library(&mut session, library("Replacement"));
assert!(session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#User_function"));
assert!(!session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#Replacement"));
}
+5
View File
@@ -10,6 +10,7 @@ pub struct OpenDocument {
pub modified: bool,
selection: Vec<NodeId>,
annotation_selection: Option<AnnotationSelection>,
annotation_target: crate::AnnotationTarget,
view2d: View2d,
view3d: View3d,
material_preview: MaterialPreview,
@@ -26,6 +27,7 @@ impl OpenDocument {
graph: self.graph,
selection: self.selection.clone(),
annotation_selection: self.annotation_selection,
annotation_target: self.annotation_target.clone(),
material_preview: self.material_preview.clone(),
label: label.into(),
modified: self.modified,
@@ -40,6 +42,7 @@ impl OpenDocument {
self.graph = snapshot.graph.min(self.pkg.graphs.len().saturating_sub(1));
self.selection = snapshot.selection;
self.annotation_selection = snapshot.annotation_selection;
self.annotation_target = snapshot.annotation_target;
self.material_preview = snapshot.material_preview;
self.modified = snapshot.modified;
}
@@ -90,6 +93,7 @@ impl OpenDocument {
modified: false,
selection: Vec::new(),
annotation_selection: None,
annotation_target: Default::default(),
view2d: View2d::default(),
view3d: View3d::default(),
load_warnings: Vec::new(),
@@ -114,6 +118,7 @@ impl OpenDocument {
modified,
selection,
annotation_selection,
annotation_target,
view2d,
view3d,
material_preview,
@@ -0,0 +1,163 @@
use crate::{
Result, Session, cmd,
commands::{CommandSpec, bad, boolp, has_graph, node_param, strp},
parameter_target::ParameterTarget,
};
use materialcraft_core::{BaseParameters, FunctionGraph, ValueType};
use serde_json::{Value as Json, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.node.function",
"Set parameter function",
[],
None,
"{id?, param, base?: false, mode?: empty|constant, value?: constant value, function?: {nodes, output}, remove?: false}",
has_graph,
set_function
),
cmd!(
"graph.node.function.edit",
"Edit parameter function",
[],
None,
"{id?, param, base?: false} resolves the parameter function to open",
has_graph,
edit
),
cmd!("graph.node.reset", "Reset parameters", [], None, "{id?, param? (default: all specific parameters), base?: false}", has_graph, reset),
cmd!("graph.node.bind", "Bind parameter to input", [], None, "{id?, param, base?: false, input: exposed id or null}", has_graph, bind),
cmd!(
"graph.node.parameterInfo",
"Inspect parameter",
[],
None,
"{id?, param, base?: false} returns the parameter's type, driver and inheritance",
has_graph,
info
),
]
}
fn set_function(session: &mut Session, parameters: &Json) -> Result<Json> {
let command = "graph.node.function";
let target = ParameterTarget::resolve(session, command, parameters)?;
let descriptor = target.descriptor(session, command)?;
if !descriptor.supports_function {
return Err(bad(command, "this parameter does not support a function"));
}
if boolp(parameters, "remove") == Some(true) {
return session.edit("Remove parameter function", |session| {
target.clear(session.graph_mut()?, false)?;
Ok(Json::Null)
});
}
let mode = strp(parameters, "mode");
if mode.is_some_and(|mode| !matches!(mode, "empty" | "constant")) {
return Err(bad(command, "mode must be empty or constant"));
}
let function = if let Some(function) = parameters.get("function").filter(|value| !value.is_null()) {
serde_json::from_value::<FunctionGraph>(function.clone()).map_err(|error| bad(command, error.to_string()))?
} else if mode == Some("empty") {
FunctionGraph::default()
} else if mode.is_none()
&& let Some(function) = target.function(session.graph()?)
{
function.clone()
} else {
let value = if let Some(value) = parameters.get("value").filter(|value| !value.is_null()) {
descriptor.default.coerce_json(value).ok_or_else(|| bad(command, "incorrect constant value type"))?
} else {
target.current_value(session, &descriptor)?
};
FunctionGraph::constant(value)
};
crate::graph_validation::function(&function).map_err(|error| bad(command, error))?;
session.edit("Set parameter function", |session| {
target.set_function(session.graph_mut()?, function)?;
Ok(json!({"target": target.function_target()}))
})
}
fn edit(session: &mut Session, parameters: &Json) -> Result<Json> {
let command = "graph.node.function.edit";
let target = ParameterTarget::resolve(session, command, parameters)?;
target.descriptor(session, command)?;
target.function(session.graph()?).ok_or_else(|| bad(command, "parameter has no function"))?;
Ok(json!({"target": target.function_target()}))
}
fn reset(session: &mut Session, parameters: &Json) -> Result<Json> {
let node = node_param(session, "graph.node.reset", parameters, "id")?;
let target = parameters.get("param").map(|_| ParameterTarget::resolve(session, "graph.node.reset", parameters)).transpose()?;
if let Some(target) = &target {
target.descriptor(session, "graph.node.reset")?;
}
session.edit("Reset parameters", |session| {
if let Some(target) = target {
target.clear(session.graph_mut()?, true)?;
} else {
let node = session.graph_mut()?.node_mut(node)?;
if boolp(parameters, "base") == Some(true) {
node.base = BaseParameters::default();
} else {
node.params.retain(|parameter, _| matches!(parameter.as_str(), "graph" | "identifier"));
node.bindings.clear();
node.functions.clear();
}
}
Ok(Json::Null)
})
}
fn bind(session: &mut Session, parameters: &Json) -> Result<Json> {
let command = "graph.node.bind";
let target = ParameterTarget::resolve(session, command, parameters)?;
let descriptor = target.descriptor(session, command)?;
let function = match parameters.get("input") {
Some(Json::Null) => None,
Some(Json::String(identifier)) => {
let input = session.graph()?.exposed.iter().find(|input| &input.id == identifier).ok_or_else(|| bad(command, "no such exposed input"))?;
let expected =
ValueType::of(&descriptor.default).filter(|_| descriptor.supports_function).ok_or_else(|| bad(command, "this parameter cannot be exposed"))?;
if ValueType::of(&input.default) != Some(expected) {
return Err(bad(command, format!("input must be {}", expected.label())));
}
Some(FunctionGraph::input(identifier, expected))
}
_ => return Err(bad(command, "input must be an exposed identifier or null")),
};
session.edit("Bind parameter", |session| {
match function {
Some(function) => target.set_function(session.graph_mut()?, function)?,
None => target.clear(session.graph_mut()?, false)?,
}
Ok(Json::Null)
})
}
fn info(session: &mut Session, parameters: &Json) -> Result<Json> {
let command = "graph.node.parameterInfo";
let target = ParameterTarget::resolve(session, command, parameters)?;
let descriptor = target.descriptor(session, command)?;
let graph = session.graph()?;
let function = target.function(graph);
let inheritance = match target {
ParameterTarget::Base { node, parameter } => Some(parameter.inheritance(&graph.node(node)?.base)),
_ => None,
};
let current = target.current_value(session, &descriptor);
Ok(json!({"target": target.function_target(), "label": descriptor.label, "default": descriptor.default,
"expectedType": ValueType::of(&descriptor.default), "supportsFunction": descriptor.supports_function,
"value": current.as_ref().ok(), "error": current.as_ref().err().map(ToString::to_string), "function": function, "input": function.and_then(FunctionGraph::input_identifier),
"inheritance": inheritance, "warnings": function.map(|function| crate::function_inspection::warnings_for(graph, &target.function_target(), function)).unwrap_or_default()}))
}
+136
View File
@@ -0,0 +1,136 @@
use crate::{
FunctionGraphTarget, Result, Session,
commands::{bad, node_param, strp},
};
use materialcraft_core::{BaseParameter, BaseParameters, FunctionGraph, Graph, NodeId, Value};
use materialcraft_nodes::ParameterDescriptor;
use serde_json::Value as Json;
#[derive(Clone, Debug)]
pub(crate) enum ParameterTarget {
Base { node: NodeId, parameter: BaseParameter },
Specific { node: NodeId, parameter: String },
}
impl ParameterTarget {
pub(crate) fn resolve(session: &Session, command: &str, parameters: &Json) -> Result<Self> {
let node = node_param(session, command, parameters, "id")?;
let parameter = strp(parameters, "param").ok_or_else(|| bad(command, "param is required"))?;
if parameters.get("base").and_then(Json::as_bool) == Some(true) {
let parameter = BaseParameter::named(parameter).ok_or_else(|| bad(command, "unknown base parameter"))?;
Ok(Self::Base { node, parameter })
} else {
Ok(Self::Specific { node, parameter: parameter.into() })
}
}
pub(crate) fn node(&self) -> NodeId {
match self {
Self::Base { node, .. } | Self::Specific { node, .. } => *node,
}
}
pub(crate) fn identifier(&self) -> &str {
match self {
Self::Base { parameter, .. } => parameter.identifier(),
Self::Specific { parameter, .. } => parameter,
}
}
pub(crate) fn descriptor(&self, session: &Session, command: &str) -> Result<ParameterDescriptor> {
let node = session.graph()?.node(self.node())?;
match self {
Self::Base { parameter, .. } => Ok(ParameterDescriptor::base(*parameter)),
Self::Specific { parameter, .. } => {
ParameterDescriptor::for_node(&session.pkg, node, parameter).ok_or_else(|| bad(command, format!("{} has no parameter `{parameter}`", node.def)))
}
}
}
pub(crate) fn function<'a>(&self, graph: &'a Graph) -> Option<&'a FunctionGraph> {
let node = graph.node(self.node()).ok()?;
match self {
Self::Base { parameter, .. } => node.base.functions.get(parameter),
Self::Specific { parameter, .. } => node.functions.get(parameter),
}
}
pub(crate) fn current_value(&self, session: &Session, descriptor: &ParameterDescriptor) -> Result<Value> {
let graph = session.graph()?;
let node = graph.node(self.node())?;
if self.function(graph).is_some() {
let decoder = session.resource_decoder();
let mut options = materialcraft_eval::Options::new(&decoder);
options.environment = session.environment;
options.max_size = session.preview_size;
options.only = Some(vec![self.node()]);
let cooked = materialcraft_eval::cook(&session.pkg, session.graph, &options, &session.cache);
let result = cooked.nodes.get(&self.node()).ok_or_else(|| bad("graph.node.function", "parameter owner was not evaluated"))?;
if let Some(error) = &result.error {
return Err(bad("graph.node.function", error.clone()));
}
let value = match self {
Self::Base { parameter, .. } => result.base_values.get(parameter),
Self::Specific { parameter, .. } => result.parameters.get(parameter),
};
return value.cloned().ok_or_else(|| bad("graph.node.function", "parameter function did not produce a value"));
}
Ok(match self {
Self::Base { parameter, .. } => parameter.value(&node.base),
Self::Specific { parameter, .. } => node
.bindings
.get(parameter)
.and_then(|input| graph.input_value(input))
.or_else(|| node.params.get(parameter))
.cloned()
.unwrap_or_else(|| descriptor.default.clone()),
})
}
pub(crate) fn set_function(&self, graph: &mut Graph, function: FunctionGraph) -> Result<()> {
let node = graph.node_mut(self.node())?;
match self {
Self::Base { parameter, .. } => {
node.base.functions.insert(*parameter, function);
}
Self::Specific { parameter, .. } => {
node.bindings.remove(parameter);
node.functions.insert(parameter.clone(), function);
}
}
Ok(())
}
pub(crate) fn clear(&self, graph: &mut Graph, reset: bool) -> Result<()> {
let node = graph.node_mut(self.node())?;
match self {
Self::Base { parameter, .. } => {
node.base.functions.remove(parameter);
if reset {
let defaults = BaseParameters::default();
parameter.set_value(&mut node.base, &parameter.value(&defaults)).map_err(|error| bad("graph.node.reset", error))?;
parameter.set_inheritance(&mut node.base, parameter.inheritance(&defaults));
}
}
Self::Specific { parameter, .. } => {
node.functions.remove(parameter);
node.bindings.remove(parameter);
if reset {
node.params.remove(parameter);
}
}
}
Ok(())
}
pub(crate) fn function_target(&self) -> FunctionGraphTarget {
match self {
Self::Base { node, parameter } => FunctionGraphTarget::Base { node: *node, parameter: *parameter },
Self::Specific { node, parameter } => FunctionGraphTarget::Dynamic { node: *node, parameter: parameter.clone() },
}
}
}
+65
View File
@@ -0,0 +1,65 @@
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
use crate::{AnnotationSelection, AnnotationTarget, Result, Session, cmd};
use materialcraft_core::Pin;
use serde_json::{Value, json};
/// Register navigation pin creation, description/position editing and deletion.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, description?, at? [x, y], function?, pattern?}", has_graph, add),
cmd!("graph.pin.edit", "Edit Navigation pin", [], None, "{id, description?, at? [x, y], function?, pattern?}", has_graph, edit),
cmd!("graph.pin.delete", "Delete pin", [], None, "{id, function?, pattern?}", has_graph, delete),
]
}
fn add(session: &mut Session, parameters: &Value) -> Result<Value> {
let target = AnnotationTarget::resolve(session, parameters)?;
let mut items = target.items(session)?;
let id = target.next_id(session, &items)?;
let name =
strp(parameters, "description").or_else(|| strp(parameters, "name")).map(str::to_string).unwrap_or_else(|| format!("Pin {}", items.pins.len() + 1));
let pos = point(parameters, "at").unwrap_or([0.0; 2]);
items.pins.push(Pin { id, name, pos });
session.edit("Add pin", |session| {
target.replace(session, items)?;
session.selection.clear();
session.annotation_target = target;
session.annotation_selection = Some(AnnotationSelection::Pin(id));
Ok(json!({"id": id}))
})
}
fn edit(session: &mut Session, parameters: &Value) -> Result<Value> {
let target = AnnotationTarget::resolve(session, parameters)?;
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.edit", "`id` is required"))?;
let mut items = target.items(session)?;
let pin = items.pins.iter_mut().find(|pin| pin.id == id).ok_or_else(|| bad("graph.pin.edit", format!("no pin {id}")))?;
if let Some(description) = strp(parameters, "description").or_else(|| strp(parameters, "name")) {
pin.name = description.into();
}
if let Some(position) = point(parameters, "at") {
pin.pos = position;
}
session.edit_merged(&format!("pin:{target:?}:{id}"), "Edit pin", |session| {
target.replace(session, items)?;
Ok(Value::Null)
})
}
fn delete(session: &mut Session, parameters: &Value) -> Result<Value> {
let target = AnnotationTarget::resolve(session, parameters)?;
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?;
let mut items = target.items(session)?;
let previous = items.pins.len();
items.pins.retain(|pin| pin.id != id);
if previous == items.pins.len() {
return Err(bad("graph.pin.delete", format!("no pin {id}")));
}
session.edit("Delete pin", |session| {
target.replace(session, items)?;
Ok(Value::Null)
})
}
+28 -12
View File
@@ -123,6 +123,8 @@ pub struct Session {
pub(crate) next_document_id: u64,
pub(crate) documents: std::collections::BTreeMap<u64, crate::OpenDocument>,
pub(crate) linked_sources: std::collections::BTreeMap<String, Arc<Package>>,
/// Snapshots inserted by the library, excluding explicitly supplied dependencies
pub(crate) library_sources: std::collections::BTreeMap<String, Arc<Package>>,
pub pkg: Package,
/// Where the package was opened from or last saved to.
pub path: Option<String>,
@@ -130,6 +132,7 @@ pub struct Session {
pub graph: usize,
pub selection: Vec<NodeId>,
pub annotation_selection: Option<AnnotationSelection>,
pub annotation_target: crate::AnnotationTarget,
pub view2d: View2d,
pub view3d: View3d,
pub material_preview: crate::MaterialPreview,
@@ -157,17 +160,26 @@ pub struct Session {
pub cache: Arc<Mutex<Cache>>,
/// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry.
pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>,
/// The node library loaded from the SBS library folder
pub library: Arc<crate::node_library::NodeLibrary>,
pub(crate) history: crate::document_history::DocumentHistory,
group: Option<(Snapshot, bool)>,
decoded: Arc<Mutex<HashMap<(u64, bool), Image>>>,
}
impl Session {
pub fn new(mut pkg: Package) -> Session {
let library = crate::function_library::load();
if let Ok(library) = &library {
for (path, package) in &library.packages {
pkg.dependencies.entry(path.clone()).or_insert_with(|| package.clone());
/// Open a package with the process's installed node library.
pub fn new(pkg: Package) -> Session {
Self::with_library(pkg, crate::node_library::NodeLibrary::shared())
}
/// Open a package with an explicit library, preserving dependencies supplied by the caller.
pub fn with_library(mut pkg: Package, library: Arc<crate::NodeLibrary>) -> Session {
let mut library_sources = std::collections::BTreeMap::new();
for (path, package) in &library.packages {
if let std::collections::btree_map::Entry::Vacant(entry) = pkg.dependencies.entry(path.clone()) {
entry.insert(package.clone());
library_sources.insert(path.clone(), package.clone());
}
}
let mut session = Session {
@@ -177,6 +189,7 @@ impl Session {
next_document_id: 1,
documents: std::collections::BTreeMap::new(),
linked_sources: pkg.dependencies.clone(),
library_sources,
material_preview: crate::MaterialPreview::for_graph(&pkg, 0),
cooked_graph: None,
material_cooked: std::collections::BTreeMap::new(),
@@ -185,6 +198,7 @@ impl Session {
graph: 0,
selection: Vec::new(),
annotation_selection: None,
annotation_target: Default::default(),
view2d: View2d { channel: "rgba".into(), ..View2d::default() },
view3d: View3d::default(),
preview_size: Some(512),
@@ -201,19 +215,19 @@ impl Session {
cook_epoch: 0,
cache: Arc::new(Mutex::new(Cache::default())),
custom_mesh: None,
library: Default::default(),
history: Default::default(),
group: None,
decoded: Arc::new(Mutex::new(HashMap::new())),
};
session.refresh_links();
match library {
Ok(library) => {
for warning in library.warnings {
session.warn(warning);
}
}
Err(error) => session.warn(format!("Missing function library: {error}")),
for warning in &library.warnings {
session.warn(warning.clone());
}
if !library.packages.contains_key(crate::function_library::STANDARD_PACKAGE) {
session.warn(format!("Missing function library: {} did not load", crate::function_library::STANDARD_PACKAGE));
}
session.library = library;
session
}
@@ -232,6 +246,7 @@ impl Session {
graph: self.graph,
selection: self.selection.clone(),
annotation_selection: self.annotation_selection,
annotation_target: self.annotation_target.clone(),
material_preview: self.material_preview.clone(),
label: label.into(),
modified: self.modified,
@@ -330,6 +345,7 @@ impl Session {
self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1));
self.selection = s.selection;
self.annotation_selection = s.annotation_selection;
self.annotation_target = s.annotation_target;
self.material_preview = s.material_preview;
self.modified = s.modified;
self.dirty = s.dirty || self.cook_epoch != s.cook_epoch;
+1
View File
@@ -7,6 +7,7 @@ pub(crate) struct Snapshot {
pub(crate) graph: usize,
pub(crate) selection: Vec<NodeId>,
pub(crate) annotation_selection: Option<AnnotationSelection>,
pub(crate) annotation_target: crate::AnnotationTarget,
pub(crate) material_preview: crate::MaterialPreview,
pub(crate) label: String,
pub(crate) modified: bool,
+107
View File
@@ -66,3 +66,110 @@ fn annotation_properties_and_selection_survive_edits_undo_and_native_save() {
assert!(session.graph().unwrap().frames.is_empty());
assert_eq!(session.graph().unwrap().comments.len(), 1);
}
/// Pins share annotation selection, properties, deletion and undo.
#[test]
fn navigation_pins_select_edit_delete_and_save() {
for kind in ["material", "function"] {
let mut session = new_session();
if kind == "function" {
execute(&mut session, "file.new", &json!({"kind": kind})).unwrap();
}
let id = execute(&mut session, "graph.pin.add", &json!({"at": [-64, 128]})).unwrap()["id"].as_u64().unwrap();
execute(&mut session, "graph.annotation.select", &json!({"kind": "pin", "id": id})).unwrap();
execute(&mut session, "graph.pin.edit", &json!({"id": id, "description": "Start & <finish>", "at": [48, -96]})).unwrap();
let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "pins.sbs", &|_| None).unwrap();
assert!(loaded.warnings.is_empty());
let graph = loaded.pkg.graph_by_name(&session.graph().unwrap().sbs_path()).unwrap().1;
assert_eq!(graph.pins[0].name, "Start & <finish>");
assert_eq!(graph.pins[0].pos, [48.0, -96.0]);
execute(&mut session, "edit.delete", &json!({})).unwrap();
assert!(session.graph().unwrap().pins.is_empty());
assert!(session.annotation_selection.is_none());
session.undo().unwrap();
assert_eq!(session.graph().unwrap().pins[0].name, "Start & <finish>");
assert_eq!(serde_json::to_value(session.annotation_selection).unwrap(), json!({"kind": "pin", "id": id}));
let original = session.pkg.clone();
assert!(execute(&mut session, "graph.pin.edit", &json!({"id": 999999, "description": "Missing"})).is_err());
assert_eq!(session.pkg, original);
}
}
/// Every graph item edits its destination canvas and survives native SBS save/reload.
#[test]
fn library_graph_items_work_in_material_function_and_embedded_canvases() {
use materialcraft_engine::{
AnnotationTarget, FunctionGraphTarget, Session,
core::{FunctionGraph, NodeId, Value},
};
for kind in ["material", "function", "pixel_processor", "value_processor", "dynamic", "fx_map"] {
let mut session = new_session();
let target = match kind {
"material" => AnnotationTarget::Graph,
"function" => {
execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap();
AnnotationTarget::Graph
}
_ => {
let definition = if kind == "dynamic" { "uniform" } else { kind };
let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap());
match kind {
"fx_map" => AnnotationTarget::Pattern { owner: node },
"dynamic" => {
session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("color".into(), FunctionGraph::default());
AnnotationTarget::Function { target: FunctionGraphTarget::Dynamic { node, parameter: "color".into() } }
}
_ => AnnotationTarget::Function { target: FunctionGraphTarget::Parameter { node, parameter: "function".into() } },
}
}
};
let mut parameters = target.parameters();
parameters["at"] = json!([64, 128]);
for entry in ["item:comment", "item:frame", "item:pin", "node:dot"] {
parameters["entry"] = json!(entry);
let before = session.pkg.clone();
execute(&mut session, "library.add", &parameters).unwrap();
let after = session.pkg.clone();
session.undo().unwrap();
assert_eq!(session.pkg, before, "{kind}: {entry} undo");
session.redo().unwrap();
assert_eq!(session.pkg, after, "{kind}: {entry} redo");
}
let items = target.items(&session).unwrap();
assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}");
let mut pin_parameters = target.parameters();
pin_parameters["id"] = json!(items.pins[0].id);
pin_parameters["kind"] = json!("pin");
execute(&mut session, "graph.annotation.select", &pin_parameters).unwrap();
pin_parameters["description"] = json!("Checkpoint & <finish>");
execute(&mut session, "graph.pin.edit", &pin_parameters).unwrap();
let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "graph-items.sbs", &|_| None).unwrap();
let mut reopened = Session::new(loaded.pkg);
reopened.graph = reopened.pkg.graph_by_name(&session.graph().unwrap().sbs_path()).unwrap().0;
let graph = reopened.graph().unwrap();
let saved = match kind {
"material" | "function" => AnnotationTarget::Graph.items(&reopened).unwrap(),
"fx_map" => match &graph.nodes.iter().find(|node| node.def == kind).unwrap().params["pattern"] {
Value::PatternGraph(graph) => graph.annotations.clone(),
other => panic!("unexpected {other:?}"),
},
"dynamic" => graph.nodes.iter().find(|node| node.def == "uniform").unwrap().functions["color"].annotations.clone(),
_ => match &graph.nodes.iter().find(|node| node.def == kind).unwrap().params["function"] {
Value::Function(graph) => graph.annotations.clone(),
other => panic!("unexpected {other:?}"),
},
};
assert_eq!((saved.comments.len(), saved.frames.len(), saved.pins.len()), (1, 1, 1), "{kind}");
assert_eq!(saved.pins[0].name, "Checkpoint & <finish>", "{kind}");
assert_eq!(saved.pins[0].pos, [64.0, 128.0], "{kind}");
if target != AnnotationTarget::Graph {
assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty(), "{kind}: parent must stay untouched");
}
execute(&mut session, "edit.delete", &json!({})).unwrap();
assert!(target.items(&session).unwrap().pins.is_empty(), "{kind}");
session.undo().unwrap();
assert_eq!(target.items(&session).unwrap().pins[0].name, "Checkpoint & <finish>");
}
}
+48 -11
View File
@@ -594,20 +594,19 @@ fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs()
let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() };
let operations: Vec<_> = target.available_operations(&session).map(|operation| operation.id).collect();
let full_catalog = materialcraft_engine::nodes::function::FUNCTIONS;
let sampling = definition == "pixel_processor";
assert_eq!(operations.len(), full_catalog.len() - if sampling { 0 } else { 2 });
assert_eq!(operations.len(), full_catalog.len());
assert!(operations.contains(&"add"));
for sampler in ["samplelum", "samplecol"] {
assert_eq!(operations.contains(&sampler), sampling);
assert!(operations.contains(&sampler));
let original = session.pkg.clone();
let history = session.history();
let result =
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}}));
assert_eq!(result.is_ok(), sampling);
if !sampling {
assert_eq!(session.pkg, original);
assert_eq!(session.history(), history);
}
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}})).unwrap();
let inserted = session.pkg.clone();
session.undo().unwrap();
assert_eq!(session.pkg, original);
session.redo().unwrap();
assert_eq!(session.pkg, inserted);
}
let mut existing = FunctionGraph::default();
existing.add("samplelum", &[], Some(Value::Int2([0, 1])));
@@ -619,3 +618,41 @@ fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs()
assert_eq!(target.available_operations(&session).count(), materialcraft_engine::nodes::function::FUNCTIONS.len());
}
}
#[test]
fn library_samplers_read_image_inputs_in_both_processors() {
for definition in ["pixel_processor", "value_processor"] {
for sampler in ["samplelum", "samplecol"] {
let mut session = new_session();
session.preview_size = Some(16);
let color = [0.25, 0.5, 0.75, 1.0];
let image = NodeId(
execute(&mut session, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": true, "color": color}})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let parameters = if definition == "pixel_processor" { json!({"color_mode": sampler == "samplecol"}) } else { json!({}) };
let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition, "params": parameters})).unwrap()["id"].as_u64().unwrap());
session.graph_mut().unwrap().connect(image, "output", owner, "input0").unwrap();
let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() };
let mut function = FunctionGraph::default();
let position = function.add_constant(Value::Float2([0.5; 2]));
execute(&mut session, "graph.function.set", &json!({"target": target, "function": function})).unwrap();
let result = execute(&mut session, "library.add", &json!({"entry": format!("function:{sampler}"), "function": target, "at": [160, 0]})).unwrap();
let id = result["result"]["id"].as_u64().unwrap();
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": position, "to": id, "input": 0}}))
.unwrap();
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": id}})).unwrap();
session.cook();
if definition == "value_processor" {
let expected = if sampler == "samplecol" { Value::Float4(color) } else { Value::Float(color[0]) };
assert_eq!(session.cooked.value(owner, 0), Some(&expected));
} else {
let expected = if sampler == "samplecol" { color } else { [color[0], color[0], color[0], 1.0] };
assert_eq!(session.cooked.image(owner, 0).unwrap().get(0, 0, false), expected);
}
}
}
}
+44 -2
View File
@@ -1,4 +1,4 @@
use materialcraft_engine::{Session, core::NodeId, execute, file_cmds::export_outputs, formats, new_session};
use materialcraft_engine::{ExportRequest, Session, core::NodeId, execute, file_cmds::export_outputs, formats, new_session};
use serde_json::json;
fn session() -> (Session, Vec<u64>) {
@@ -31,7 +31,7 @@ fn export_rejects_duplicate_final_names_from_patterns_identifiers_and_sanitizati
for (&id, name) in outputs.iter().zip(identifiers) {
execute(&mut s, "graph.node.param", &json!({"id": id, "param": "identifier", "value": name})).unwrap();
}
let result = export_outputs(&s, 0, "png", pattern, None, None);
let result = export_outputs(&s, &ExportRequest { pattern: pattern.into(), ..ExportRequest::new(0) });
assert!(result.is_err(), "colliding names were accepted: {identifiers:?}, {pattern}");
let error = result.err().unwrap().to_string();
assert!(error.contains("filename") && error.contains("identifier"), "{error}");
@@ -108,3 +108,45 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() {
assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}");
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn export_writes_only_the_selected_outputs_in_their_color_spaces() {
let (mut s, _) = session();
let dir = TempDir::new("selected");
let stored = |name: &str| formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), true).unwrap().get(0, 0, false)[0];
let only_second = json!({"dir": dir.0, "pattern": "$(identifier)", "outputs": ["second"], "colorSpaces": {"second": "srgb"}});
let result = execute(&mut s, "file.export", &only_second).unwrap();
assert_eq!(result["files"].as_array().unwrap().len(), 1);
assert!(!dir.0.join("first.png").exists(), "an unselected output stays unwritten");
let srgb = 1.055 * 0.8_f32.powf(1.0 / 2.4) - 0.055;
assert!((stored("second.png") - srgb).abs() < 0.005, "sRGB writes through the curve: {}", stored("second.png"));
std::fs::remove_file(dir.0.join("second.png")).unwrap();
execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)", "colorSpaces": {"second": "linear"}})).unwrap();
assert!((stored("second.png") - 0.8).abs() < 0.005, "linear writes the values unchanged: {}", stored("second.png"));
assert!(dir.0.join("first.png").exists(), "without `outputs` every connected output is written");
}
#[test]
fn export_requests_name_existing_outputs_and_color_spaces() {
let (s, _) = session();
let request = ExportRequest::from_params(&s, &json!({"outputs": ["first"], "colorSpaces": {"first": "Linear"}})).unwrap();
assert!(request.includes("first") && !request.includes("second"));
assert_eq!(request.color_space("first", "baseColor"), materialcraft_engine::ColorSpace::Linear);
assert_eq!(request.color_space("second", "baseColor"), materialcraft_engine::ColorSpace::Srgb, "unset outputs follow their usage");
assert_eq!(request.color_space("second", "normal"), materialcraft_engine::ColorSpace::Raw);
for (params, expected) in [
(json!({"outputs": []}), "no outputs selected"),
(json!({"outputs": ["third"]}), "no output `third`"),
(json!({"outputs": "first"}), "list of output identifiers"),
(json!({"colorSpaces": {"third": "raw"}}), "no output `third`"),
(json!({"colorSpaces": {"first": "cmyk"}}), "srgb, linear or raw"),
(json!({"format": "tif"}), "unknown format `tif`"),
] {
let error = ExportRequest::from_params(&s, &params).unwrap_err().to_string();
assert!(error.contains(expected), "{params}: {error}");
}
}
+111 -1
View File
@@ -19,10 +19,120 @@ fn exposing_the_same_parameter_on_two_nodes_gives_each_its_own_input() {
let graph = s.graph().unwrap();
assert_eq!(graph.exposed.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ids);
for (node, id) in nodes.iter().zip(&ids) {
assert_eq!(graph.node(*node).unwrap().bindings.get("opacity"), Some(id));
assert_eq!(graph.node(*node).unwrap().functions["opacity"].input_identifier(), Some(id.as_str()));
}
// An explicit id still has to be free, and an unbound input still needs one
assert!(execute(&mut s, "graph.exposed.add", &json!({"id": "opacity_1", "bind": {"node": nodes[0].0, "param": "opacity"}})).is_err());
assert!(execute(&mut s, "graph.exposed.add", &json!({"default": 0.5})).is_err());
}
#[test]
fn base_parameters_cannot_be_exposed_as_graph_inputs() {
let mut session = new_session();
let owner = execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].clone();
let original = session.graph().unwrap().clone();
let result = execute(&mut session, "graph.exposed.add", &json!({"bind": {"node": owner, "param": "randomseed", "base": true}}));
assert!(result.is_err(), "exposure belongs to Specific Parameters");
assert_eq!(*session.graph().unwrap(), original);
}
#[test]
fn exposed_input_settings_survive_sbs_and_undo() {
let mut session = new_session();
let owner = execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].clone();
let original = session.graph().unwrap().clone();
execute(
&mut session,
"graph.exposed.add",
&json!({
"id": "radius", "label": "Radius", "group": "Surface/Blur", "description": "Controls the radius",
"editor": "input", "default": 10.0, "min": 0.0, "max": 32.0, "clamp": true, "step": 0.25,
"bind": {"node": owner, "param": "intensity"}
}),
)
.unwrap();
let input = serde_json::to_value(&session.graph().unwrap().exposed[0]).unwrap();
assert_eq!(input["description"], "Controls the radius");
assert_eq!(input["editor"], "input");
assert_eq!(input["clamp"], true);
assert_eq!(input["step"], 0.25);
let bytes = materialcraft_engine::formats::sbs::write_sbs(&session.pkg).unwrap();
let reopened = materialcraft_engine::formats::sbs::read_sbs(&bytes, "exposed.sbs", &|_| None).unwrap();
assert_eq!(reopened.pkg.graphs[0].exposed, session.graph().unwrap().exposed);
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(*session.graph().unwrap(), original);
}
#[test]
fn preparing_an_input_is_read_only_and_invalid_settings_are_atomic() {
let mut session = new_session();
let owner = execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].clone();
execute(&mut session, "graph.node.param", &json!({"id": owner, "param": "intensity", "value": 10.0})).unwrap();
let original = session.graph().unwrap().clone();
let binding = json!({"node": owner, "param": "intensity"});
let draft = execute(&mut session, "graph.exposed.prepare", &json!({"bind": binding})).unwrap();
assert_eq!(draft["id"], "intensity");
assert_eq!(draft["label"], "Intensity");
assert_eq!(draft["default"], json!({"t": "float", "v": 10.0}));
assert_eq!(*session.graph().unwrap(), original);
for changes in [
json!({"step": 0.0}),
json!({"step": -0.01}),
json!({"min": 3.0, "max": 2.0}),
json!({"id": "bad id"}),
json!({"editor": "toggle"}),
json!({"default": {"t": "float", "v": 1e39}}),
] {
let mut parameters = changes;
parameters["bind"] = binding.clone();
assert!(execute(&mut session, "graph.exposed.add", &parameters).is_err(), "{parameters}");
assert_eq!(*session.graph().unwrap(), original);
}
}
#[test]
fn color_and_enum_exposure_preserve_their_editors_and_defaults() {
let mut session = new_session();
let uniform = execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].clone();
let blend = execute(&mut session, "graph.node.add", &json!({"def": "blend"})).unwrap()["id"].clone();
execute(&mut session, "graph.exposed.add", &json!({"editor": "input", "bind": {"node": uniform, "param": "color"}})).unwrap();
execute(&mut session, "graph.exposed.add", &json!({"bind": {"node": blend, "param": "mode"}})).unwrap();
let bytes = materialcraft_engine::formats::sbs::write_sbs(&session.pkg).unwrap();
let reopened = materialcraft_engine::formats::sbs::read_sbs(&bytes, "editors.sbs", &|_| None).unwrap();
let mut inputs = reopened.pkg.graphs[0].exposed.clone();
let expected = &session.graph().unwrap().exposed;
let color = inputs[0].default.as_vec4().unwrap();
let original = expected[0].default.as_vec4().unwrap();
assert!(color.iter().zip(original).all(|(left, right)| (left - right).abs() < 1e-6));
inputs[0].default = expected[0].default.clone();
assert_eq!(&inputs, expected);
assert_eq!(reopened.pkg.graphs[0].exposed[0].editor(), materialcraft_engine::core::ParameterEditor::Input);
assert_eq!(reopened.pkg.graphs[0].exposed[1].editor(), materialcraft_engine::core::ParameterEditor::Dropdown);
}
#[test]
fn deleting_an_exposed_input_detaches_its_parameter_functions_and_undo_restores_them() {
let mut session = new_session();
let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap());
execute(&mut session, "graph.node.param", &json!({"id": owner, "param": "intensity", "value": 2.0})).unwrap();
execute(&mut session, "graph.exposed.add", &json!({"id": "radius", "default": 3.0, "bind": {"node": owner, "param": "intensity"}})).unwrap();
let original = session.graph().unwrap().clone();
execute(&mut session, "graph.exposed.delete", &json!({"id": "radius"})).unwrap();
session.cook();
assert_eq!(session.cooked.nodes[&owner].error, None);
assert!(session.graph().unwrap().node(owner).unwrap().functions.is_empty());
assert_eq!(session.cooked.nodes[&owner].parameters.get("intensity"), Some(&materialcraft_engine::core::Value::Float(2.0)));
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(*session.graph().unwrap(), original);
}
@@ -11,6 +11,10 @@ fn source() -> Package {
let mut package = Package::new("Functions");
let mut graph = Graph::new("Twice");
graph.exposed.push(ExposedParameter {
description: String::new(),
editor: None,
clamp: false,
step: None,
id: "amount".into(),
label: "Amount".into(),
group: String::new(),
@@ -246,6 +250,102 @@ fn unconnected_instance_inputs_use_the_source_defaults() {
assert!(function::warnings(graph).is_empty());
}
#[test]
fn function_instance_inputs_follow_current_source_values() {
for linked in [false, true] {
let mut session = Session::new(source());
session.path = Some(std::env::temp_dir().join("materialcraft-function-input-source.sbs").to_string_lossy().into_owned());
execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.25})).unwrap();
if linked {
let mut package = Package::new("Calls");
let mut graph = Graph::new("Caller");
graph.function = Some(FunctionGraph::default());
package.graphs.push(graph);
file_cmds::open_bytes(&mut session, &formats::sbs::write_sbs(&package).unwrap(), Some("function-input-target.sbs".into())).unwrap();
} else {
execute(&mut session, "file.new", &json!({"name": "Caller", "kind": "function"})).unwrap();
}
let document = session.document_id;
let target = json!({"kind": "graph"});
let instance = call(&mut session, 0, "Twice", &target);
edit(&mut session, &target, json!({"action": "output", "id": instance}));
assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.5));
execute(&mut session, "file.new", &json!({"name": "Outer", "kind": "function"})).unwrap();
let outer = call(&mut session, document, "Caller", &target);
edit(&mut session, &target, json!({"action": "output", "id": outer}));
execute(&mut session, "package.activate", &json!({"document": 0})).unwrap();
execute(&mut session, "graph.open", &json!({"graph": "Twice"})).unwrap();
execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.75})).unwrap();
execute(&mut session, "package.activate", &json!({"document": document})).unwrap();
execute(&mut session, "graph.open", &json!({"graph": "Outer"})).unwrap();
assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(1.5));
assert!(function::warnings(session.graph().unwrap().function.as_ref().unwrap()).is_empty());
execute(&mut session, "graph.open", &json!({"graph": "Caller"})).unwrap();
let constant = edit(&mut session, &target, json!({"action": "add", "operation": "const_float1", "at": [0, 0]}))["id"].as_u64().unwrap();
edit(&mut session, &target, json!({"action": "value", "id": constant, "value": Value::Float(0.125)}));
edit(&mut session, &target, json!({"action": "connect", "from": constant, "to": instance, "input": 0}));
execute(&mut session, "package.activate", &json!({"document": 0})).unwrap();
execute(&mut session, "graph.open", &json!({"graph": "Twice"})).unwrap();
execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 1.0})).unwrap();
execute(&mut session, "package.activate", &json!({"document": document})).unwrap();
execute(&mut session, "graph.open", &json!({"graph": "Outer"})).unwrap();
assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.25));
}
}
#[test]
fn function_instance_input_changes_recook_parameter_functions_and_processors() {
let mut session = Session::new(source());
execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.25})).unwrap();
execute(&mut session, "file.new", &json!({"name": "Material", "template": "empty"})).unwrap();
let blur = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap());
execute(&mut session, "graph.node.function", &json!({"id": blur, "param": "intensity", "mode": "empty"})).unwrap();
let processor = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "value_processor"})).unwrap()["id"].as_u64().unwrap());
for target in [json!({"kind": "dynamic", "node": blur, "parameter": "intensity"}), json!({"kind": "parameter", "node": processor, "parameter": "function"})]
{
let instance = call(&mut session, 0, "Twice", &target);
edit(&mut session, &target, json!({"action": "output", "id": instance}));
}
session.preview_size = Some(16);
let cooked = session.cook();
assert_eq!(cooked.nodes[&blur].error, None);
assert_eq!(cooked.nodes[&blur].parameters["intensity"], Value::Float(0.5));
assert_eq!(cooked.value(processor, 0), Some(&Value::Float(0.5)));
execute(&mut session, "graph.open", &json!({"graph": "Twice"})).unwrap();
execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.75})).unwrap();
execute(&mut session, "graph.open", &json!({"graph": "Material"})).unwrap();
let cooked = session.cook();
assert_eq!(cooked.nodes[&blur].error, None);
assert_eq!(cooked.nodes[&blur].parameters["intensity"], Value::Float(1.5));
assert_eq!(cooked.nodes[&processor].error, None);
assert_eq!(cooked.value(processor, 0), Some(&Value::Float(1.5)));
assert!(!cooked.nodes[&blur].cached);
assert!(!cooked.nodes[&processor].cached);
let cached = session.cook();
assert!(cached.nodes[&blur].cached);
assert!(cached.nodes[&processor].cached);
assert_eq!(cached.value(processor, 0), Some(&Value::Float(1.5)));
let saved = formats::sbs::write_sbs(&session.pkg).unwrap();
let mut reopened = Session::new(formats::sbs::read_sbs(&saved, "function-inputs.sbs", &|_| None).unwrap().pkg);
execute(&mut reopened, "graph.open", &json!({"graph": "Material"})).unwrap();
reopened.preview_size = Some(16);
let blur = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "blur").unwrap().id;
let processor = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "value_processor").unwrap().id;
let cooked = reopened.cook();
assert_eq!(cooked.nodes[&blur].parameters["intensity"], Value::Float(1.5));
assert_eq!(cooked.value(processor, 0), Some(&Value::Float(1.5)));
}
#[test]
fn connected_inputs_survive_source_interface_changes_and_missing_sources() {
let mut session = Session::new(source());
@@ -301,3 +301,86 @@ fn saved_dependencies_reopen_without_source_files_in_explorer_and_missing_source
assert!(missing.path.is_some());
std::fs::remove_dir_all(directory).unwrap();
}
fn assert_instance_color(session: &mut Session, instance: NodeId, expected: [f32; 4]) {
let cooked = session.cook();
assert_eq!(cooked.nodes[&instance].error, None);
let actual = cooked.image(instance, 0).unwrap().get(0, 0, false);
assert!(actual.into_iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-6), "{actual:?} != {expected:?}");
}
#[test]
fn instance_defaults_follow_current_source_inputs_before_and_after_save() {
for linked in [false, true] {
let directory = std::env::temp_dir().join(format!("materialcraft-current-inputs-{}-{linked}", std::process::id()));
std::fs::create_dir_all(&directory).unwrap();
let source_path = directory.join("source.sbs");
let target_path = directory.join("target.sbs");
let (package, value) = source();
let mut session = Session::new(package);
session.path = Some(source_path.to_string_lossy().into_owned());
execute(&mut session, "graph.exposed.add", &json!({"id": "tint", "bind": {"node": value, "param": "color"}})).unwrap();
execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": [0.2, 0.3, 0.4, 1.0]})).unwrap();
let target_document = if linked {
let mut target = Package::new("Target");
target.graphs.push(Graph::new("Target"));
open(&mut session, &target, target_path.to_str().unwrap())
} else {
execute(&mut session, "file.new", &json!({"name": "Target", "template": "empty"})).unwrap();
session.document_id
};
let target_graph = session.graph;
let instance = NodeId(execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Source"})).unwrap()["id"].as_u64().unwrap());
session.preview_size = Some(16);
for expected in [[0.2, 0.3, 0.4, 1.0], [0.8, 0.6, 0.4, 1.0]] {
execute(&mut session, "package.activate", &json!({"document": 0})).unwrap();
session.graph = 0;
execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": expected})).unwrap();
execute(&mut session, "package.activate", &json!({"document": target_document})).unwrap();
session.graph = target_graph;
let cooked = session.cook();
assert_eq!(cooked.nodes[&instance].error, None);
assert_eq!(cooked.nodes[&instance].parameters["tint"], Value::Color(expected));
assert_instance_color(&mut session, instance, expected);
}
let source_bytes = formats::sbs::write_sbs(session.open_packages().iter().find(|entry| entry.0 == 0).unwrap().1).unwrap();
std::fs::write(&source_path, source_bytes).unwrap();
std::fs::write(&target_path, file_cmds::save_bytes(&session).unwrap()).unwrap();
let mut reopened = Session::new(Package::new("Initial"));
file_cmds::open_file(&mut reopened, target_path.to_str().unwrap()).unwrap();
assert!(reopened.load_warnings.is_empty(), "{:?}", reopened.load_warnings);
reopened.graph = target_graph;
reopened.preview_size = Some(16);
let instance = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "graph_instance").unwrap().id;
assert_instance_color(&mut reopened, instance, [0.8, 0.6, 0.4, 1.0]);
execute(&mut reopened, "graph.node.param", &json!({"id": instance, "param": "tint", "value": [0.1, 0.2, 0.3, 1.0]})).unwrap();
assert_instance_color(&mut reopened, instance, [0.1, 0.2, 0.3, 1.0]);
execute(&mut reopened, "graph.node.reset", &json!({"id": instance, "param": "tint"})).unwrap();
assert_instance_color(&mut reopened, instance, [0.8, 0.6, 0.4, 1.0]);
std::fs::remove_dir_all(directory).unwrap();
}
}
#[test]
fn instance_constant_capture_uses_the_current_source_input_without_a_prior_cook() {
let (package, value) = source();
let mut session = Session::new(package);
execute(&mut session, "graph.exposed.add", &json!({"id": "tint", "bind": {"node": value, "param": "color"}})).unwrap();
execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": [0.8, 0.6, 0.4, 1.0]})).unwrap();
execute(&mut session, "file.new", &json!({"name": "Target", "template": "empty"})).unwrap();
let instance = NodeId(execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Source"})).unwrap()["id"].as_u64().unwrap());
let info = execute(&mut session, "graph.node.parameterInfo", &json!({"id": instance, "param": "tint"})).unwrap();
assert_eq!(info["value"], json!(Value::Color([0.8, 0.6, 0.4, 1.0])));
execute(&mut session, "graph.node.function", &json!({"id": instance, "param": "tint", "mode": "constant"})).unwrap();
session.graph = 0;
execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": [0.0, 0.0, 0.0, 1.0]})).unwrap();
session.graph = 1;
session.preview_size = Some(16);
assert_instance_color(&mut session, instance, [0.8, 0.6, 0.4, 1.0]);
}
+2
View File
@@ -20,9 +20,11 @@ mod graph_properties;
mod linked_instances;
mod linked_resources;
mod material_preview;
mod node_library;
mod normal_maps;
mod open_documents;
mod optimization_perf;
mod parameter_functions;
mod pattern_graph;
mod perf;
mod reset_drivers;
+110
View File
@@ -0,0 +1,110 @@
use materialcraft_engine::{
Session,
core::{FunctionGraph, Graph, Package},
execute,
};
use serde_json::{Value, json};
#[path = "../support/node_library.rs"]
mod fixture;
/// Return the catalog entries exposed by the library command.
fn entries(session: &mut Session, parameters: Value) -> Vec<Value> {
execute(session, "library.tree", &parameters).unwrap()["entries"].as_array().unwrap().clone()
}
/// Catalog filters preserve matching entries and reject unknown canvases.
#[test]
fn the_library_tree_lists_categories_and_filters_entries() {
let mut session = fixture::session();
let tree = execute(&mut session, "library.tree", &json!({})).unwrap();
let names: Vec<_> = tree["categories"].as_array().unwrap().iter().map(|category| category["name"].as_str().unwrap()).collect();
assert_eq!(names[..4], ["Graph items", "Atomic nodes", "FxMap nodes", "Function nodes"]);
assert!(names.contains(&"MCF functions") && !names.contains(&"SDF functions"));
assert_eq!(tree["layouts"], json!([]));
let constants = entries(&mut session, json!({"category": "Functions/Constant"}));
assert!(constants.iter().any(|entry| entry["label"] == "Pi"));
let functions = entries(&mut session, json!({"category": "Functions"}));
let expected = fixture::library().packages["sbs://functions.sbs"].graphs.iter().filter(|graph| graph.function.is_some()).count();
assert_eq!(functions.len(), expected, "every bundled function, across the sub-categories");
assert!(entries(&mut session, json!({})).iter().all(|entry| entry["missing"].is_null()));
assert!(entries(&mut session, json!({"category": "Texture generators"})).is_empty());
let functions = entries(&mut session, json!({"canvas": "function", "filter": "pi"}));
assert!(functions.iter().any(|entry| entry["id"] == "sbs://functions.sbs#Functions/Math/Pi" && entry["type"] == "functionInstance"));
assert!(functions.iter().all(|entry| entry["canvas"] == "function" || entry["canvas"] == "any"));
assert!(execute(&mut session, "library.tree", &json!({"canvas": "teapot"})).is_err());
}
/// Library additions use compatible canvases and participate in undo.
#[test]
fn library_entries_add_to_the_graph_they_fit() {
let mut session = fixture::session();
let before = session.graph().unwrap().nodes.len();
let added = execute(&mut session, "library.add", &json!({"entry": "node:blur", "at": [32.0, 64.0]})).unwrap();
assert_eq!(added["entry"], "node:blur");
let graph = session.graph().unwrap();
assert_eq!(graph.nodes.len(), before + 1);
assert_eq!(graph.nodes.last().unwrap().def, "blur");
assert_eq!(graph.nodes.last().unwrap().pos, [32.0, 64.0]);
for (entry, check) in [("item:comment", "comments"), ("item:frame", "frames"), ("item:pin", "pins")] {
let count = |session: &Session| serde_json::to_value(session.graph().unwrap()).unwrap()[check].as_array().map_or(0, Vec::len);
let previous = count(&session);
execute(&mut session, "library.add", &json!({"entry": entry})).unwrap();
assert_eq!(count(&session), previous + 1, "{entry}");
}
assert!(execute(&mut session, "library.add", &json!({"entry": "nothing"})).is_err());
assert!(execute(&mut session, "library.add", &json!({})).is_err());
// Function entries need a Function canvas
assert!(execute(&mut session, "library.add", &json!({"entry": "function:add"})).is_err());
assert!(execute(&mut session, "library.add", &json!({"entry": "pattern:paramset"})).is_err());
let mut package = Package::new("Functions");
let mut graph = Graph::new("Caller");
graph.function = Some(FunctionGraph::default());
package.graphs.push(graph);
let mut session = Session::with_library(package, fixture::library());
execute(&mut session, "library.add", &json!({"entry": "function:add", "at": [0.0, 0.0]})).unwrap();
execute(&mut session, "library.add", &json!({"entry": "sbs://functions.sbs#Functions/Math/Pi", "at": [140.0, 0.0]})).unwrap();
let function = session.graph().unwrap().function.as_ref().unwrap();
assert_eq!(function.nodes.len(), 2);
assert!(function.nodes.iter().any(|node| node.op == "add"));
assert!(function.nodes.iter().any(|node| node.instance.as_ref().is_some_and(|instance| instance.graph == "Functions/Math/Pi")));
assert!(execute(&mut session, "library.add", &json!({"entry": "node:blur"})).is_err());
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(session.graph().unwrap().function.as_ref().unwrap().nodes.len(), 1);
}
/// Reload reports the installed catalog without modifying an unrelated graph.
#[test]
fn reloading_the_library_keeps_open_work_unmodified() {
let mut session = fixture::session();
let reloaded = execute(&mut session, "library.reload", &json!({})).unwrap();
let entries = session.library_entries();
assert_eq!(reloaded["entries"].as_u64(), Some(entries.len() as u64));
assert_eq!(reloaded["available"].as_u64(), Some(entries.iter().filter(|entry| entry.missing.is_none()).count() as u64));
assert!(!session.modified);
assert!(session.library.packages.keys().all(|path| session.pkg.dependencies.contains_key(path)));
}
/// Reload must retain an explicitly supplied package even when its alias matches the library.
#[test]
fn review_reload_preserves_user_library_alias() {
let mut dependency = Package::new("User functions");
let mut function = Graph::new("User_function");
function.function = Some(FunctionGraph::default());
dependency.graphs.push(function);
let mut package = Package::new("Project");
package.graphs.push(Graph::new("Material"));
package.dependencies.insert("sbs://functions.sbs".into(), std::sync::Arc::new(dependency.clone()));
let mut session = Session::with_library(package, fixture::library());
execute(&mut session, "library.reload", &json!({})).unwrap();
assert!(session.pkg.dependencies["sbs://functions.sbs"].graphs == dependency.graphs, "the user dependency was replaced");
assert!(entries(&mut session, json!({})).iter().any(|entry| entry["id"] == "sbs://functions.sbs#User_function"));
}
@@ -0,0 +1,391 @@
use materialcraft_engine::{
Session,
core::{FunctionGraph, NodeId, Value},
execute, formats, new_session,
};
use serde_json::{Value as Json, json};
fn command(session: &mut Session, name: &str, parameters: Json) -> Json {
execute(session, name, &parameters).unwrap()
}
fn node(session: &mut Session, definition: &str) -> NodeId {
NodeId(command(session, "graph.node.add", json!({"def": definition}))["id"].as_u64().unwrap())
}
#[test]
fn output_size_function_controls_resolution_and_survives_sbs() {
let mut session = new_session();
session.preview_size = None;
command(&mut session, "graph.size", json!({"width": 64, "height": 64}));
let owner = node(&mut session, "uniform");
let function = FunctionGraph::constant(Value::Int2([1, -1]));
command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "function": function}));
let cooked = session.cook();
let image = cooked.image(owner, 0).unwrap();
assert_eq!((image.w, image.h), (128, 32));
assert!(cooked.nodes[&owner].error.is_none());
let bytes = formats::sbs::write_sbs(&session.pkg).unwrap();
let loaded = formats::sbs::read_sbs(&bytes, "parameter-functions.sbs", &|_| None).unwrap();
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
let mut reopened = Session::new(loaded.pkg);
reopened.preview_size = None;
let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id;
let cooked = reopened.cook();
let image = cooked.image(owner, 0).unwrap();
assert_eq!((image.w, image.h), (128, 32));
}
#[test]
fn empty_creation_has_no_output_and_constant_creation_uses_the_current_value() {
let mut session = new_session();
let owner = node(&mut session, "blur");
command(&mut session, "graph.node.param", json!({"id": owner, "param": "intensity", "value": 7.0}));
command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "mode": "empty"}));
let function = &session.graph().unwrap().node(owner).unwrap().functions["intensity"];
assert!(function.nodes.is_empty());
assert_eq!(function.output, None);
command(&mut session, "edit.undo", json!({}));
command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "mode": "constant"}));
let function = &session.graph().unwrap().node(owner).unwrap().functions["intensity"];
assert_eq!(function.nodes.len(), 1);
assert_eq!(function.nodes[0].value, Some(Value::Float(7.0)));
assert_eq!(function.output, Some(function.nodes[0].id));
}
#[test]
fn exposed_parameters_are_editable_get_functions() {
let mut session = new_session();
let owner = node(&mut session, "blend");
command(&mut session, "graph.exposed.add", json!({"id": "amount", "bind": {"node": owner, "param": "opacity"}}));
let function = &session.graph().unwrap().node(owner).unwrap().functions["opacity"];
let output = function.node(function.output.unwrap()).unwrap();
assert_eq!(output.op, "get_float1");
assert_eq!(output.value, Some(Value::Text("amount".into())));
}
#[test]
fn native_dynamic_output_size_is_not_discarded_on_load() {
let xml = br#"<package><identifier v="Original"/><content><graph><identifier v="Material"/><compNodes>
<compNode><uid v="1"/><compImplementation><compFilter><filter v="uniform"/><parameters>
<parameter><name v="outputsize"/><relativeTo v="0"/><paramValue><dynamicValue><rootnode v="2"/><paramNodes>
<paramNode><uid v="2"/><function v="const_int2"/><type v="32"/><funcDatas><funcData><name v="const_int2"/><constantValue><constantValueInt2 v="6 5"/></constantValue></funcData></funcDatas></paramNode>
</paramNodes></dynamicValue></paramValue></parameter>
</parameters></compFilter></compImplementation></compNode>
</compNodes></graph></content></package>"#;
let loaded = formats::sbs::read_sbs(xml, "original.sbs", &|_| None).unwrap();
let mut session = Session::new(loaded.pkg);
session.preview_size = None;
let owner = session.graph().unwrap().nodes[0].id;
let cooked = session.cook();
let image = cooked.image(owner, 0).unwrap();
assert_eq!((image.w, image.h), (64, 32));
}
#[test]
fn inherited_size_functions_use_nominal_input_size_before_preview_capping() {
use materialcraft_engine::core::{BaseParameter, ValueType};
let mut session = new_session();
session.preview_size = Some(16);
command(&mut session, "graph.size", json!({"width": 64, "height": 64}));
let source = node(&mut session, "uniform");
command(
&mut session,
"graph.node.function",
json!({"id": source, "base": true, "param": "outputsize", "function": FunctionGraph::constant(Value::Int2([1, 0]))}),
);
let owner = NodeId(command(&mut session, "graph.node.add", json!({"def": "blur", "connectFrom": {"node": source}}))["id"].as_u64().unwrap());
let unrelated = node(&mut session, "uniform");
let mut function = FunctionGraph::input("$sizelog2", ValueType::Float2);
let size = function.output.unwrap();
let parent = function.add_constant(Value::Float2([6.0, 6.0]));
let difference = function.add("sub", &[size, parent], None);
function.output = Some(function.add("toint2", &[difference], None));
command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "function": function}));
let cooked = session.cook();
assert_eq!(cooked.nodes[&owner].error, None);
assert_eq!(cooked.nodes[&owner].base.size, [256, 64]);
assert_eq!(cooked.nodes[&owner].base_values[&BaseParameter::OutputSize], Value::Int2([1, 0]));
assert_eq!((cooked.image(owner, 0).unwrap().w, cooked.image(owner, 0).unwrap().h), (16, 4));
command(
&mut session,
"graph.node.function",
json!({"id": source, "base": true, "param": "outputsize", "function": FunctionGraph::constant(Value::Int2([0, 0]))}),
);
let cooked = session.cook();
assert_eq!(cooked.nodes[&owner].base.size, [64, 64]);
assert!(!cooked.nodes[&owner].cached);
assert!(cooked.nodes[&unrelated].cached);
}
#[test]
fn every_base_function_preserves_its_type_inheritance_and_value_in_sbs() {
use materialcraft_engine::core::{BaseParameter, ParameterInheritance};
let mut session = new_session();
session.preview_size = Some(16);
let owner = node(&mut session, "uniform");
let cases = [
(BaseParameter::OutputSize, Value::Int2([6, 5])),
(BaseParameter::Format, Value::Int(3)),
(BaseParameter::PixelSize, Value::Float2([0.25, 0.5])),
(BaseParameter::PixelRatio, Value::Int(1)),
(BaseParameter::Tiling, Value::Int(2)),
(BaseParameter::RandomSeed, Value::Int(23)),
];
for (parameter, value) in &cases {
command(&mut session, "graph.node.base", json!({"id": owner, "param": parameter.identifier(), "inheritance": "absolute"}));
command(
&mut session,
"graph.node.function",
json!({"id": owner, "base": true, "param": parameter.identifier(), "function": FunctionGraph::constant(value.clone())}),
);
}
let saved = formats::sbs::write_sbs(&session.pkg).unwrap();
let loaded = formats::sbs::read_sbs(&saved, "base-functions.sbs", &|_| None).unwrap();
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
let mut reopened = Session::new(loaded.pkg);
reopened.preview_size = Some(16);
let owner = reopened.graph().unwrap().nodes[0].id;
for (parameter, _) in &cases {
assert_eq!(parameter.inheritance(&reopened.graph().unwrap().node(owner).unwrap().base), ParameterInheritance::Absolute);
}
let result = &reopened.cook().nodes[&owner];
assert_eq!(result.error, None);
for (parameter, value) in cases {
assert_eq!(result.base_values[&parameter], value);
}
assert_eq!(result.base.size, [64, 32]);
assert_eq!(result.base.seed, 23);
assert_eq!(result.base.pixel_size, [0.25, 0.5]);
assert_eq!(result.base.tiling, [false, true]);
assert_eq!(result.base.pixel_ratio, 1);
assert_eq!(result.base.format, materialcraft_engine::core::OutputFormat::F32);
}
#[test]
fn constant_replacement_freezes_the_driven_value_and_reset_is_undoable() {
let mut session = new_session();
session.preview_size = Some(16);
let owner = node(&mut session, "blur");
command(&mut session, "graph.exposed.add", json!({"id": "amount", "bind": {"node": owner, "param": "intensity"}}));
command(&mut session, "graph.exposed.set", json!({"id": "amount", "value": 3.0}));
command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "mode": "constant"}));
command(&mut session, "graph.exposed.set", json!({"id": "amount", "value": 8.0}));
assert_eq!(session.cook().nodes[&owner].parameters["intensity"], Value::Float(3.0));
let before = session.pkg.clone();
command(&mut session, "graph.node.reset", json!({"id": owner, "param": "intensity"}));
assert!(!session.graph().unwrap().node(owner).unwrap().functions.contains_key("intensity"));
command(&mut session, "edit.undo", json!({}));
assert_eq!(session.pkg, before);
command(&mut session, "graph.node.param", json!({"id": owner, "param": "intensity", "value": 2.0}));
assert!(!session.graph().unwrap().node(owner).unwrap().functions.contains_key("intensity"));
assert_eq!(session.cook().nodes[&owner].parameters["intensity"], Value::Float(2.0));
}
#[test]
fn empty_and_wrong_type_functions_remain_editable_but_report_cook_errors() {
let mut session = new_session();
session.preview_size = Some(16);
let owner = node(&mut session, "uniform");
for function in [FunctionGraph::default(), FunctionGraph::constant(Value::Float(2.0))] {
command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "function": function}));
assert!(session.cook().nodes[&owner].error.is_some());
let info = command(&mut session, "graph.node.parameterInfo", json!({"id": owner, "base": true, "param": "outputsize"}));
assert_eq!(info["expectedType"], "Integer2");
assert!(!info["warnings"].as_array().unwrap().is_empty());
command(&mut session, "graph.node.function.edit", json!({"id": owner, "base": true, "param": "outputsize"}));
let bytes = formats::sbs::write_sbs(&session.pkg).unwrap();
let loaded = formats::sbs::read_sbs(&bytes, "incomplete.sbs", &|_| None).unwrap();
assert_eq!(loaded.pkg.graphs[0].nodes[0].base.functions.values().next().unwrap().nodes.len(), function.nodes.len());
}
}
#[test]
fn instance_parameter_functions_work_without_stored_literals_and_use_instance_size() {
use materialcraft_engine::core::{Graph, Package, ValueType};
let mut source = Graph::new("Source");
let color = source.add_node("uniform", [0.0; 2]);
source.node_mut(color).unwrap().params.insert("color_mode".into(), Value::Bool(false));
source.node_mut(color).unwrap().functions.insert("color".into(), FunctionGraph::input("amount", ValueType::Float4));
source.exposed.push(materialcraft_engine::core::ExposedParameter {
description: String::new(),
editor: None,
clamp: false,
step: None,
id: "amount".into(),
label: "Amount".into(),
group: String::new(),
default: Value::Float4([0.2; 4]),
min: 0.0,
max: 1.0,
options: Vec::new(),
});
let output = source.add_node("output", [200.0, 0.0]);
source.connect(color, "output", output, "input").unwrap();
let dimensions = source.add_node("value_processor", [0.0; 2]);
source.node_mut(dimensions).unwrap().params.insert("function".into(), Value::Function(Box::new(FunctionGraph::input("$size", ValueType::Float2))));
let size_output = source.add_node("output", [200.0, 200.0]);
source.node_mut(size_output).unwrap().params.insert("identifier".into(), Value::Text("dimensions".into()));
source.connect(dimensions, "output", size_output, "input").unwrap();
let mut parent = Graph::new("Parent");
parent.size = [6, 5];
let owner = parent.add_node("graph_instance", [0.0; 2]);
parent.node_mut(owner).unwrap().params.insert("graph".into(), Value::Text("Source".into()));
let mut package = Package::new("Instances");
package.graphs = vec![parent, source];
let mut session = Session::new(package);
session.preview_size = None;
command(&mut session, "graph.node.function", json!({"id": owner, "param": "amount", "function": FunctionGraph::constant(Value::Float4([0.75; 4]))}));
let result = session.cook();
assert_eq!(result.nodes[&owner].error, None);
assert!(result.nodes[&owner].outputs.iter().any(|output| output.as_value() == Some(&Value::Float2([64.0, 32.0]))));
assert!((result.image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6);
assert_eq!((result.image(owner, 0).unwrap().w, result.image(owner, 0).unwrap().h), (64, 32));
assert!(!session.graph().unwrap().node(owner).unwrap().params.contains_key("amount"));
let bytes = formats::sbs::write_sbs(&session.pkg).unwrap();
let loaded = formats::sbs::read_sbs(&bytes, "instance.sbs", &|_| None).unwrap();
let mut reopened = Session::new(loaded.pkg);
let owner = reopened.graph().unwrap().nodes[0].id;
assert!((reopened.cook().image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6);
}
#[test]
fn color_boolean_enum_and_text_parameters_use_typed_function_outputs() {
let mut session = new_session();
session.preview_size = Some(16);
for (definition, parameter, value) in [
("uniform", "color", Value::Float4([0.2, 0.4, 0.6, 1.0])),
("uniform", "color_mode", Value::Bool(false)),
("blend", "mode", Value::Int(2)),
("text", "text", Value::Text("Original".into())),
] {
let owner = node(&mut session, definition);
command(&mut session, "graph.node.function", json!({"id": owner, "param": parameter, "function": FunctionGraph::constant(value.clone())}));
let result = &session.cook().nodes[&owner];
assert_eq!(result.error, None, "{parameter}");
let expected = materialcraft_engine::nodes::find(definition).unwrap().param(parameter).unwrap().default.coerce_json(&json!(value)).unwrap();
assert_eq!(result.parameters[parameter], expected);
}
let owner = node(&mut session, "uniform");
command(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": FunctionGraph::constant(Value::Float(0.5))}));
assert!(session.cook().nodes[&owner].error.as_ref().unwrap().contains("Float4"));
let bitmap = node(&mut session, "bitmap");
assert!(execute(&mut session, "graph.node.function", &json!({"id": bitmap, "param": "resource"})).is_err());
}
#[test]
fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensions() {
let mut session = new_session();
session.preview_size = Some(16);
let foreground = node(&mut session, "uniform");
command(&mut session, "graph.node.base", json!({"id": foreground, "sizeMode": "absolute", "size": [7, 6]}));
let background = node(&mut session, "uniform");
command(&mut session, "graph.node.base", json!({"id": background, "sizeMode": "absolute", "size": [5, 5]}));
let blend = node(&mut session, "blend");
session.graph_mut().unwrap().connect(foreground, "output", blend, "foreground").unwrap();
session.graph_mut().unwrap().connect(background, "output", blend, "background").unwrap();
command(
&mut session,
"graph.node.function",
json!({"id": blend, "param": "outputsize", "base": true, "function": FunctionGraph::constant(Value::Int2([1, 0]))}),
);
assert_eq!(session.cook().nodes[&blend].base.size, [64, 32]);
let blur = NodeId(command(&mut session, "graph.node.add", json!({"def": "blur", "connectFrom": {"node": blend}}))["id"].as_u64().unwrap());
command(
&mut session,
"graph.node.function",
json!({"id": blur, "param": "outputsize", "base": true, "function": FunctionGraph::constant(Value::Int2([-1, 0]))}),
);
command(&mut session, "graph.node.disable", json!({"ids": [blur], "disabled": true}));
let output = NodeId(command(&mut session, "graph.node.add", json!({"def": "output", "connectFrom": {"node": blur}}))["id"].as_u64().unwrap());
assert_eq!(session.cook().nodes[&output].base.size, [64, 32]);
command(&mut session, "graph.node.disable", json!({"ids": [blend], "disabled": true}));
let cooked = session.cook();
let image = cooked.image(blend, 0).unwrap();
assert_eq!((image.w, image.h), (16, 16));
assert_eq!(cooked.nodes[&blend].base.size, [32, 32]);
assert_eq!(cooked.nodes[&output].base.size, [32, 32]);
}
#[test]
fn setting_a_base_literal_keeps_inheritance_and_removes_only_its_driver() {
use materialcraft_engine::core::{BaseParameter, ParameterInheritance};
let mut session = new_session();
let owner = node(&mut session, "uniform");
command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "format", "mode": "constant"}));
command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "mode": "constant"}));
session.selection.clear();
command(&mut session, "graph.node.base", json!({"id": owner, "param": "format", "value": 3}));
let base = &session.graph().unwrap().node(owner).unwrap().base;
assert_eq!(BaseParameter::Format.inheritance(base), ParameterInheritance::RelativeToInput);
assert!(!base.functions.contains_key(&BaseParameter::Format));
assert!(base.functions.contains_key(&BaseParameter::OutputSize));
}
#[test]
fn malformed_literals_do_not_change_a_native_parameter_functions_expected_type() {
let mut session = new_session();
session.preview_size = Some(16);
let owner = node(&mut session, "blur");
session.graph_mut().unwrap().node_mut(owner).unwrap().params.insert("intensity".into(), Value::Text("invalid".into()));
command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "function": FunctionGraph::constant(Value::Float(2.0))}));
let result = &session.cook().nodes[&owner];
assert_eq!(result.error, None);
assert_eq!(result.parameters["intensity"], Value::Float(2.0));
}
#[test]
fn input_value_default_functions_follow_the_selected_value_type() {
let mut session = new_session();
session.preview_size = Some(16);
let owner = node(&mut session, "input_value");
session.selection.clear();
command(&mut session, "graph.node.param", json!({"id": owner, "param": "default", "value": Value::Int2([3, 5])}));
command(&mut session, "graph.node.function", json!({"id": owner, "param": "default", "mode": "constant"}));
let info = command(&mut session, "graph.node.parameterInfo", json!({"id": owner, "param": "default"}));
assert_eq!(info["expectedType"], "Integer2");
assert!(info["warnings"].as_array().unwrap().is_empty());
let result = &session.cook().nodes[&owner];
assert_eq!(result.error, None);
assert_eq!(result.outputs[0].as_value(), Some(&Value::Int2([3, 5])));
}
+35 -23
View File
@@ -91,26 +91,35 @@ fn package_save_and_open_round_trip() {
let _ = std::fs::remove_dir_all(&dir);
}
/// `file.export` `size` is the larger side in pixels; 0 means the graph's size and the proportions are kept
/// `file.export` `size` is the larger side in pixels or [width, height]; 0 means the graph's size and the proportions are kept
#[test]
fn export_size_keeps_proportions_and_clamps() {
use materialcraft_engine::{ExportRequest, ExportSize};
let mut s = sample_session();
s.pkg.graphs[0].size = [7, 6];
let dims = |s: &Session, size: Value| {
let (gi, ext, pattern, depth, size) = materialcraft_engine::file_cmds::export_params(s, &json!({"size": size})).unwrap();
let files = materialcraft_engine::file_cmds::export_outputs(s, gi, &ext, &pattern, depth, size).unwrap();
let request = ExportRequest::from_params(s, &json!({"size": size})).unwrap();
let files = materialcraft_engine::file_cmds::export_outputs(s, &request).unwrap();
files.iter().map(|f| materialcraft_formats::decode(&f.bytes, false).unwrap()).map(|i| (i.w, i.h)).collect::<Vec<_>>()
};
let parsed = |s: &Session, size: Value| ExportRequest::from_params(s, &json!({"size": size})).map(|request| request.size);
for size in [json!(0), json!(null)] {
assert!(dims(&s, size).iter().all(|d| *d == (128, 64)));
}
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 16)));
let parsed = |size: Value| materialcraft_engine::file_cmds::export_params(&s, &json!({"size": size})).unwrap().4;
assert_eq!(parsed(json!(0)), None);
assert_eq!(parsed(json!(u64::MAX)), Some(u32::MAX));
assert!(dims(&s, json!([16, 100])).iter().all(|d| *d == (16, 64)), "each side rounds down to a power of two");
assert_eq!(parsed(&s, json!(0)).unwrap(), None);
assert_eq!(parsed(&s, json!(u64::MAX)).unwrap(), Some(ExportSize::LargerSide(u32::MAX)));
assert_eq!(parsed(&s, json!([1, u64::MAX])).unwrap(), Some(ExportSize::Exact([1, u32::MAX])));
for invalid in [json!("large"), json!([64]), json!([64, "wide"]), json!([64, 64, 64])] {
assert!(parsed(&s, invalid.clone()).is_err(), "{invalid}");
}
s.pkg.graphs[0].size = [u32::MAX, u32::MAX];
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32)));
assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (16, 8192)), "sides clamp to 16..8192");
}
/// A scratch folder for one test, removed when dropped
@@ -252,23 +261,26 @@ fn panic_hunt() {
#[test]
fn dynamic_parameters_follow_graph_inputs() {
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "empty"}));
let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}}))["id"].as_u64().unwrap();
run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}}));
let f = json!({"nodes": [{"id": 1, "op": "get_float1", "value": {"t": "text", "v": "level"}}], "output": 1});
run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f}));
s.cook();
let mean = |s: &Session| s.cooked.image(materialcraft_engine::core::NodeId(u), 0).unwrap().mean()[0];
assert!((mean(&s) - 0.25).abs() < 1e-4, "{}", mean(&s));
run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75}));
s.cook();
assert!((mean(&s) - 0.75).abs() < 1e-4);
// Text parameters can't take functions; removing restores the plain value
assert!(execute(&mut s, "graph.node.function", &json!({"id": u, "param": "nope"})).is_err());
run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "remove": true}));
s.cook();
assert!((mean(&s) - 0.5).abs() < 0.05);
use materialcraft_engine::core::{FunctionGraph, NodeId, Value, ValueType};
let mut session = sample_session();
run(&mut session, "file.new", json!({"template": "empty"}));
let owner = NodeId(run(&mut session, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}}))["id"].as_u64().unwrap());
run(&mut session, "graph.exposed.add", json!({"id": "level", "default": Value::Float4([0.25; 4])}));
let function = FunctionGraph::input("level", ValueType::Float4);
run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": function}));
let mean = session.cook().image(owner, 0).unwrap().mean()[0];
assert!((mean - 0.25).abs() < 1e-4, "{mean}");
run(&mut session, "graph.exposed.set", json!({"id": "level", "value": Value::Float4([0.75; 4])}));
let mean = session.cook().image(owner, 0).unwrap().mean()[0];
assert!((mean - 0.75).abs() < 1e-4);
// Removing the function restores the plain value
assert!(execute(&mut session, "graph.node.function", &json!({"id": owner, "param": "nope"})).is_err());
run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "remove": true}));
let mean = session.cook().image(owner, 0).unwrap().mean()[0];
assert!((mean - 0.5).abs() < 0.05);
}
#[test]
@@ -0,0 +1,27 @@
//! An isolated catalog fixture shared by the library unit and integration tests.
use materialcraft_core::{Graph, Package};
use materialcraft_engine::{NodeLibrary, Session};
use std::sync::{Arc, OnceLock};
/// Load only the embedded functions, independent of the installed library directory.
pub fn library() -> Arc<NodeLibrary> {
static LIBRARY: OnceLock<Arc<NodeLibrary>> = OnceLock::new();
LIBRARY
.get_or_init(|| {
let read = materialcraft_formats::sbs::read_sbs(include_bytes!("../../../../assets/sbs/functions.sbs"), "sbs://functions.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
let mut library = NodeLibrary::default();
library.packages.insert("sbs://functions.sbs".into(), Arc::new(read.pkg));
Arc::new(library)
})
.clone()
}
/// Start an empty material graph with the isolated bundled library.
#[allow(dead_code)]
pub fn session() -> Session {
let mut package = Package::new("Library tests");
package.graphs.push(Graph::new("Material"));
Session::with_library(package, library())
}
+1
View File
@@ -13,3 +13,4 @@ materialcraft-core = { workspace = true }
materialcraft-image = { workspace = true }
materialcraft-nodes = { workspace = true }
serde_json = { workspace = true }
serde = { workspace = true }
+10 -4
View File
@@ -94,14 +94,19 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, va
let mut pending = vec![graph.as_ref()];
while let Some(graph) = pending.pop() {
serde_json::to_string(graph).unwrap_or_default().hash(&mut hasher);
for function in &graph.nodes {
match &function.source {
for function_node in &graph.nodes {
// Resolved call defaults are omitted from graph serialization
if let Some(instance) = &function_node.instance {
serde_json::to_string(&instance.defaults).unwrap_or_default().hash(&mut hasher);
}
match &function_node.source {
Some(Ok(source)) => pending.push(source.as_ref()),
Some(Err(error)) => error.hash(&mut hasher),
None => {}
}
if (function.op.starts_with("get_") || function.op == "isdefined")
&& let Some(Value::Text(name)) = &function.value
if (function_node.op.starts_with("get_") || function_node.op == "isdefined")
&& let Some(Value::Text(name)) = &function_node.value
{
names.insert(name.as_str());
}
@@ -124,5 +129,6 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, va
name.hash(&mut hasher);
variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher);
}
hasher.finish()
}
+1 -1
View File
@@ -49,7 +49,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
}
let Some(node) = prepared.index.node(id) else { continue };
let result = cook_node(package, graph_index, graph, &prepared, node, &cooked, &variables, options, cache);
let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache);
cooked.nodes.insert(id, result);
}
cooked.ms = (now_ms() - started_ms) as f32;
+1
View File
@@ -73,6 +73,7 @@ pub(crate) fn cook_instance(
o.environment = opts.environment;
o.parent_tiling = Some(base.tiling);
o.parent_pixel_ratio = Some(base.pixel_ratio);
o.parent_base = Some(base);
o.registry = Some(registry);
o.resource_root = Some(root_resource);
o.max_size = opts.max_size;
+2
View File
@@ -14,6 +14,7 @@ mod node_result;
mod node_size;
mod options;
mod parameter;
mod parameter_function;
mod port;
mod ports;
mod prepared_graph;
@@ -34,6 +35,7 @@ pub use node_size::node_size;
pub use options::Options;
pub use port::Port;
pub use ports::{identifier, instance_graph, ports, ports_with_connections};
pub use resolved_base_parameters::ResolvedBaseParameters;
pub use resource_decoder::ResourceDecoder;
pub use time::now_ms;
pub use value_input_label::value_input_label;
+80 -56
View File
@@ -1,4 +1,4 @@
use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, node_size, now_ms};
use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, now_ms};
use crate::{
cache_key::{graph_tree_hash_with_registry, hash_of, image_key, variable_key},
graph_instance::cook_instance,
@@ -6,7 +6,7 @@ use crate::{
prepared_graph::PreparedGraph,
value_execution::evaluate_value,
};
use materialcraft_core::{Graph, Node, Package, Value};
use materialcraft_core::{Node, Package, Value};
use materialcraft_image::{Image, Kind};
use materialcraft_nodes::{CookContext, find};
use std::{
@@ -25,27 +25,27 @@ fn lock(cache: &Mutex<Cache>) -> std::sync::MutexGuard<'_, Cache> {
}
pub(crate) fn cook_node(
pkg: &Package,
gi: usize,
graph: &Graph,
package: &Package,
graph_index: usize,
prepared: &PreparedGraph<'_>,
node: &Node,
done: &Cooked,
vars: &BTreeMap<String, Value>,
opts: &Options,
cooked: &Cooked,
graph_variables: &BTreeMap<String, Value>,
options: &Options,
cache: &Mutex<Cache>,
) -> NodeResult {
let (in_ports, out_ports) = prepared.ports(node.id);
let def = find(&node.def);
let (input_ports, output_ports) = prepared.ports(node.id);
let definition = find(&node.def);
// Gather inputs by port order, with their keys
let mut inputs = Vec::new();
let mut incoming = Vec::new();
let mut input_keys = Vec::new();
let mut variables = std::borrow::Cow::Borrowed(vars);
let mut variables = std::borrow::Cow::Borrowed(graph_variables);
let mut input_error = None;
for port in in_ports {
for port in input_ports {
let source = prepared.index.input_of(node.id, &port.id).and_then(|connection| {
let result = done.nodes.get(&connection.from)?;
let result = cooked.nodes.get(&connection.from)?;
let index = prepared.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?;
Some((result.outputs.get(index)?, result.key ^ hash_of(&index)))
});
@@ -80,76 +80,98 @@ pub(crate) fn cook_node(
incoming.push(output);
}
let base = prepared.base_parameters(node);
if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map") {
let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1);
variables.to_mut().insert("$tiling".into(), Value::Int(tiling));
variables.to_mut().insert("$pixelratio".into(), Value::Int(base.pixel_ratio));
let input_base = prepared.input_base(node.id, cooked);
let (mut base, base_values, base_error) = match crate::resolved_base_parameters::evaluate(&node.base, input_base, prepared.parent_base, &variables) {
Ok((base, values)) => (base, values, None),
Err(error) => (crate::ResolvedBaseParameters::resolve(&node.base, input_base, prepared.parent_base), BTreeMap::new(), Some(error)),
};
if node.disabled
&& let Some(input) = input_base
{
base = input;
}
let vars = &variables;
let first = prepared.first_input_size(node.id);
let (w, h) = node_size(graph, def, node, first, opts.max_size);
let fail = |msg: String, key: u64| NodeResult {
outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]),
error: Some(msg),
let (w, h) = crate::node_size::limit(base.size, options.max_size);
let fail = |message: String, key: u64| NodeResult {
base,
base_values: base_values.clone(),
parameters: BTreeMap::new(),
outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); output_ports.len().max(1)]),
error: Some(message),
ms: 0.0,
key,
cached: false,
};
if let Some(error) = base_error {
return fail(error, 0);
}
if let Some(error) = input_error {
return fail(error, 0);
}
let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32);
let params = match resolve_parameters(node, def, vars, seed, [w, h]) {
if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map") {
base.variables(variables.to_mut());
}
let variables = &variables;
let seed = base.seed;
let mut parameters = match resolve_parameters(package, node, definition, variables, seed, base.size) {
Ok(parameters) => parameters,
Err(error) => return fail(error, 0),
};
let tile = base.tiling[0] && base.tiling[1];
// Input nodes read the caller's image for their identifier
let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten();
let res_hash = match params.get("resource") {
Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()),
let input_image = node.def.starts_with("input_").then(|| options.inputs.get(&identifier(node))).flatten();
let resource_hash = match parameters.get("resource") {
Some(Value::Text(name)) => package.resource(name).map_or(0, |r| r.bytes.content_hash()),
_ => 0,
};
let registry = opts.registry.unwrap_or(pkg);
let sub_hash = if node.def == "graph_instance" {
crate::graph_instance::resolve(registry, pkg, node).map_or(0, |(source, index, _)| graph_tree_hash_with_registry(registry, source, index))
let registry = options.registry.unwrap_or(package);
let subgraph_hash = if node.def == "graph_instance" {
crate::graph_instance::resolve(registry, package, node).map_or(0, |(source, index, _)| graph_tree_hash_with_registry(registry, source, index))
} else {
0
};
let key = hash_of(&(
&node.def,
serde_json::to_string(&params).unwrap_or_default(),
(w, h, seed, tile, node.disabled, base.tiling, base.pixel_ratio),
serde_json::to_string(&parameters).unwrap_or_default(),
(w, h, seed, tile, node.disabled, base.size, base.format, base.tiling, base.pixel_ratio, base.pixel_size.map(f32::to_bits)),
&input_keys,
res_hash,
sub_hash,
resource_hash,
subgraph_hash,
// A cached graph instance includes results evaluated with its host environment
(node.def == "graph_instance").then(|| serde_json::to_string(&opts.environment).unwrap_or_default()),
input_img.map(|image| image_key(image, cache)),
variable_key(node, &params, vars),
(node.def == "graph_instance").then(|| serde_json::to_string(&options.environment).unwrap_or_default()),
input_image.map(|image| image_key(image, cache)),
variable_key(node, &parameters, variables),
));
if let Some(v) = lock(cache).get(key) {
return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true };
if let Some(outputs) = lock(cache).get(key) {
parameters.retain(|_, value| materialcraft_core::ValueType::of(value).is_some());
return NodeResult { base, base_values, parameters, outputs, error: None, ms: 0.0, key, cached: true };
}
let t0 = now_ms();
let started_ms = now_ms();
let result: Result<Vec<NodeOutput>, String> = if node.disabled {
let output = incoming.iter().find_map(|output| *output).cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4])));
Ok(vec![output; out_ports.len().max(1)])
let input = if let Some(primary) = definition.and_then(|definition| definition.primary_input) {
input_ports.iter().position(|port| port.id == primary).and_then(|index| incoming.get(index)).copied().flatten()
} else {
incoming.iter().find_map(|output| *output)
};
let output = input.cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4])));
Ok(vec![output; output_ports.len().max(1)])
} else if node.def == "input_value" {
let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0));
let value = variables.get(&identifier(node)).or_else(|| parameters.get("default")).cloned().unwrap_or(Value::Float(0.0));
Ok(vec![NodeOutput::Value(value)])
} else if node.def == "value_processor" {
evaluate_value(&params, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)])
evaluate_value(&parameters, variables, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)])
} else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) {
incoming.first().copied().flatten().cloned().map(|output| vec![output]).ok_or("missing value input".into())
} else if let Some(image) = input_img {
} else if let Some(image) = input_image {
let image = image.resize(w, h, tile);
let image = if node.def == "input_grayscale" { image.to_gray() } else { image };
@@ -159,21 +181,23 @@ pub(crate) fn cook_node(
Err(format!("unsupported node `{name}`"))
} else if node.def == "graph_instance" {
cook_instance(pkg, gi, node, in_ports, out_ports, &incoming, &params, (w, h), base, opts, cache)
} else if let Some(definition) = def {
let context = CookContext { w, h, seed, tile, inputs: &inputs, params: &params, resource: opts.resource, vars };
cook_instance(package, graph_index, node, input_ports, output_ports, &incoming, &parameters, (w, h), base, options, cache)
} else if let Some(definition) = definition {
let context = CookContext { w, h, seed, tile, inputs: &inputs, params: &parameters, resource: options.resource, vars: variables };
(definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::Image).collect())
} else {
Err(format!("unknown node `{}`", node.def))
};
// Cooked values serve parameter controls; authoring graphs stay in the document
parameters.retain(|_, value| materialcraft_core::ValueType::of(value).is_some());
match result {
Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => {
let v = Arc::new(imgs);
lock(cache).put(key, v.clone());
NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false }
Ok(outputs) if outputs.len() == output_ports.len().max(1) || output_ports.is_empty() => {
let outputs = Arc::new(outputs);
lock(cache).put(key, outputs.clone());
NodeResult { base, base_values, parameters, outputs, error: None, ms: (now_ms() - started_ms) as f32, key, cached: false }
}
Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key),
Err(e) => fail(e, key),
Ok(outputs) => fail(format!("`{}` made {} images for {} outputs", node.def, outputs.len(), output_ports.len()), key),
Err(error) => fail(error, key),
}
}
+4
View File
@@ -4,6 +4,10 @@ use std::sync::Arc;
/// One node's cooked result
#[derive(Clone, Debug)]
pub struct NodeResult {
pub base: crate::ResolvedBaseParameters,
pub base_values: std::collections::BTreeMap<materialcraft_core::BaseParameter, materialcraft_core::Value>,
/// Evaluated scalar and vector parameters, excluding authoring graphs and curves
pub parameters: std::collections::BTreeMap<String, materialcraft_core::Value>,
/// One image per output port (empty when the cook failed)
pub outputs: Arc<Vec<NodeOutput>>,
pub error: Option<String>,
+16 -26
View File
@@ -1,33 +1,23 @@
use materialcraft_core::{Graph, Node, SizeMode};
use materialcraft_core::{Graph, Node};
use materialcraft_nodes::NodeDefinition;
/// Output size of `node` given its first connected input's size
pub fn node_size(graph: &Graph, def: Option<&NodeDefinition>, node: &Node, input: Option<(u32, u32)>, max: Option<u32>) -> (u32, u32) {
let parent = graph.size_px();
let (bw, bh) = match node.base.size_mode {
SizeMode::Absolute => {
let s = |l: i32| 1u32 << l.clamp(4, 13);
(s(node.base.size[0]), s(node.base.size[1]))
}
mode => {
let base = match (mode, input, def.is_some_and(|d| d.generator)) {
(SizeMode::RelativeToInput, Some(i), false) => i,
_ => (parent[0], parent[1]),
};
/// Literal output size; cooking also evaluates any attached parameter function
pub fn node_size(graph: &Graph, definition: Option<&NodeDefinition>, node: &Node, input: Option<(u32, u32)>, maximum: Option<u32>) -> (u32, u32) {
let parent = crate::ResolvedBaseParameters { size: graph.size_px(), ..Default::default() };
let input = input
.filter(|_| !definition.is_some_and(|definition| definition.generator))
.map(|(width, height)| crate::ResolvedBaseParameters { size: [width, height], ..parent });
let resolved = crate::ResolvedBaseParameters::resolve(&node.base, input, parent);
let sh = |v: u32, o: i32| {
let v = v as f64 * 2f64.powi(o.clamp(-12, 12));
v.round().clamp(16.0, 8192.0) as u32
};
(sh(base.0, node.base.size[0]), sh(base.1, node.base.size[1]))
}
};
limit(resolved.size, maximum)
}
match max {
Some(m) if bw.max(bh) > m => {
let k = m as f64 / bw.max(bh) as f64;
(((bw as f64 * k).round() as u32).max(1), ((bh as f64 * k).round() as u32).max(1))
pub(crate) fn limit([width, height]: [u32; 2], maximum: Option<u32>) -> (u32, u32) {
match maximum {
Some(maximum) if width.max(height) > maximum => {
let scale = f64::from(maximum.max(1)) / f64::from(width.max(height));
(((f64::from(width) * scale).round() as u32).max(1), ((f64::from(height) * scale).round() as u32).max(1))
}
_ => (bw, bh),
_ => (width, height),
}
}
+2
View File
@@ -8,6 +8,7 @@ pub struct Options<'a> {
pub environment: materialcraft_core::EvaluationEnvironment,
pub parent_tiling: Option<[bool; 2]>,
pub parent_pixel_ratio: Option<i32>,
pub parent_base: Option<crate::ResolvedBaseParameters>,
/// Cap on the larger side of every node's output (previews); `None` = full size
pub max_size: Option<u32>,
/// Cook only these nodes and what they depend on (`None` = the whole graph)
@@ -34,6 +35,7 @@ impl<'a> Options<'a> {
environment: Default::default(),
parent_tiling: None,
parent_pixel_ratio: None,
parent_base: None,
max_size: None,
only: None,
inputs: BTreeMap::new(),
+36 -41
View File
@@ -1,59 +1,54 @@
use materialcraft_core::{Node, Value};
use materialcraft_nodes::{NodeDefinition, clamp_params, resolve_params};
use materialcraft_core::{Node, Package, Value, ValueType};
use materialcraft_nodes::{NodeDefinition, ParameterDescriptor, clamp_params, resolve_params};
use std::collections::BTreeMap;
pub(crate) fn resolve_parameters(
package: &Package,
node: &Node,
def: Option<&NodeDefinition>,
vars: &BTreeMap<String, Value>,
definition: Option<&NodeDefinition>,
variables: &BTreeMap<String, Value>,
seed: u32,
size: [u32; 2],
) -> Result<BTreeMap<String, Value>, String> {
// Parameters: defaults, overrides, then bindings to exposed inputs
let mut params = match def {
Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params),
_ => node.params.clone(),
let mut parameters = match definition {
Some(definition) if node.def != "graph_instance" => resolve_params(definition, &node.params),
_ => {
let mut parameters = node.instance.as_ref().map(|instance| instance.defaults.clone()).unwrap_or_default();
parameters.extend(node.params.clone());
parameters
}
};
for (param, exposed) in &node.bindings {
if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param))
&& let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default())
for parameter in node.bindings.keys().chain(node.functions.keys()) {
if !parameters.contains_key(parameter)
&& let Some(descriptor) = ParameterDescriptor::for_node(package, node, parameter)
{
params.insert(param.clone(), c);
parameters.insert(parameter.clone(), descriptor.default);
}
}
// Dynamic parameters: functions of the graph's inputs, evaluated once per cook
for (param, f) in &node.functions {
let Some(cur) = params.get(param) else { continue };
match materialcraft_nodes::function::compile(f, seed) {
Ok(prog) => {
let context = materialcraft_nodes::function::EvaluationContext {
scope: Default::default(),
position: [0.5; 2],
size: size.map(|side| side as f32),
images: &[],
tile: true,
variables: vars,
};
let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) {
Ok(value) => value,
Err(error) => return Err(format!("function of `{param}`: {error}")),
};
if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) {
params.insert(param.clone(), c);
}
}
Err(e) => return Err(format!("function of `{param}`: {e}")),
for (parameter, exposed) in &node.bindings {
if let (Some(value), Some(current)) = (variables.get(exposed), parameters.get(parameter))
&& let Some(coerced) = current.coerce_json(&serde_json::to_value(value).unwrap_or_default())
{
parameters.insert(parameter.clone(), coerced);
}
}
// Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook)
if let Some(d) = def
for (parameter, function) in &node.functions {
let current = parameters.get(parameter).ok_or_else(|| format!("unknown function parameter `{parameter}`"))?;
let expected = ValueType::of(current).ok_or_else(|| format!("parameter `{parameter}` cannot have a function"))?;
let value =
crate::parameter_function::evaluate(function, expected, variables, seed, size).map_err(|error| format!("function of `{parameter}`: {error}"))?;
let value = current.coerce_json(&serde_json::to_value(value).unwrap_or_default()).ok_or_else(|| format!("invalid function value for `{parameter}`"))?;
parameters.insert(parameter.clone(), value);
}
// Catalog limits keep values from files and functions within safe cook bounds
if let Some(definition) = definition
&& node.def != "graph_instance"
{
clamp_params(d, &mut params);
clamp_params(definition, &mut parameters);
}
Ok(params)
Ok(parameters)
}
+25
View File
@@ -0,0 +1,25 @@
use materialcraft_core::{FunctionGraph, Value, ValueType};
use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile};
use std::collections::BTreeMap;
pub(crate) fn evaluate(function: &FunctionGraph, expected: ValueType, variables: &BTreeMap<String, Value>, seed: u32, size: [u32; 2]) -> Result<Value, String> {
let program = compile(function, seed)?;
if program.output_type() != expected as u32 {
return Err(format!("output must be {}", expected.label()));
}
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images: &[], tile: true, variables };
let value = program.evaluate(&context, &mut EvaluationState::default())?;
let finite = match &value {
Value::Float(value) => value.is_finite(),
Value::Float2(values) => values.iter().all(|value| value.is_finite()),
Value::Float3(values) => values.iter().all(|value| value.is_finite()),
Value::Float4(values) | Value::Color(values) => values.iter().all(|value| value.is_finite()),
_ => true,
};
if !finite {
return Err("function returned a non-finite value".into());
}
Ok(value)
}
+22 -34
View File
@@ -6,9 +6,7 @@ use std::collections::BTreeMap;
pub(crate) struct PreparedGraph<'a> {
pub index: GraphIndex<'a>,
pub order: Vec<NodeId>,
nominal_sizes: BTreeMap<NodeId, (u32, u32)>,
base_parameters: BTreeMap<NodeId, crate::resolved_base_parameters::ResolvedBaseParameters>,
parent_base: crate::resolved_base_parameters::ResolvedBaseParameters,
pub parent_base: crate::resolved_base_parameters::ResolvedBaseParameters,
ports: BTreeMap<NodeId, (Vec<Port>, Vec<Port>)>,
}
@@ -26,42 +24,32 @@ impl<'a> PreparedGraph<'a> {
.collect();
let parent_base = crate::resolved_base_parameters::ResolvedBaseParameters::graph(graph, options);
let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new(), base_parameters: BTreeMap::new(), parent_base };
for &id in &prepared.order {
let Some(node) = prepared.index.node(id) else { continue };
let input = prepared.first_input_size(id);
let nominal = if node.disabled {
input.unwrap_or_else(|| crate::node_size(graph, materialcraft_nodes::find(&node.def), node, None, None))
} else {
crate::node_size(graph, materialcraft_nodes::find(&node.def), node, input, None)
};
prepared.nominal_sizes.insert(id, nominal);
let input_base = prepared.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| {
let connection = prepared.index.input_of(id, &port.id)?;
prepared.base_parameters.get(&connection.from).copied()
});
let base = crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, input_base, parent_base);
prepared.base_parameters.insert(id, base);
}
prepared
Self { index, order, ports, parent_base }
}
pub fn first_input_size(&self, id: NodeId) -> Option<(u32, u32)> {
self.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| {
let connection = self.index.input_of(id, &port.id)?;
self.nominal_sizes.get(&connection.from).copied()
})
pub fn input_base(&self, id: NodeId, cooked: &crate::Cooked) -> Option<crate::ResolvedBaseParameters> {
let node = self.index.node(id)?;
let definition = materialcraft_nodes::find(&node.def);
let primary = definition.and_then(|definition| definition.primary_input);
let mut base = self
.ports(id)
.0
.iter()
.filter(|port| port.kind != materialcraft_nodes::PortKind::Value && primary.is_none_or(|primary| port.id == primary))
.find_map(|port| {
let connection = self.index.input_of(id, &port.id)?;
cooked.nodes.get(&connection.from).map(|result| result.base)
})?;
// Only bypassed generators take their image dimensions from the input
if !node.disabled && definition.is_some_and(|definition| definition.generator) {
base.size = self.parent_base.size;
}
Some(base)
}
pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) {
self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice()))
}
pub fn base_parameters(&self, node: &materialcraft_core::Node) -> crate::resolved_base_parameters::ResolvedBaseParameters {
self.base_parameters
.get(&node.id)
.copied()
.unwrap_or_else(|| crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, None, self.parent_base))
}
}
+90 -7
View File
@@ -1,23 +1,106 @@
use materialcraft_core::{BaseParameters, Graph};
use materialcraft_core::{BaseParameter, BaseParameters, Graph, OutputFormat, ParameterInheritance, Value};
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
pub(crate) struct ResolvedBaseParameters {
#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolvedBaseParameters {
pub size: [u32; 2],
pub seed: u32,
pub format: OutputFormat,
pub tiling: [bool; 2],
pub pixel_ratio: i32,
pub pixel_size: [f32; 2],
}
impl ResolvedBaseParameters {
pub fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self {
pub(crate) fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self {
let parent = options.parent_base;
Self {
size: parent.map_or_else(|| graph.size_px(), |base| base.size),
seed: parent.map_or((graph.seed as u32).wrapping_mul(0x9e37_79b9), |base| base.seed),
format: parent.map_or(graph.format, |base| base.format),
tiling: graph.tiling_mode.resolve(graph.tiling, options.parent_tiling, options.parent_tiling.unwrap_or(graph.tiling)),
pixel_ratio: graph.pixel_ratio_mode.resolve(graph.pixel_ratio, options.parent_pixel_ratio, options.parent_pixel_ratio.unwrap_or(graph.pixel_ratio)),
pixel_size: parent.map_or([1.0; 2], |base| base.pixel_size),
}
}
pub fn resolve(base: &BaseParameters, input: Option<Self>, parent: Self) -> Self {
pub(crate) fn resolve(base: &BaseParameters, input: Option<Self>, parent: Self) -> Self {
let size_base = BaseParameter::OutputSize.inheritance(base).resolve([1; 2], input.map(|base| base.size), parent.size);
let size = std::array::from_fn(|axis| (f64::from(size_base[axis]) * 2f64.powi(base.size[axis].clamp(-12, 13))).round().clamp(16.0, 8192.0) as u32);
let inherited_seed = base.seed_mode.resolve(0, input.map(|base| base.seed), parent.seed);
let inherited_pixel_size = base.pixel_size_mode.resolve([1.0; 2], input.map(|base| base.pixel_size), parent.pixel_size);
Self {
tiling: base.tiling_mode.resolve(base.tiling, input.map(|input| input.tiling), parent.tiling),
pixel_ratio: base.pixel_ratio_mode.resolve(base.pixel_ratio, input.map(|input| input.pixel_ratio), parent.pixel_ratio),
size,
seed: inherited_seed.wrapping_add(base.seed as u32),
format: BaseParameter::Format.inheritance(base).resolve(base.format, input.map(|base| base.format), parent.format),
tiling: base.tiling_mode.resolve(base.tiling, input.map(|base| base.tiling), parent.tiling),
pixel_ratio: base.pixel_ratio_mode.resolve(base.pixel_ratio, input.map(|base| base.pixel_ratio), parent.pixel_ratio),
pixel_size: std::array::from_fn(|axis| (inherited_pixel_size[axis] * base.pixel_size[axis]).clamp(f32::MIN_POSITIVE, 8192.0)),
}
}
pub(crate) fn variables(self, variables: &mut BTreeMap<String, Value>) {
variables.insert("$tiling".into(), Value::Int(i32::from(self.tiling[0]) | (i32::from(self.tiling[1]) << 1)));
variables.insert("$pixelratio".into(), Value::Int(self.pixel_ratio));
}
}
pub(crate) fn evaluate(
base: &BaseParameters,
input: Option<ResolvedBaseParameters>,
parent: ResolvedBaseParameters,
variables: &BTreeMap<String, Value>,
) -> Result<(ResolvedBaseParameters, BTreeMap<BaseParameter, Value>), String> {
if base.functions.is_empty() {
return Ok((ResolvedBaseParameters::resolve(base, input, parent), BTreeMap::new()));
}
// Evaluation mutates literals while borrowing the attached function graphs
let mut evaluated = BaseParameters {
size_mode: base.size_mode,
size: base.size,
format: base.format,
format_mode: base.format_mode,
seed: base.seed,
seed_mode: base.seed_mode,
pixel_size: base.pixel_size,
pixel_size_mode: base.pixel_size_mode,
functions: BTreeMap::new(),
tiling: base.tiling,
tiling_mode: base.tiling_mode,
pixel_ratio: base.pixel_ratio,
pixel_ratio_mode: base.pixel_ratio_mode,
};
let mut values = BTreeMap::new();
let mut variables = variables.clone();
let mut resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent);
// Size and seed establish the context used by the remaining parameter functions
for parameter in [
BaseParameter::RandomSeed,
BaseParameter::OutputSize,
BaseParameter::Format,
BaseParameter::PixelSize,
BaseParameter::PixelRatio,
BaseParameter::Tiling,
] {
if let Some(function) = base.functions.get(&parameter) {
resolved.variables(&mut variables);
let size = if parameter == BaseParameter::OutputSize && parameter.inheritance(base) != ParameterInheritance::Absolute {
parameter.inheritance(base).resolve(parent.size, input.map(|base| base.size), parent.size)
} else {
resolved.size
};
let value = crate::parameter_function::evaluate(function, parameter.value_type(), &variables, resolved.seed, size)
.map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?;
parameter.set_value(&mut evaluated, &value)?;
parameter.set_inheritance(&mut evaluated, parameter.inheritance(base));
resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent);
}
values.insert(parameter, parameter.value(&evaluated));
}
Ok((resolved, values))
}
+107 -1
View File
@@ -265,7 +265,11 @@ fn input_change_recooks_only_readers() {
value: Some(Value::Text("a".into())),
pos: [0.0; 2],
};
p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FunctionGraph { nodes: vec![get_a], output: Some(1) })));
p.graphs[0]
.node_mut(reader)
.unwrap()
.params
.insert("function".into(), Value::Function(Box::new(FunctionGraph { nodes: vec![get_a], output: Some(1), ..Default::default() })));
let cache = &Mutex::new(Cache::default());
let mut opts = Options::new(&no_res);
opts.overrides.insert("a".into(), Value::Float(0.25));
@@ -465,3 +469,105 @@ fn bound_input_image_linear_flag_change_recooks_instance() {
let third_value = third.image(inst, 0).unwrap().data[0];
assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}");
}
#[test]
fn cooked_parameters_retain_values_without_processor_graph_copies() {
let mut graph = Graph::new("Parameter results");
graph.size = [4, 4];
for _ in 0..12 {
let owner = graph.add_node("value_processor", [0.0; 2]);
let mut function = materialcraft_core::FunctionGraph::constant(Value::Float(0.25));
let constant = function.output.unwrap();
for _ in 0..32 {
function.output = Some(function.add("add", &[function.output.unwrap(), constant], None));
}
graph.node_mut(owner).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
}
let scalar = graph.add_node("uniform", [0.0; 2]);
graph.node_mut(scalar).unwrap().functions.insert("color".into(), materialcraft_core::FunctionGraph::constant(Value::Color([0.5; 4])));
let mut package = Package::new("Parameter results");
package.graphs.push(graph);
let cache = Mutex::new(Cache::default());
let results = [cook(&package, 0, &Options::new(&no_res), &cache), cook(&package, 0, &Options::new(&no_res), &cache)];
assert!(results[1].nodes.values().all(|result| result.cached));
for result in results {
for (owner, node) in &result.nodes {
assert_eq!(node.error, None);
assert!(
node.parameters.values().all(|value| materialcraft_core::ValueType::of(value).is_some()),
"cooked previews must not retain authoring graphs"
);
if *owner != scalar {
assert_eq!(result.value(*owner, 0), Some(&Value::Float(8.25)));
}
}
assert_eq!(result.nodes[&scalar].parameters.get("color"), Some(&Value::Color([0.5; 4])));
}
}
#[test]
fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() {
use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance, SizeMode, ValueType};
for definition in ["svg", "fx_map"] {
for dynamic in [false, true] {
let mut graph = Graph::new("Generator sizes");
graph.size = [6, 5];
let background = graph.add_node("uniform", [0.0; 2]);
let base = &mut graph.node_mut(background).unwrap().base;
base.size_mode = SizeMode::Absolute;
base.size = [5, 6];
base.seed = 17;
base.format = OutputFormat::F32;
base.tiling = [false, true];
base.tiling_mode = ParameterInheritance::Absolute;
base.pixel_ratio = 1;
base.pixel_ratio_mode = ParameterInheritance::Absolute;
base.pixel_size = [0.25, 0.5];
base.pixel_size_mode = ParameterInheritance::Absolute;
let generator = graph.add_node(definition, [200.0, 0.0]);
graph.node_mut(generator).unwrap().base.format_mode = ParameterInheritance::RelativeToInput;
if dynamic {
let mut function = FunctionGraph::input("$sizelog2", ValueType::Float2);
let size = function.output.unwrap();
let parent = function.add_constant(Value::Float2([6.0, 5.0]));
let difference = function.add("sub", &[size, parent], None);
function.output = Some(function.add("toint2", &[difference], None));
graph.node_mut(generator).unwrap().base.functions.insert(BaseParameter::OutputSize, function);
}
graph.connect(background, "output", generator, "background").unwrap();
let mut package = Package::new("Generator sizes");
package.graphs.push(graph);
let cache = Mutex::new(Cache::default());
let mut options = Options::new(&no_res);
options.max_size = Some(16);
let cooked = cook(&package, 0, &options, &cache);
let result = &cooked.nodes[&generator];
assert_eq!(result.error, None, "{definition}");
assert_eq!(result.base.size, [64, 32], "{definition}, dynamic: {dynamic}");
assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((16, 8)));
assert_eq!(result.base.seed, 17);
assert_eq!(result.base.format, OutputFormat::F32);
assert_eq!(result.base.tiling, [false, true]);
assert_eq!(result.base.pixel_ratio, 1);
assert_eq!(result.base.pixel_size, [0.25, 0.5]);
if !dynamic {
assert_eq!(
node_size(&package.graphs[0], materialcraft_nodes::find(definition), package.graphs[0].node(generator).unwrap(), Some((32, 64)), Some(16)),
(16, 8)
);
}
package.graphs[0].node_mut(generator).unwrap().disabled = true;
let cooked = cook(&package, 0, &options, &cache);
assert_eq!(cooked.nodes[&generator].error, None);
assert_eq!(cooked.nodes[&generator].base.size, cooked.nodes[&background].base.size);
assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((8, 16)));
}
}
}
@@ -32,11 +32,12 @@ pub(super) fn package(bytes: &[u8], source: &str) -> Result<Package, Box<dyn std
graph.exposed.iter().map(|parameter| parameter.id.as_str()).collect::<Vec<_>>().join(", ")
};
graph.attributes.description = format!("Evaluates the {} function graph. Result type: {}. Inputs: {inputs}.", graph.name, result.label());
graph.attributes.category = graph.folder.clone();
for input in &mut graph.exposed {
input.description.clear();
}
graph.attributes.author.clear();
graph.attributes.author_url.clear();
graph.attributes.user_data.clear();
graph.attributes.tags.clear();
graph.frames.clear();
graph.comments.clear();
graph.pins.clear();
@@ -10,7 +10,8 @@ fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() {
graph.attributes.author = "Source author".into();
graph.attributes.author_url = "https://example.org/source".into();
graph.attributes.user_data = "Source notes".into();
graph.attributes.tags = "Source tags".into();
graph.attributes.category = "Function".into();
graph.attributes.tags = "Maths".into();
graph.function_type = 256;
let mut body = FunctionGraph::default();
let left = body.add_constant(Value::Float(1.0));
@@ -30,7 +31,10 @@ fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() {
assert!(converted.graphs[0].attributes.author.is_empty());
assert!(converted.graphs[0].attributes.author_url.is_empty());
assert!(converted.graphs[0].attributes.user_data.is_empty());
assert!(converted.graphs[0].attributes.tags.is_empty());
assert_eq!(converted.graphs[0].attributes.category, "Function");
assert_eq!(converted.graphs[0].attributes.tags, "Maths");
assert_eq!(reopened.graphs[0].attributes.category, "Function");
assert_eq!(reopened.graphs[0].attributes.tags, "Maths");
assert_eq!(converted.graphs[0].function, reopened.graphs[0].function);
let mut restored = converted.graphs[0].function.clone().unwrap();
let original = imported.graphs[0].function.as_ref().unwrap();
@@ -64,3 +68,21 @@ fn layout_separates_nodes_and_rejects_invalid_connections_without_partial_edits(
function.nodes[0].inputs = vec![Some(9999)];
assert!(super::layout::reposition(&mut function).unwrap_err().contains("missing node"));
}
#[test]
fn conversion_preserves_empty_classification_attributes() {
let mut package = Package::new("Functions");
let mut graph = Graph::new("EmptyMetadata");
graph.folder = "Functions/Math".into();
let mut function = FunctionGraph::default();
function.output = Some(function.add_constant(Value::Float(1.0)));
graph.function = Some(function);
graph.function_type = 256;
package.graphs.push(graph);
let bytes = write_sbs(&package).unwrap();
let converted = super::convert::package(&bytes, "source.sbs").unwrap();
assert!(converted.graphs[0].attributes.category.is_empty());
assert!(converted.graphs[0].attributes.tags.is_empty());
}
+1 -2
View File
@@ -76,7 +76,6 @@ pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8
"png" => image::ImageFormat::Png,
"jpg" | "jpeg" => image::ImageFormat::Jpeg,
"tga" => image::ImageFormat::Tga,
"tif" | "tiff" => image::ImageFormat::Tiff,
"bmp" => image::ImageFormat::Bmp,
"webp" => image::ImageFormat::WebP,
"exr" => image::ImageFormat::OpenExr,
@@ -85,7 +84,7 @@ pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8
};
let float_only = matches!(fmt, image::ImageFormat::OpenExr | image::ImageFormat::Hdr);
let sixteen_ok = matches!(fmt, image::ImageFormat::Png | image::ImageFormat::Tiff);
let sixteen_ok = fmt == image::ImageFormat::Png;
let q8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let q16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
let dynimg: image::DynamicImage = if float_only {
+1 -1
View File
@@ -26,7 +26,7 @@ pub type Result<T> = std::result::Result<T, FormatError>;
pub(crate) const MAX_JSON: u64 = 64 << 20;
pub(crate) const MAX_RESOURCE: u64 = 256 << 20;
pub const EXPORT_FORMATS: &[(&str, &str)] =
&[("png", "PNG"), ("jpg", "JPEG"), ("tga", "TGA"), ("tif", "TIFF"), ("bmp", "BMP"), ("webp", "WEBP"), ("exr", "OpenEXR"), ("hdr", "Radiance HDR")];
&[("png", "PNG"), ("jpg", "JPEG"), ("tga", "TGA"), ("bmp", "BMP"), ("webp", "WEBP"), ("exr", "OpenEXR"), ("hdr", "Radiance HDR")];
pub const VECTOR_EXTENSIONS: &[&str] = &["svg"];
pub const VECTOR_FORMATS: &[(&str, &[&str])] = &[("All formats", VECTOR_EXTENSIONS), ("Scalable Vector Graphics", VECTOR_EXTENSIONS)];
pub const BITMAP_EXTENSIONS: &[&str] = &["dds", "webp", "gif", "hdr", "exr", "jpg", "jif", "jpeg", "jpe", "pgm", "png", "tif", "tiff", "tga", "targa", "bmp"];
+4
View File
@@ -110,6 +110,10 @@ mod tests {
fn manifest() -> Manifest {
let param = ExposedParameter {
description: String::new(),
editor: None,
clamp: false,
step: None,
id: "rough".into(),
label: "Roughness".into(),
group: String::new(),
+42 -81
View File
@@ -1,94 +1,52 @@
use super::sbs_value::sbs_constant;
use super::xml::{child_element, child_value, children_named};
use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, ParameterInheritance, SizeMode};
use super::{
function_graph,
sbs_value::{constant_xml, sbs_constant, to_natural_value},
sbs_writer::SbsWriter,
warnings::Warnings,
};
use materialcraft_core::{BaseParameter, BaseParameters, ParameterInheritance};
use roxmltree::Node as XmlNode;
use std::fmt::Write as _;
pub(super) fn read_base_params(params: Option<XmlNode>) -> BaseParameters {
pub(super) fn read_base_params(params: Option<XmlNode>, warnings: &mut Warnings) -> BaseParameters {
let mut base = BaseParameters::default();
for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) {
let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::<i32>().ok()).unwrap_or(1);
let inheritance = match relative_to {
0 => ParameterInheritance::Absolute,
2 => ParameterInheritance::RelativeToParent,
for element in params.into_iter().flat_map(|parameters| children_named(parameters, "parameter")) {
let Some(parameter) = child_value(element, "name").and_then(BaseParameter::named) else { continue };
let inheritance = match child_value(element, "relativeTo").unwrap_or("1") {
"0" => ParameterInheritance::Absolute,
"2" => ParameterInheritance::RelativeToParent,
_ => ParameterInheritance::RelativeToInput,
};
match child_value(param, "name") {
Some("tiling") => base.tiling_mode = inheritance,
Some("pixelratio") => base.pixel_ratio_mode = inheritance,
_ => {}
}
let Some(value) = child_element(element, "paramValue") else { continue };
let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue };
match child_value(param, "name") {
Some("outputsize") => {
base.size_mode = match relative_to {
0 => SizeMode::Absolute,
2 => SizeMode::RelativeToParent,
_ => SizeMode::RelativeToInput,
};
let limit = |log2: i32| log2.clamp(-(MAX_SIZE_LOG2 as i32), MAX_SIZE_LOG2 as i32);
base.size = [limit(value.int(0)), limit(value.int(1))];
}
Some("format") if relative_to == 0 => {
base.format = match value.int(0) {
0 => OutputFormat::U8,
1 => OutputFormat::U16,
2 => OutputFormat::F16,
3 => OutputFormat::F32,
_ => OutputFormat::Inherit,
if let Some(dynamic) = child_element(value, "dynamicValue") {
match function_graph::read(dynamic) {
Ok(function) => {
base.functions.insert(parameter, function);
}
Err(error) => warnings.add(format!("{} function: {error}", parameter.label())),
}
Some("randomseed") if relative_to == 0 => base.seed = value.int(0),
Some("tiling") => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0],
Some("pixelratio") => base.pixel_ratio = value.int(0).clamp(0, 1),
_ => {}
} else if let Some(value) = sbs_constant(value)
&& let Err(error) = parameter.set_value(&mut base, &to_natural_value(&value))
{
warnings.add(error);
}
parameter.set_inheritance(&mut base, inheritance);
}
base
}
pub(super) fn base_params_xml(base: &BaseParameters) -> String {
let mut out = String::new();
if base.size_mode != SizeMode::RelativeToInput || base.size != [0, 0] {
let relative_to = match base.size_mode {
SizeMode::Absolute => 0,
SizeMode::RelativeToInput => 1,
SizeMode::RelativeToParent => 2,
};
let [width, height] = base.size;
let _ = write!(
out,
"<parameter><name v=\"outputsize\"/><relativeTo v=\"{relative_to}\"/><paramValue><constantValueInt2 v=\"{width} {height}\"/></paramValue></parameter>"
);
}
let format = match base.format {
OutputFormat::Inherit => None,
OutputFormat::U8 => Some(0),
OutputFormat::U16 => Some(1),
OutputFormat::F16 => Some(2),
OutputFormat::F32 => Some(3),
};
if let Some(format) = format {
let _ = write!(out, "<parameter><name v=\"format\"/><relativeTo v=\"0\"/><paramValue><constantValueInt32 v=\"{format}\"/></paramValue></parameter>");
}
if base.seed != 0 {
let _ = write!(
out,
"<parameter><name v=\"randomseed\"/><relativeTo v=\"0\"/><paramValue><constantValueInt32 v=\"{}\"/></paramValue></parameter>",
base.seed
);
}
let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1);
for (name, value, inheritance, default) in [("tiling", tiling, base.tiling_mode, 3), ("pixelratio", base.pixel_ratio, base.pixel_ratio_mode, 0)] {
if inheritance == ParameterInheritance::RelativeToInput && value == default {
pub(super) fn base_params_xml(base: &BaseParameters, writer: &mut SbsWriter) -> Result<String, String> {
let mut output = String::new();
let defaults = BaseParameters::default();
for parameter in BaseParameter::ALL {
let function = base.functions.get(&parameter);
let value = parameter.value(base);
let inheritance = parameter.inheritance(base);
if function.is_none() && value == parameter.value(&defaults) && inheritance == parameter.inheritance(&defaults) {
continue;
}
@@ -97,10 +55,13 @@ pub(super) fn base_params_xml(base: &BaseParameters) -> String {
ParameterInheritance::RelativeToInput => 1,
ParameterInheritance::RelativeToParent => 2,
};
let _ = write!(
out,
"<parameter><name v=\"{name}\"/><relativeTo v=\"{relative_to}\"/><paramValue><constantValueInt32 v=\"{value}\"/></paramValue></parameter>"
);
let body = match function {
Some(function) => function_graph::write(function, writer)?,
None => constant_xml(&value).ok_or("invalid base parameter value")?,
};
let _ =
write!(output, "<parameter><name v=\"{}\"/><relativeTo v=\"{relative_to}\"/><paramValue>{body}</paramValue></parameter>", parameter.identifier());
}
out
Ok(output)
}
+14 -3
View File
@@ -8,9 +8,13 @@ use roxmltree::Node as XmlNode;
use std::fmt::Write as _;
pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) {
write_items(output, &graph.frames, &graph.comments, &graph.pins, writer);
}
pub(super) fn write_items(output: &mut String, frames: &[Frame], comments: &[Comment], pins: &[Pin], writer: &mut SbsWriter) {
output.push_str("<GUIObjects>");
for frame in &graph.frames {
for frame in frames {
let [x, y, width, height] = frame.rect.map(format_float);
let [red, green, blue] = [0, 1, 2].map(|channel| format_float(linear_to_srgb(frame.color[channel])));
let _ = write!(
@@ -24,7 +28,7 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu
);
}
for comment in &graph.comments {
for comment in comments {
let [x, y] = comment.pos.map(format_float);
let [width, height] = comment.size.map(format_float);
let _ = write!(
@@ -35,7 +39,7 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu
);
}
for pin in &graph.pins {
for pin in pins {
let [x, y] = pin.pos.map(format_float);
let _ = write!(
output,
@@ -85,3 +89,10 @@ pub(super) fn read_canvas_items(element: XmlNode, graph: &mut Graph, warnings: &
}
}
}
/// Embedded canvases use the same GUIObjects schema as document graphs.
pub(super) fn read_embedded(element: XmlNode) -> materialcraft_core::CanvasAnnotations {
let mut graph = Graph::new("embedded");
read_canvas_items(element, &mut graph, &mut Warnings::default());
materialcraft_core::CanvasAnnotations { frames: graph.frames, comments: graph.comments, pins: graph.pins }
}
+12 -19
View File
@@ -8,7 +8,11 @@ use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
pub(super) fn read(element: XmlNode<'_, '_>) -> Result<FunctionGraph, String> {
let mut graph = FunctionGraph { output: child_value(element, "rootnode").and_then(|value| value.parse().ok()), nodes: Vec::new() };
let mut graph = FunctionGraph {
output: child_value(element, "rootnode").and_then(|value| value.parse().ok()),
nodes: Vec::new(),
annotations: super::canvas::read_embedded(element),
};
let mut ids = BTreeSet::new();
for element in child_element(element, "paramNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramNode")) {
if graph.nodes.len() >= 4096 {
@@ -153,27 +157,16 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result<Str
}
output.push_str("</paramNode>");
}
output.push_str("</paramNodes></dynamicValue>");
output.push_str("</paramNodes>");
if !graph.annotations.is_empty() {
super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer);
}
output.push_str("</dynamicValue>");
Ok(output)
}
pub(super) fn binding(identifier: &str, value: &Value) -> Result<FunctionGraph, String> {
use materialcraft_core::ValueType;
let value_type = materialcraft_core::ValueType::of(value).ok_or("only scalar and vector parameters can be exposed")?;
let operation = match ValueType::of(value).ok_or("only scalar and vector parameters can be exposed")? {
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()))));
Ok(graph)
Ok(FunctionGraph::input(identifier, value_type))
}
+10
View File
@@ -0,0 +1,10 @@
use super::LayoutItem;
/// A titled frame and the nodes inside it, top to bottom
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutFrame {
pub title: String,
/// The frame groups function nodes (it sits in a function graph or a parameter function)
pub function: bool,
pub items: Vec<LayoutItem>,
}
+17
View File
@@ -0,0 +1,17 @@
/// One node placed in a layout frame
#[derive(Clone, Debug, PartialEq)]
pub enum LayoutItem {
/// An atomic SBS filter by its SBS name, with the MaterialCraft node it reads as (`None`
/// when MaterialCraft has no counterpart yet)
Atomic { filter: String, node: Option<&'static str> },
/// A graph input (`input_color`, `input_grayscale`, `input_value`) or `output`
Node(&'static str),
/// An instance of graph `graph` from the library package `package`
Instance { package: String, graph: String, outputs: Vec<String> },
/// A native function operation, e.g. `add`
Operation(String),
/// An instance of function graph `graph` from the library package `package`
FunctionInstance { package: String, graph: String },
/// A bitmap showing one of the layout package's own resources, e.g. an environment image
Bitmap { resource: String },
}
+71
View File
@@ -10,6 +10,7 @@ pub fn relative_path(uri: &str) -> Result<&str, String> {
{
return Err("invalid SBS library path".into());
}
Ok(path)
}
@@ -51,15 +52,18 @@ pub fn root() -> std::path::PathBuf {
if let Some(root) = std::env::var_os("MATERIALCRAFT_SBS_DIR") {
return root.into();
}
if let Ok(executable) = std::env::current_exe()
&& let Some(parent) = executable.parent()
&& parent.join("assets/sbs").is_dir()
{
return parent.join("assets/sbs");
}
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs")
}
/// Read a validated library alias from the configured directory or the embedded fallback.
pub fn read(uri: &str) -> Result<Vec<u8>, String> {
let relative = relative_path(uri)?;
#[cfg(not(target_arch = "wasm32"))]
@@ -82,3 +86,70 @@ pub fn read(uri: &str) -> Result<Vec<u8>, String> {
_ => Err(format!("Missing library asset {uri}")),
}
}
/// The packages bundled into the binary, for installs and the browser without an asset folder
pub const BUNDLED: &[&str] = &["sbs://functions.sbs"];
/// Bounds for scanning the library folder: how deep, and how many packages
const MAX_DEPTH: usize = 6;
const MAX_FILES: usize = 2048;
/// Every SBS package in the library as `sbs://` paths, sorted: the files under the asset folder
/// (resource folders skipped), or the bundled packages when there is no folder
pub fn files() -> Vec<String> {
#[cfg(not(target_arch = "wasm32"))]
{
let root = root();
if root.is_dir() {
let mut found = Vec::new();
scan(&root, "", 0, &mut found);
found.sort();
return found;
}
}
BUNDLED.iter().map(|uri| uri.to_string()).collect()
}
/// Discover packages in deterministic order within the depth and file limits.
#[cfg(not(target_arch = "wasm32"))]
fn scan(directory: &std::path::Path, prefix: &str, depth: usize, found: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(directory) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
if found.len() >= MAX_FILES {
return;
}
let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue };
let Ok(kind) = entry.file_type() else { continue };
let uri = format!("sbs://{prefix}{name}");
// Symlinks are skipped: `read` refuses files that leave the asset folder anyway
if kind.is_dir() && depth < MAX_DEPTH && !name.ends_with(".resources") && !name.starts_with('.') {
scan(&entry.path(), &format!("{prefix}{name}/"), depth + 1, found);
} else if kind.is_file() && name.to_ascii_lowercase().ends_with(".sbs") && relative_path(&uri).is_ok() {
found.push(uri);
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
/// Discovered packages have unique valid aliases and the embedded fallback is present.
#[test]
fn the_library_lists_every_package_once_and_bundles_a_fallback() {
let files = files();
for uri in BUNDLED {
assert!(files.iter().any(|file| file == uri), "{uri} in {files:?}");
assert!(!read(uri).unwrap().is_empty());
}
let mut unique = files.clone();
unique.dedup();
assert_eq!(unique, files);
assert!(files.iter().all(|file| relative_path(file).is_ok() && file.ends_with(".sbs")));
}
}
+281
View File
@@ -0,0 +1,281 @@
//! Library layouts. An SBS package can lay out a node library: its graphs group nodes in titled
//! frames ("Filters - Blurs"), and a parameter function groups function nodes the same way. This
//! reads the frames and the nodes inside each one; it does not cook anything. The engine decides
//! which frame titles are library categories.
use super::{
LayoutFrame, LayoutItem,
constant::MAX_XML_NODES,
filter_map::FILTERS,
xml::{child_element, child_value, children_named, parse_floats},
};
use crate::{FormatError, Result};
use roxmltree::Node as XmlNode;
use std::collections::HashMap;
/// Bounds for hostile layouts: frames and placed nodes kept per file
const MAX_FRAMES: usize = 4096;
const MAX_ITEMS: usize = 65_536;
/// The frames of every graph and parameter function in `bytes`, in document order
pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> {
let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?;
let text = text.trim_start_matches('\u{feff}');
let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES };
let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?;
let root = doc.root_element();
if root.tag_name().name() != "package" {
return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into()));
}
let mut dependencies = HashMap::new();
for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) {
if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) {
let file = if file == "?himself" { uri.to_string() } else { super::library::resolve(uri, file).map_err(FormatError::BadPackage)? };
dependencies.insert(uid, file);
}
}
let mut frames = Vec::new();
let mut items = 0;
for scope in root.descendants().filter(|node| node.is_element()) {
let function = match scope.tag_name().name() {
"graph" if child_element(scope, "compNodes").is_some() => false,
_ if child_element(scope, "paramNodes").is_some() => true,
_ => continue,
};
let mut scope_frames = scope_frames(scope);
if scope_frames.is_empty() {
continue;
}
let nodes: Vec<(XmlNode, [f32; 2])> = if function {
child_element(scope, "paramNodes").into_iter().flat_map(|n| children_named(n, "paramNode")).filter_map(|n| Some((n, position(n)?))).collect()
} else {
child_element(scope, "compNodes").into_iter().flat_map(|n| children_named(n, "compNode")).filter_map(|n| Some((n, position(n)?))).collect()
};
let mut placed: Vec<(usize, [f32; 2], LayoutItem)> = Vec::new();
for (node, at) in nodes {
if items >= MAX_ITEMS {
break;
}
// The smallest frame holding the node wins, so nested frames keep their own nodes
let Some(frame) = scope_frames
.iter()
.enumerate()
.filter(|(_, (_, rect))| at[0] >= rect[0] && at[1] >= rect[1] && at[0] <= rect[0] + rect[2] && at[1] <= rect[1] + rect[3])
.min_by(|a, b| (a.1.1[2] * a.1.1[3]).total_cmp(&(b.1.1[2] * b.1.1[3])))
.map(|(index, _)| index)
else {
continue;
};
let item = if function { function_item(node, &dependencies) } else { graph_item(scope, node, &dependencies) };
if let Some(item) = item {
placed.push((frame, at, item));
items += 1;
}
}
placed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1[1].total_cmp(&b.1[1])).then(a.1[0].total_cmp(&b.1[0])));
let mut grouped: Vec<Vec<LayoutItem>> = vec![Vec::new(); scope_frames.len()];
for (frame, _, item) in placed {
if let Some(list) = grouped.get_mut(frame) {
list.push(item);
}
}
for ((title, _), items) in scope_frames.drain(..).zip(grouped) {
if frames.len() >= MAX_FRAMES {
break;
}
frames.push(LayoutFrame { title, function, items });
}
}
Ok(frames)
}
/// The titled frames of a graph or function: (title, [x, y, width, height])
fn scope_frames(scope: XmlNode) -> Vec<(String, [f32; 4])> {
child_element(scope, "GUIObjects")
.into_iter()
.flat_map(|objects| children_named(objects, "GUIObject"))
.filter(|object| child_value(*object, "type") == Some("COMMENT"))
.filter_map(|object| {
let title = child_value(object, "title")?.trim();
let layout = child_element(object, "GUILayout")?;
let at = parse_floats(child_value(layout, "gpos")?);
let size = parse_floats(child_value(layout, "size")?);
let rect = [*at.first()?, *at.get(1)?, *size.first()?, *size.get(1)?];
(!title.is_empty() && rect[2] > 0.0 && rect[3] > 0.0).then(|| (title.chars().take(256).collect(), rect))
})
.take(MAX_FRAMES)
.collect()
}
/// Read a node position when its layout has both coordinates.
fn position(node: XmlNode) -> Option<[f32; 2]> {
let at = parse_floats(child_value(child_element(node, "GUILayout")?, "gpos")?);
Some([*at.first()?, *at.get(1)?])
}
/// `pkg:///Graph/Path?dependency=123` as (graph path, package file)
fn reference(path: &str, dependencies: &HashMap<&str, String>) -> Option<(String, String)> {
let path = path.strip_prefix("pkg:///")?;
let (graph, query) = path.split_once('?').unwrap_or((path, ""));
let uid = query.split('&').find_map(|pair| pair.strip_prefix("dependency="))?;
let package = dependencies.get(uid)?.clone();
let graph = graph.trim_matches('/');
(!graph.is_empty()).then(|| (graph.chars().take(1024).collect(), package))
}
/// Translate a graph node into a library placement without cooking it.
fn graph_item(graph: XmlNode, node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<LayoutItem> {
let implementation = child_element(node, "compImplementation")?.children().find(|c| c.is_element())?;
match implementation.tag_name().name() {
"compFilter" => {
let filter = child_value(implementation, "filter")?;
if filter == "bitmap"
&& let Some(resource) = string_parameter(implementation, "bitmapresourcepath")
{
let resource = resource.strip_prefix("pkg:///").unwrap_or(resource);
let resource = resource.split_once('?').map_or(resource, |(path, _)| path);
return Some(LayoutItem::Bitmap { resource: resource.chars().take(1024).collect() });
}
Some(LayoutItem::Atomic { filter: filter.chars().take(128).collect(), node: FILTERS.iter().find(|f| f.sbs == filter).map(|f| f.def) })
}
"compInstance" => {
let (graph, package) = reference(child_value(implementation, "path")?, dependencies)?;
let outputs = child_element(implementation, "outputBridgings")
.into_iter()
.flat_map(|b| children_named(b, "outputBridging"))
.filter_map(|b| child_value(b, "identifier"))
.take(64)
.map(str::to_string)
.collect();
Some(LayoutItem::Instance { package, graph, outputs })
}
"compInputBridge" => {
let entry = child_value(implementation, "entry")?;
let input = child_element(graph, "paraminputs")
.into_iter()
.flat_map(|inputs| children_named(inputs, "paraminput"))
.find(|input| child_value(*input, "uid") == Some(entry));
Some(LayoutItem::Node(match input.and_then(|input| child_value(input, "type")) {
Some("1") | None => "input_color",
Some("2") => "input_grayscale",
Some(_) => "input_value",
}))
}
"compOutputBridge" => Some(LayoutItem::Node("output")),
_ => None,
}
}
/// Translate a native operation or reusable function reference into a placement.
fn function_item(node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<LayoutItem> {
let operation = child_value(node, "function")?;
if operation != "instance" {
return Some(LayoutItem::Operation(operation.chars().take(128).collect()));
}
let path = child_element(node, "funcDatas")
.into_iter()
.flat_map(|datas| children_named(datas, "funcData"))
.find(|data| child_value(*data, "name") == Some("instance"))
.and_then(|data| child_element(data, "constantValue"))
.and_then(|value| child_value(value, "constantValueString"))?;
let (graph, package) = reference(path, dependencies)?;
Some(LayoutItem::FunctionInstance { package, graph })
}
/// Read a named static string parameter from an atomic filter.
fn string_parameter<'a>(filter: XmlNode<'a, '_>, name: &str) -> Option<&'a str> {
child_element(filter, "parameters")
.into_iter()
.flat_map(|parameters| children_named(parameters, "parameter"))
.find(|parameter| child_value(*parameter, "name") == Some(name))
.and_then(|parameter| child_element(parameter, "paramValue"))
.and_then(|value| child_value(value, "constantValueString"))
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
const LAYOUT: &str = r#"<?xml version="1.0"?><package><dependencies>
<dependency><filename v="?himself"/><uid v="1"/></dependency>
<dependency><filename v="sbs://noise.sbs"/><uid v="2"/></dependency>
<dependency><filename v="sbs://functions.sbs"/><uid v="3"/></dependency></dependencies>
<content><graph><identifier v="Graph"/>
<paraminputs><paraminput><identifier v="mask"/><uid v="40"/><type v="2"/></paraminput></paraminputs>
<compNodes>
<compNode><uid v="10"/><GUILayout><gpos v="20 90 0"/></GUILayout><compImplementation><compInstance><path v="pkg:///perlin_noise?dependency=2"/><outputBridgings><outputBridging><uid v="11"/><identifier v="output"/></outputBridging></outputBridgings></compInstance></compImplementation></compNode>
<compNode><uid v="12"/><GUILayout><gpos v="20 40 0"/></GUILayout><compImplementation><compFilter><filter v="blur"/></compFilter></compImplementation></compNode>
<compNode><uid v="13"/><GUILayout><gpos v="20 60 0"/></GUILayout><compImplementation><compInputBridge><entry v="40"/></compInputBridge></compImplementation></compNode>
<compNode><uid v="14"/><GUILayout><gpos v="500 60 0"/></GUILayout><compImplementation><compFilter><filter v="bitmap"/><parameters><parameter><name v="bitmapresourcepath"/><paramValue><constantValueString v="pkg:///Resources/studio?dependency=1"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode>
<compNode><uid v="15"/><GUILayout><gpos v="900 900 0"/></GUILayout><compImplementation><compOutputBridge/></compImplementation></compNode>
<compNode><uid v="16"/><GUILayout><gpos v="30 70 0"/></GUILayout><compImplementation><compFilter><filter v="blend"/><parameters><parameter><name v="opacitymult"/><paramValue><dynamicValue>
<paramNodes>
<paramNode><uid v="1"/><GUILayout><gpos v="0 10 0"/></GUILayout><function v="add"/></paramNode>
<paramNode><uid v="2"/><GUILayout><gpos v="300 10 0"/></GUILayout><function v="instance"/><funcDatas><funcData><name v="instance"/><constantValue><constantValueString v="pkg:///Functions/Math/Pi?dependency=3"/></constantValue></funcData></funcDatas></paramNode>
</paramNodes>
<GUIObjects>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="-10 0 0"/><size v="100 100"/></GUILayout><title v="Operator"/></GUIObject>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="250 0 0"/><size v="100 100"/></GUILayout><title v="Constant"/></GUIObject>
</GUIObjects></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation></compNode>
</compNodes>
<GUIObjects>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="160 200"/></GUILayout><title v="Texture Generators - Noises"/></GUIObject>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="400 0 0"/><size v="160 200"/></GUILayout><title v="3D view - HDRI environments"/></GUIObject>
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="10 10"/></GUILayout></GUIObject>
</GUIObjects></graph></content></package>"#;
/// Frames preserve spatial ordering and distinguish material and function entries.
#[test]
fn frames_list_what_sits_inside_them_top_to_bottom() {
let frames = read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap();
let graph: Vec<_> = frames.iter().filter(|frame| !frame.function).collect();
assert_eq!(graph.len(), 2);
assert_eq!(graph[0].title, "Texture Generators - Noises");
assert_eq!(
graph[0].items,
vec![
LayoutItem::Atomic { filter: "blur".into(), node: Some("blur") },
LayoutItem::Node("input_grayscale"),
LayoutItem::Atomic { filter: "blend".into(), node: Some("blend") },
LayoutItem::Instance { package: "sbs://noise.sbs".into(), graph: "perlin_noise".into(), outputs: vec!["output".into()] },
]
);
assert_eq!(graph[1].items, vec![LayoutItem::Bitmap { resource: "Resources/studio".into() }]);
let function: Vec<_> = frames.iter().filter(|frame| frame.function).collect();
assert_eq!(function.len(), 2);
assert_eq!(function[0].items, vec![LayoutItem::Operation("add".into())]);
assert_eq!(function[1].items, vec![LayoutItem::FunctionInstance { package: "sbs://functions.sbs".into(), graph: "Functions/Math/Pi".into() }]);
}
/// Missing layouts and malformed input remain nonfatal.
#[test]
fn packages_without_frames_have_no_layout_and_bad_input_errors() {
assert!(read_layout(b"<package><content><graph><compNodes/></graph></content></package>", "sbs://x.sbs").unwrap().is_empty());
assert!(read_layout(b"<nope/>", "sbs://x.sbs").is_err());
assert!(read_layout(b"\xff\xfe", "sbs://x.sbs").is_err());
assert!(read_layout(b"<package><content><graph><compNodes><compNode><GUILayout><gpos v=\"nan\"/></GUILayout></compNode></compNodes><GUIObjects><GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"0 0\"/><size v=\"-5 1e40\"/></GUILayout><title v=\"X\"/></GUIObject></GUIObjects></graph></content></package>", "sbs://x.sbs").unwrap().is_empty());
}
/// Relative layout references resolve beside the layout, including parent directories.
#[test]
fn review_layout_resolves_relative_dependencies() {
let layout = LAYOUT.replace("sbs://noise.sbs", "../noise.sbs").replace("sbs://functions.sbs", "functions.sbs");
let frames = read_layout(layout.as_bytes(), "sbs://layouts/library.sbs").unwrap();
assert!(frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item,
LayoutItem::Instance { package, .. } if package == "sbs://noise.sbs")));
assert!(frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item,
LayoutItem::FunctionInstance { package, .. } if package == "sbs://layouts/functions.sbs")));
}
}
+7
View File
@@ -11,11 +11,15 @@ mod graph_attributes;
mod group_layout;
mod image_input;
mod input_bridge;
mod layout_frame;
mod layout_item;
pub mod library;
mod library_layout;
mod node_identifiers;
mod node_parameter;
mod output;
mod parameter_array;
mod parameter_widget;
mod pattern_graph;
mod placeholder;
mod read_node;
@@ -29,6 +33,9 @@ mod warnings;
mod xml;
pub use constant::SBS_EXT;
pub use layout_frame::LayoutFrame;
pub use layout_item::LayoutItem;
pub use library_layout::read_layout;
pub use read::{is_sbs, read_sbs};
pub use sbs_read::SbsRead;
pub use write::write_sbs;
@@ -0,0 +1,94 @@
use super::xml::{child_element, child_value, children_named, format_float, xml_escape};
use materialcraft_core::{ExposedParameter, ParameterEditor, Value};
use roxmltree::Node;
use std::fmt::Write;
pub(super) fn read(element: Node<'_, '_>, input: &mut ExposedParameter) {
input.description = child_element(element, "attributes").and_then(|attributes| child_value(attributes, "description")).unwrap_or("").into();
let Some(widget) = child_element(element, "defaultWidget") else {
return;
};
let name = child_value(widget, "name").unwrap_or("");
let mut color = name == "color";
for option in child_element(widget, "options").into_iter().flat_map(|options| children_named(options, "option")) {
let text = child_value(option, "value").unwrap_or("");
let number = text.split([' ', ';']).next().and_then(|value| value.parse::<f32>().ok()).filter(|value| value.is_finite());
match child_value(option, "name").unwrap_or("") {
"clamp" => input.clamp = number.is_some_and(|value| value != 0.0),
"step" => input.step = number.filter(|step| *step > 0.0),
"valueInterpretation" if text == "color" => color = true,
"parameters" if name == "dropdownlist" => {
let mut parts = text.split(';').skip(1);
while let (Some(index), Some(label)) = (parts.next(), parts.next()) {
// The model's enum values are contiguous; sparse external lists remain numeric
if index.parse::<usize>().ok() != Some(input.options.len()) {
input.options.clear();
break;
}
input.options.push(label.into());
}
}
_ => {}
}
}
if name == "dropdownlist"
&& !input.options.is_empty()
&& let Some(value) = input.default.as_i32()
{
input.default = Value::Enum(value.max(0) as u32);
}
if color && matches!(input.default, Value::Float4(_)) {
// Color defaults use the same displayed-to-linear conversion as node colors
if let Some(value) = child_element(element, "defaultValue")
.and_then(super::sbs_value::sbs_constant)
.and_then(|value| super::sbs_value::to_param_value(&Value::Color([0.0; 4]), &value, 0))
{
input.default = value;
}
}
let editor = match name {
"slider" => Some(ParameterEditor::Slider),
"inputfield" => Some(ParameterEditor::Input),
"color" => Some(ParameterEditor::Color),
"dropdownlist" => Some(ParameterEditor::Dropdown),
"buttons" => Some(ParameterEditor::Toggle),
"text" => Some(ParameterEditor::Text),
_ => None,
};
input.editor = editor.filter(|editor| *editor != ParameterEditor::for_value(&input.default) && ParameterEditor::choices(&input.default).contains(editor));
}
pub(super) fn write(out: &mut String, input: &ExposedParameter) {
let name = match input.editor() {
ParameterEditor::Slider => "slider",
ParameterEditor::Input => "inputfield",
ParameterEditor::Color => "color",
ParameterEditor::Dropdown => "dropdownlist",
ParameterEditor::Toggle => "buttons",
ParameterEditor::Text => "text",
};
let _ = write!(out, "<defaultWidget><name v=\"{name}\"/><options>");
for (name, value) in [("min", format_float(input.min)), ("max", format_float(input.max)), ("clamp", u8::from(input.clamp).to_string())] {
option(out, name, &value);
}
if matches!(input.default, Value::Color(_)) {
option(out, "valueInterpretation", "color");
}
if let Some(step) = input.step {
option(out, "step", &format_float(step));
}
if !input.options.is_empty() {
let mut values = input.default.as_i32().unwrap_or(0).to_string();
for (index, label) in input.options.iter().enumerate() {
let _ = write!(values, ";{index};{label}");
}
option(out, "parameters", &values);
}
out.push_str("</options></defaultWidget>");
}
fn option(out: &mut String, name: &str, value: &str) {
let _ = write!(out, "<option><name v=\"{name}\"/><value v=\"{}\"/></option>", xml_escape(value));
}
+10 -2
View File
@@ -32,7 +32,11 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result<PatternGraph, String> {
}
}
let mut graph = PatternGraph { root: child_value(element, "rootnode").and_then(|id| id.parse().ok()), nodes: Vec::new() };
let mut graph = PatternGraph {
root: child_value(element, "rootnode").and_then(|id| id.parse().ok()),
nodes: Vec::new(),
annotations: super::canvas::read_embedded(element),
};
for element in child_element(element, "paramsGraphNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramsGraphNode")) {
if graph.nodes.len() >= 4096 {
return Err("pattern graph exceeds the 4096-node limit".into());
@@ -111,6 +115,10 @@ pub(super) fn write(graph: &PatternGraph, writer: &mut SbsWriter) -> Result<Stri
}
output.push_str("</connections></paramsGraphNode>");
}
output.push_str("</paramsGraphNodes></paramsGraph></paramsGraphs>");
output.push_str("</paramsGraphNodes>");
if !graph.annotations.is_empty() {
super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer);
}
output.push_str("</paramsGraph></paramsGraphs>");
Ok(output)
}
+23 -6
View File
@@ -146,7 +146,7 @@ impl<'text> SbsReader<'text, '_> {
pub(super) fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph {
let mut graph = Graph::new(&name);
let base = read_base_params(child_element(element, "baseParameters"));
let base = read_base_params(child_element(element, "baseParameters"), self.warnings);
graph.seed = base.seed;
graph.pixel_ratio = base.pixel_ratio;
graph.pixel_ratio_mode = base.pixel_ratio_mode;
@@ -184,7 +184,10 @@ impl<'text> SbsReader<'text, '_> {
let dynamic = child_element(element, "paramValue").and_then(|value| child_element(value, "dynamicValue"));
let function = dynamic.ok_or_else(|| "missing function body".to_string()).and_then(super::function_graph::read);
graph.function = Some(match function {
Ok(function) => function,
Ok(mut function) => {
function.annotations = Default::default();
function
}
Err(error) => {
self.warnings.add(format!("function graph `{name}`: {error}"));
materialcraft_core::FunctionGraph::default()
@@ -276,7 +279,21 @@ impl<'text> SbsReader<'text, '_> {
}
let group = child_value(input, "group").unwrap_or("").to_string();
graph.exposed.push(ExposedParameter { id, label, group, default, min, max, options: Vec::new() });
let mut exposed = ExposedParameter {
id,
label,
group,
default,
min,
max,
options: Vec::new(),
description: String::new(),
editor: None,
clamp: false,
step: None,
};
super::parameter_widget::read(input, &mut exposed);
graph.exposed.push(exposed);
}
image_inputs
}
@@ -375,7 +392,7 @@ impl<'text> SbsReader<'text, '_> {
if let Some(input) = input {
node.params.insert("default".into(), input.default.clone());
}
node.base = read_base_params(params);
node.base = read_base_params(params, self.warnings);
}
ReadNode { id, index, inputs: HashMap::new(), outputs: all_outputs_to("output"), open_inputs: false }
}
@@ -399,7 +416,7 @@ impl<'text> SbsReader<'text, '_> {
if let Some(node) = node {
self.read_filter_params(node, filter, params, &graph_name);
super::parameter_array::read(node, implementation);
node.base = read_base_params(params);
node.base = read_base_params(params, self.warnings);
if filter.sbs == "fxmaps"
&& let Some(pattern) = child_element(implementation, "paramsGraphs").and_then(|graphs| child_element(graphs, "paramsGraph"))
{
@@ -484,7 +501,7 @@ impl<'text> SbsReader<'text, '_> {
self.set_param(node, child_value(param, "name").unwrap_or(""), &Value::Float(0.0), 0, param, &graph_name);
}
}
node.base = read_base_params(params);
node.base = read_base_params(params, self.warnings);
}
return ReadNode { id, index, inputs: HashMap::new(), outputs: bridgings, open_inputs: true };
}
+7 -6
View File
@@ -150,7 +150,7 @@ impl SbsWriter {
tiling_mode: graph.tiling_mode,
..Default::default()
};
out.push_str(&super::base_parameters::base_params_xml(&base));
out.push_str(&super::base_parameters::base_params_xml(&base, self).map_err(FormatError::Io)?);
out.push_str("</baseParameters>");
write_canvas_items(out, graph, self);
@@ -196,14 +196,15 @@ impl SbsWriter {
let _ = write!(
out,
"<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/><attributes><label v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue><defaultWidget><name v=\"slider\"/><options><option><name v=\"min\"/><value v=\"{}\"/></option><option><name v=\"max\"/><value v=\"{}\"/></option></options></defaultWidget>{group}</paraminput>",
"<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/><attributes><label v=\"{}\"/><description v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue>",
xml_escape(&exposed.id),
self.next_uid(),
xml_escape(&exposed.label),
exposed_type_code(&exposed.default),
format_float(exposed.min),
format_float(exposed.max)
xml_escape(&exposed.description),
exposed_type_code(&exposed.default)
);
super::parameter_widget::write(out, exposed);
let _ = write!(out, "{group}</paraminput>");
}
out.push_str("</paraminputs>");
@@ -242,7 +243,7 @@ impl SbsWriter {
ids: NodeIdentifiers,
package: &Package,
) -> Result<()> {
let base = base_params_xml(&node.base);
let base = base_params_xml(&node.base, self).map_err(FormatError::Io)?;
match node.def.as_str() {
"output" => {
+9 -4
View File
@@ -19,16 +19,21 @@ fn bitmap_filters_are_specific_and_match_supported_extensions() {
#[test]
fn common_bitmap_formats_decode() {
let pixels = Image::filled(4, 4, Kind::Color, [0.25, 0.5, 0.75, 1.0]);
for extension in ["png", "jpeg", "tga", "tiff", "bmp", "webp", "exr", "hdr"] {
for extension in ["png", "jpeg", "tga", "bmp", "webp", "exr", "hdr"] {
let bytes = encode(&pixels, extension, Depth::U8, true).unwrap();
let image = decode(&bytes, false).unwrap();
assert_eq!((image.w, image.h), (4, 4), "{extension}");
}
let mut gif = Cursor::new(Vec::new());
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut gif, image::ImageFormat::Gif).unwrap();
assert_eq!(decode(gif.get_ref(), false).unwrap().w, 2);
// GIF and TIFF import only, so another writer makes them
for format in [image::ImageFormat::Gif, image::ImageFormat::Tiff] {
let mut bytes = Cursor::new(Vec::new());
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut bytes, format).unwrap();
assert_eq!(decode(bytes.get_ref(), false).unwrap().w, 2, "{format:?}");
}
assert!(encode(&pixels, "tif", Depth::U8, true).is_err(), "TIFF is not an export format");
for pgm in [&b"P2\n2 1\n255\n0 255\n"[..], &b"P5\n2 1\n255\n\0\xff"[..]] {
let image = decode(pgm, false).unwrap();
+18 -3
View File
@@ -109,10 +109,15 @@ fn supplied_function_package_round_trip() {
let replacement = bundled.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
assert_eq!(graph.function_type, replacement.function_type, "{}", graph.sbs_path());
assert_eq!(graph.function_type, other.function_type, "{}", graph.sbs_path());
assert_eq!(graph.exposed, replacement.exposed, "{}", graph.sbs_path());
let mut expected_inputs = graph.exposed.clone();
for input in &mut expected_inputs {
input.description.clear();
}
assert_eq!(expected_inputs, replacement.exposed, "{}", graph.sbs_path());
assert_ne!(graph.attributes.description, replacement.attributes.description, "{}", graph.sbs_path());
assert!(replacement.attributes.author.is_empty());
assert!(replacement.attributes.tags.is_empty());
assert_eq!(replacement.attributes.category, graph.attributes.category);
assert_eq!(replacement.attributes.tags, graph.attributes.tags);
assert!(replacement.frames.is_empty() && replacement.comments.is_empty() && replacement.pins.is_empty());
assert_same_body(graph, replacement);
assert_eq!(graph.name, other.name);
@@ -167,9 +172,19 @@ fn bundled_library_has_complete_bodies_and_current_export_metadata() {
assert!(function.output.is_some(), "{}", graph.sbs_path());
assert!(function.nodes.iter().all(|node| node.missing.is_none()), "{}", graph.sbs_path());
assert!(!graph.attributes.description.is_empty());
assert!(graph.attributes.author.is_empty() && graph.attributes.tags.is_empty());
assert!(graph.attributes.author.is_empty());
assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty());
}
let pi = &read.pkg.graph_by_name("Functions/Math/Pi").unwrap().1.attributes;
assert!(pi.category.is_empty());
assert_eq!(pi.tags, "Constant");
let saved = write_sbs(&read.pkg).unwrap();
let reopened = read_sbs(&saved, "functions.sbs", &|_| None).unwrap();
for graph in &read.pkg.graphs {
let reloaded = reopened.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
assert_eq!(reloaded.attributes.category, graph.attributes.category);
assert_eq!(reloaded.attributes.tags, graph.attributes.tags);
}
assert!(!xml.descendants().any(|element| element.has_tag_name("icon")));
}
+1
View File
@@ -10,6 +10,7 @@ pub(super) fn definition() -> NodeDefinition {
.atomic()
.any_in("foreground", "Foreground")
.any_in("background", "Background")
.primary_input("background")
.gray_in("mask", "Opacity")
.float("opacity", "Opacity", 1.0, 0.0, 1.0)
.choice("mode", "Blending mode", BLEND_MODES, 0)
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more