Integrate cache keys with SBS and bound graph traversal

This commit is contained in:
Rafael Mendes committed 2026-11-05 11:02:15 -03:00
commit a026ddaaf9
68 files changed
+5777 -384

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
name: SonarCloud
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
sonarcloud:
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
secrets: inherit
+1
View File
@@ -10,3 +10,4 @@ target/
/craft-fonts
*.mcraft.tmp
.claude/worktrees/
pr-review-guidelines.md
+8 -5
View File
@@ -11,7 +11,8 @@ The product name is always written **MaterialCraft** (`{Function}Craft` in Pasca
siblings PhotoCraft, VectorCraft, FilmCraft, LightCraft, PdfCraft, EffectCraft, DesignCraft,
TextureCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose.
Machine names stay lowercase: crates (`materialcraft-*`), binaries, file names, ids
(`ai.storyteller.materialcraft`), the native package extension `.mcraft`.
(`ai.storyteller.materialcraft`). The main project format is SBS (`.sbs`); the older native
package extension `.mcraft` is still read and written.
Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next
to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its
@@ -41,7 +42,7 @@ file first, then `docs/`.
crates/
core image geom L0 document model (package, graphs, nodes, values, function graphs); float images; meshes, BVH, camera
nodes L1 the node library: definitions + CPU cooks (atomic nodes, noises, patterns, filters, PBR utilities, function evaluator)
eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); .mcraft packages, bitmaps, texture export
eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); .sbs and .mcraft packages, bitmaps, texture export
engine render L3 Session + command registry (every action is a command), inspect, samples; the 3D preview renderer (CPU PBR + IBL)
automation L4 MCP server + headless JSON-lines RPC + bridge to the running app
ui-egui L5 egui shell (thin: every edit goes through engine commands)
@@ -96,9 +97,11 @@ workflow. Work from public documentation, general domain knowledge and public al
and simplex gradient noise, Worley/cellular noise, fractal sums, Gaussian and box blurs,
Felzenszwalb–Huttenlocher distance transforms, Sobel/central-difference normals, reoriented normal
mapping, HSL, levels, monotone cubic curves, W3C blend modes, GGX/Smith/Schlick PBR, split-sum IBL,
ACES fitted tone mapping). Never copy proprietary code, shaders, node implementations, presets or
file formats; compatibility with the reference app's package formats is a non-goal. Always describe
MaterialCraft as a clean-room implementation, in code, docs and commits.
ACES fitted tone mapping). Never copy proprietary code, shaders, node implementations or presets.
SBS packages are the main project format (issue #49): `crates/formats/src/sbs.rs` reads and writes
them with MaterialCraft's own code, written from the format's public documentation and sample
files, never from another implementation. Always describe MaterialCraft as a clean-room
implementation, in code, docs and commits.
### Never crash (outranks feature work)
+3
View File
@@ -26,7 +26,10 @@ images, materials, sample graphs, presets, environments) may ever be added.
| `docs/images/materialcraft-lava.png` | README screenshot: the lava rock template | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
| `docs/images/materialcraft-ground.png` | README screenshot: the mossy ground template | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
| `docs/images/materialcraft-new-graph.png` | README screenshot: the New graph dialog | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
| `docs/images/materialcraft-alpha-transparency.png` | Docs screenshot: a cut-out material in the 3D view and a reroute dot on a wire | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/images/materialcraft-alpha-channel.png` | Docs screenshot: the 3D view's alpha channel view | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/images/materialcraft-materials.png` | README render: eight sample materials on spheres | MaterialCraft contributors | `materialcraft-cli render --scene sphere --full --hq` of the templates, eight renders in a grid | MIT OR Apache-2.0 |
| `docs/images/materialcraft-levels-editor.png` | Docs screenshot: the Levels editor with the input histogram | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
| `crates/nodes/src/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 |
Generated
+27 -14
View File
@@ -2307,12 +2307,13 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "materialcraft"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"eframe",
"egui",
"image",
"log",
"materialcraft-automation",
"materialcraft-engine",
"materialcraft-ui-egui",
"serde_json",
@@ -2321,7 +2322,7 @@ dependencies = [
[[package]]
name = "materialcraft-automation"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -2332,6 +2333,7 @@ dependencies = [
"materialcraft-render",
"rayon",
"rmcp",
"rustix 1.1.6",
"schemars",
"serde",
"serde_json",
@@ -2341,7 +2343,7 @@ dependencies = [
[[package]]
name = "materialcraft-cli"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-automation",
"materialcraft-engine",
@@ -2352,7 +2354,7 @@ dependencies = [
[[package]]
name = "materialcraft-core"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"serde",
"serde_json",
@@ -2361,7 +2363,7 @@ dependencies = [
[[package]]
name = "materialcraft-engine"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-eval",
@@ -2376,7 +2378,7 @@ dependencies = [
[[package]]
name = "materialcraft-eval"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2386,13 +2388,17 @@ dependencies = [
[[package]]
name = "materialcraft-formats"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"base64 0.22.1",
"flate2",
"gltf",
"image",
"materialcraft-core",
"materialcraft-geom",
"materialcraft-image",
"materialcraft-nodes",
"roxmltree",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -2402,7 +2408,7 @@ dependencies = [
[[package]]
name = "materialcraft-geom"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -2413,7 +2419,7 @@ dependencies = [
[[package]]
name = "materialcraft-image"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"rayon",
"thiserror 2.0.21",
@@ -2421,7 +2427,7 @@ dependencies = [
[[package]]
name = "materialcraft-nodes"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2430,7 +2436,7 @@ dependencies = [
[[package]]
name = "materialcraft-render"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-geom",
"materialcraft-image",
@@ -2439,7 +2445,7 @@ dependencies = [
[[package]]
name = "materialcraft-ui-egui"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"base64 0.22.1",
"craft-ui",
@@ -2455,6 +2461,7 @@ dependencies = [
"rfd",
"serde",
"serde_json",
"sys-locale",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -2463,7 +2470,7 @@ dependencies = [
[[package]]
name = "materialcraft-web"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"eframe",
"js-sys",
@@ -3588,6 +3595,12 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "roxmltree"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -5234,7 +5247,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"serde_json",
]
+4 -1
View File
@@ -35,7 +35,7 @@ default-members = [
]
[workspace.package]
version = "0.1.0"
version = "0.1.2"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -68,6 +68,7 @@ eframe = { version = "0.37", default-features = false }
egui = "0.37"
wgpu = "30"
rfd = "0.17"
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils"] }
tobj = { version = "4", default-features = false }
@@ -76,6 +77,8 @@ rmcp = { version = "3.5", default-features = false, features = ["server", "macro
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
schemars = "1"
base64 = "0.22"
roxmltree = "0.20"
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
cap-std = "4"
getrandom = "0.3"
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
+15 -11
View File
@@ -106,14 +106,16 @@ ray-traced ambient occlusion and a shadowed key light).
- **Familiar.** The layout, panels, menus and gestures material artists already know: a package
explorer, a library of nodes with previews, the node graph with live thumbnails, a 3D view, a 2D
view and a properties panel with base and specific parameters. Space opens the node search.
view and a properties panel with base and specific parameters (Levels is edited over a
histogram of its input, see [docs/levels-editor.md](docs/levels-editor.md)). Space opens the
node search.
- **Fast.** Every node cooks on every CPU core, and a content-addressed cache means an edit
re-cooks only what lies downstream: the brick wall sample cooks in about 40 ms at preview size.
Cooking runs on a worker thread, so the UI never waits.
- **Tileable by design.** Noises and patterns live on whole-number lattices, so everything tiles
seamlessly at any resolution, from 16 px to 8K.
- **Robust.** No panics in shipped code, every command tested with hostile input, every node cooked
with odd inputs in tests, unlimited undo from snapshots, and lossless `.mcraft` packages.
with odd inputs in tests, unlimited undo from snapshots, and lossless project files.
- **Open.** Export base color, normal, roughness, metallic, height and ambient occlusion as PNG,
JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with your own file name pattern.
- **Works with TextureCraft.** **File ▸ Send to TextureCraft** puts a material on TextureCraft's
@@ -131,20 +133,20 @@ ray-traced ambient occlusion and a shadowed key light).
git clone https://github.com/storytold/materialcraft
cd materialcraft
cargo run --release -p materialcraft # desktop app (opens the brick wall sample)
cargo run --release -p materialcraft -- package.mcraft # open a package
cargo run --release -p materialcraft # desktop app
cargo run --release -p materialcraft -- package.sbs # open a package (.sbs or .mcraft)
cargo run --release -p materialcraft -- --control 7878 # + JSON control channel
cargo run --release -p materialcraft-cli -- mcp # MCP server (stdio)
cargo run --release -p materialcraft-cli -- new wood wood.mcraft
cargo run --release -p materialcraft-cli -- render wood.mcraft wood.png --scene sphere --full --hq
cargo run --release -p materialcraft-cli -- export wood.mcraft textures --format png --depth 16
cargo run --release -p materialcraft-cli -- export my.mcraft out --set wear=0.7 # with a graph input "wear" set first
cargo run --release -p materialcraft-cli -- run my.mcraft file.exportMaterial '{"path": "my.mcmat", "size": 2048}' # for TextureCraft
cargo run --release -p materialcraft-cli -- new wood wood.sbs
cargo run --release -p materialcraft-cli -- render wood.sbs wood.png --scene sphere --full --hq
cargo run --release -p materialcraft-cli -- export wood.sbs textures --format png --depth 16
cargo run --release -p materialcraft-cli -- export my.sbs out --set wear=0.7 # with a graph input "wear" set first
cargo run --release -p materialcraft-cli -- run my.sbs file.exportMaterial '{"path": "my.mcmat", "size": 2048}' # for TextureCraft
cd apps/materialcraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
```
You need Rust 1.95 or newer. The app opens with the brick wall sample; **File ▸ New ▸ Graph...**
You need Rust 1.95 or newer. The app opens with an empty graph in a new package; **File ▸ New ▸ Graph...**
starts from a PBR template or one of the sample materials.
### Use it from Claude Code and other agents
@@ -172,7 +174,9 @@ area, the remaining work and what's next.
SVG and Text, noises including tileable 3D ones, patterns, filters, the flood fill family,
whole-material blending and weathering), function graphs with a visual editor and dynamic
parameters, sub-graphs with exposed inputs and presets, the full editor (graph, library,
properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes), `.mcraft` packages,
properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes, alpha transparency and an
alpha channel view; wires you can select, delete, swap (X) and reroute with dots, see
[docs/wires-and-alpha.md](docs/wires-and-alpha.md)), SBS project files (`.mcraft` too),
texture export, portable `.mcmat` materials that TextureCraft paints with (inputs stay editable
there), the browser build with file I/O, the CLI, the control channel and the MCP server
all work today. We estimate about two thirds (≈ 67%) of a material artist's daily workflow works
+21 -18
View File
@@ -14,23 +14,23 @@ materialcraft-cli: headless MaterialCraft
USAGE:
materialcraft-cli --version
materialcraft-cli info <package.mcraft | sample>
materialcraft-cli info <package.sbs | package.mcraft | sample>
Graphs, nodes, outputs and cook results, as JSON.
materialcraft-cli commands [--filter <text>]
List the engine commands (id, label, params).
materialcraft-cli nodes [--filter <text>] [--category <text>]
List the node library (ids, ports, parameters).
materialcraft-cli run <input> <command-id> [params-json] [-o <out.mcraft>]
materialcraft-cli run <input> <command-id> [params-json] [-o <out.sbs>]
Run one command and print its JSON result; -o saves the package.
materialcraft-cli batch <script.json>
Run [{\"id\", \"params\"}, ...] or {\"open\": <input>, \"steps\": [...], \"save\": <out.mcraft>}.
materialcraft-cli new <template> <out.mcraft> [--size <px>] [--name <name>]
Run [{\"id\", \"params\"}, ...] or {\"open\": <input>, \"steps\": [...], \"save\": <out.sbs>}.
materialcraft-cli new <template> <out.sbs> [--size <px>] [--name <name>]
A new package with one graph from a template (empty, pbr, bricks, stone_tiles, wood,
metal_plates, rusty_metal, lava, marble, wicker, fabric, ground).
materialcraft-cli cook <input> [--graph <index>] [--set <input>=<value>]... [--full]
Cook a graph and print per-node timings and errors.
materialcraft-cli export <input> <dir> [--graph <index>] [--set <input>=<value>]... [--format <ext>]
[--depth 8|16|32] [--pattern <p>]
[--depth 8|16|32] [--size <px>] [--pattern <p>]
Cook at full size and write every output (png, jpg, tga, tif, bmp, webp, exr, hdr).
materialcraft-cli render <input> <out.png> [--size <W>x<H>] [--view 3d|2d] [--scene <id>] [--node <id>]
[--yaw <deg>] [--pitch <deg>] [--graph <index>] [--set <input>=<value>]... [--full]
@@ -44,7 +44,8 @@ USAGE:
materialcraft-cli serve [--port <port>] [--read-root <dir>] [--write-root <dir>]
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1:<port> with a token.
<input> is a .mcraft package or `sample` (the built-in brick wall). --set gives a graph input a value
<input> is an .sbs or .mcraft package or `sample` (the built-in brick wall). Packages save as SBS
unless the output path ends in .mcraft. --set gives a graph input a value
(JSON, e.g. `--set roughness=0.4 --set tint=\"#aa7744\"`) before cooking. See docs/control-protocol.md.
";
@@ -57,7 +58,7 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
("batch", &[], &[]),
("new", &["--size", "--name"], &[]),
("cook", &["--graph", "--set"], &["--full"]),
("export", &["--graph", "--set", "--format", "--depth", "--pattern"], &[]),
("export", &["--graph", "--set", "--format", "--depth", "--size", "--pattern"], &[]),
("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--set", "--tiling", "--displacement"], &["--full", "--hq"]),
("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]),
("serve", &["--port", "--read-root", "--write-root"], &[]),
@@ -113,7 +114,7 @@ fn version() -> String {
}
}
/// A headless session on `input` (a .mcraft package or `sample`), with local file access.
/// A headless session on `input` (an .sbs or .mcraft package, or `sample`), with local file access.
fn open(input: &str) -> Result<Headless, String> {
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
if input != "sample" {
@@ -210,7 +211,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
}
"new" => {
let tpl = a.pos(0, "<template>")?;
let out = a.pos(1, "<out.mcraft>")?;
let out = a.pos(1, "<out.sbs>")?;
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
h.command_run("file.newPackage", json!({"name": a.get("--name").unwrap_or("Untitled package")})).map_err(|e| e.to_string())?;
h.command_run("file.new", json!({"template": tpl, "size": a.num::<u64>("--size")?.unwrap_or(1024), "name": a.get("--name")}))
@@ -227,7 +228,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let mut h = open(a.pos(0, "<input>")?)?;
select_graph(&mut h, a)?;
let dir = a.pos(1, "<dir>")?;
let p = json!({"dir": dir, "graph": a.num::<u64>("--graph")?, "format": a.get("--format"), "depth": a.num::<u64>("--depth")?, "pattern": a.get("--pattern")});
let p = json!({"dir": dir, "graph": a.num::<u64>("--graph")?, "format": a.get("--format"), "depth": a.num::<u64>("--depth")?, "size": a.num::<u64>("--size")?, "pattern": a.get("--pattern")});
print(&h.export(&p).map_err(|e| e.to_string())?);
}
"render" => {
@@ -274,14 +275,16 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?)));
match a.num::<u16>("--port")? {
Some(port) => {
let (token, file) = server_token(port).map_err(|e| e.to_string())?;
rpc::serve_tcp(port, h, token, |addr| {
eprintln!("materialcraft-cli: serving JSON lines on {addr}");
if let Some(f) = &file {
eprintln!("materialcraft-cli: token in {}", f.display());
}
})
.map_err(|e| e.to_string())?;
// Bind first: a port in use must not replace its server's token file, and port 0's
// token file is named after the port actually picked.
let listener = rpc::bind_tcp(port).map_err(|e| e.to_string())?;
let addr = listener.local_addr().map_err(|e| e.to_string())?;
let (token, file) = server_token(addr.port()).map_err(|e| e.to_string())?;
eprintln!("materialcraft-cli: serving JSON lines on {addr}");
if let Some(f) = &file {
eprintln!("materialcraft-cli: token in {}", f.display());
}
rpc::serve_listener(listener, h, token).map_err(|e| e.to_string())?;
}
None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| e.to_string())?,
}
+2 -2
View File
@@ -38,8 +38,8 @@ pub fn start() {
async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
// The WebAssembly has downloaded and compiled when this runs.
step(0.5, "Preparing the sample package…").await;
let session = materialcraft_engine::sample_session();
step(0.5, "Preparing a new package…").await;
let session = materialcraft_engine::new_session();
step(0.8, "Starting the renderer…").await;
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
+1
View File
@@ -12,6 +12,7 @@ workspace = true
[dependencies]
materialcraft-engine = { workspace = true }
materialcraft-automation = { workspace = true }
materialcraft-ui-egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }
egui = { workspace = true }
+211 -70
View File
@@ -1,80 +1,109 @@
//! Loopback JSON-lines control server (`--control <port>`): one request per line,
//! `{"id", "method", "params"}`, one reply per line. The first request must be
//! `{"method":"auth","params":{"token":"…"}}` with the token from `MATERIALCRAFT_CONTROL_TOKEN`
//! or, when that is unset, the token written to `<temp>/materialcraft-control-<port>.token`.
//! or, when that is unset, the token written (owner-only) to
//! `<temp>/materialcraft-control-<port>.token`. Token handling, request framing and connection
//! limits are shared with `materialcraft-cli serve` (`materialcraft_automation::security`).
use std::io::{BufRead, BufReader, Read, Write};
use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use materialcraft_automation::security::{
AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_CONNECTIONS, read_bounded_line, server_token, token_matches,
};
use materialcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
/// Requests larger than this are rejected (screenshots go the other way).
const MAX_REQUEST: u64 = 8 << 20;
fn token(port: u16) -> String {
if let Ok(t) = std::env::var("MATERIALCRAFT_CONTROL_TOKEN")
&& t.len() >= 16
{
return t;
}
use std::hash::{BuildHasher, Hasher};
let mut out = String::new();
for i in 0..4u64 {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u64(i ^ u64::from(std::process::id()));
h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
out.push_str(&format!("{:016x}", h.finish()));
}
let path = std::env::temp_dir().join(format!("materialcraft-control-{port}.token"));
if let Err(e) = std::fs::write(&path, &out) {
eprintln!("materialcraft: could not write the control token to {}: {e}", path.display());
} else {
eprintln!("materialcraft: control token written to {}", path.display());
}
out
}
/// How long an authenticated connection may stay idle.
const IDLE_TIMEOUT: Duration = Duration::from_secs(600);
/// Listen on `127.0.0.1:port` and return the requests for the UI thread to answer
/// ([`ControlRequest::reply`]). Bind or token failures are printed and leave the channel empty.
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
eprintln!("materialcraft: control server failed to bind 127.0.0.1:{port}: {e}");
return channel().1;
}
};
start_listener(listener, ctx)
}
fn start_listener(listener: TcpListener, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let addr = match listener.local_addr() {
Ok(addr) => addr,
Err(e) => {
eprintln!("materialcraft: could not determine the control port: {e}");
return rx;
}
};
let token = token(port);
eprintln!("materialcraft: control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.clone());
std::thread::spawn(move || serve(stream, &token, tx, ctx));
// After binding, so an app that cannot listen never replaces another server's token.
let token = match server_token(addr.port()) {
Ok((token, Some(path))) => {
eprintln!("materialcraft: control token written to {}", path.display());
token
}
});
Ok((token, None)) => token,
Err(e) => {
eprintln!("materialcraft: control server disabled: {e}");
return rx;
}
};
eprintln!("materialcraft: control server listening on {addr}");
if let Err(e) = std::thread::Builder::new().name("materialcraft-control".into()).spawn(move || accept(listener, &token, &tx, &ctx)) {
eprintln!("materialcraft: could not start the control server: {e}");
}
rx
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(600)));
let Ok(read) = stream.try_clone() else { return };
let mut reader = BufReader::new(read.take(u64::MAX));
let mut out = stream;
let mut authed = false;
loop {
let mut line = String::new();
let n = match reader.by_ref().take(MAX_REQUEST).read_line(&mut line) {
Ok(n) => n,
Err(_) => break,
/// Serve connections from `listener` (at most [`MAX_CONNECTIONS`] at once).
fn accept(listener: TcpListener, token: &str, tx: &Sender<ControlRequest>, ctx: &egui::Context) {
let limiter = ConnectionLimiter::default();
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let Some(permit) = limiter.try_acquire(MAX_CONNECTIONS) else {
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"}));
continue;
};
if n == 0 {
break;
let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.to_string());
if let Err(e) = std::thread::Builder::new().name("materialcraft-control-client".into()).spawn(move || {
let _permit = permit;
serve(stream, &token, &tx, &ctx);
}) {
log::warn!("could not start a control connection: {e}");
}
if !line.ends_with('\n') && n as u64 >= MAX_REQUEST {
let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"}));
break;
}
}
/// Send `reply` with the request's `id`; false when the client is gone.
fn reply(out: &mut TcpStream, id: Value, mut reply: Value) -> bool {
if let Some(o) = reply.as_object_mut() {
o.insert("id".into(), id);
}
writeln!(out, "{reply}").is_ok() && out.flush().is_ok()
}
/// One connection: `auth` first (within [`AUTH_TIMEOUT`], one attempt), then requests
/// forwarded to the UI thread one at a time until the client disconnects or idles out.
fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui::Context) {
let Ok(mut deadline) = AuthDeadline::start(&stream, AUTH_TIMEOUT).map(Some) else { return };
let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT));
let Ok(read) = stream.try_clone() else { return };
let mut reader = BufReader::new(read);
let mut out = stream;
let mut line = String::new();
loop {
match read_bounded_line(&mut reader, &mut line) {
Ok(LineRead::Line) => {}
Ok(LineRead::TooLong) => {
reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"}));
return;
}
Ok(LineRead::Eof) | Err(_) => return,
}
if line.trim().is_empty() {
continue;
@@ -82,33 +111,145 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
let msg: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}));
let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": format!("bad JSON: {e}")}));
// Before `auth` a malformed line is the one refused attempt, as on `serve --port`.
if !sent || deadline.is_some() {
return;
}
continue;
}
};
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let mut reply = if !authed {
let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token);
authed = ok;
if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) }
} else {
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
break;
if deadline.is_some() {
let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default();
if method != "auth" || !token_matches(token, supplied) {
// One attempt per connection, as on `materialcraft-cli serve`.
reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}));
return;
}
ctx.request_repaint();
rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}))
};
if let Some(o) = reply.as_object_mut() {
o.insert("id".into(), id);
drop(deadline.take());
if !reply(&mut out, id, json!({"ok": true})) {
return;
}
continue;
}
if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed {
if !authed {
continue;
}
break;
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
return;
}
ctx.request_repaint();
let answer = rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
if !reply(&mut out, id, answer) {
return;
}
}
}
#[cfg(test)]
mod tests {
use std::io::BufRead;
use super::*;
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
#[test]
fn ephemeral_listener_uses_its_actual_port_for_the_token() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
assert_ne!(addr.port(), 0);
let _requests = start_listener(listener, egui::Context::default());
let token = materialcraft_automation::security::client_token(addr.port(), None).unwrap();
let (mut w, mut r) = connect(addr);
let auth = json!({"method": "auth", "params": {"token": token}}).to_string();
assert_eq!(call(&mut w, &mut r, &auth).unwrap()["ok"], true);
}
/// A server on a free port whose app side answers every request with its method name.
fn server() -> std::net::SocketAddr {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
std::thread::spawn(move || accept(listener, TOKEN, &tx, &egui::Context::default()));
std::thread::spawn(move || {
for r in rx {
let _ = r.reply.send(json!({"ok": true, "result": r.method}));
}
});
addr
}
fn connect(addr: std::net::SocketAddr) -> (TcpStream, BufReader<TcpStream>) {
let s = TcpStream::connect(addr).unwrap();
s.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
let r = BufReader::new(s.try_clone().unwrap());
(s, r)
}
fn call(w: &mut TcpStream, r: &mut BufReader<TcpStream>, line: &str) -> Option<Value> {
writeln!(w, "{line}").ok()?;
let mut reply = String::new();
(r.read_line(&mut reply).ok()? > 0).then(|| serde_json::from_str(&reply).unwrap())
}
#[test]
fn requests_need_the_token() {
let addr = server();
// Anything before `auth` is refused and the connection closed.
let (mut w, mut r) = connect(addr);
let denied = call(&mut w, &mut r, r#"{"id":1,"method":"command.run","params":{"id":"file.open"}}"#).unwrap();
assert_eq!(denied["ok"], false);
assert_eq!(denied["id"], 1);
assert!(call(&mut w, &mut r, r#"{"id":2,"method":"ping"}"#).is_none(), "closed after a refused request");
// A wrong token is refused and gets no second try.
let (mut w, mut r) = connect(addr);
let wrong = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{}x"}}}}"#, &TOKEN[1..]);
assert_eq!(call(&mut w, &mut r, &wrong).unwrap()["ok"], false);
let right = format!(r#"{{"id":2,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#);
assert!(call(&mut w, &mut r, &right).is_none());
// So is a malformed first line: no further lines before `auth`.
let (mut w, mut r) = connect(addr);
assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false);
assert!(call(&mut w, &mut r, &right).is_none(), "closed after malformed JSON before auth");
// The right token unlocks the connection.
let (mut w, mut r) = connect(addr);
let ok = call(&mut w, &mut r, &right).unwrap();
assert_eq!((ok["ok"].clone(), ok["id"].clone()), (json!(true), json!(2)));
let pong = call(&mut w, &mut r, r#"{"id":3,"method":"ping"}"#).unwrap();
assert_eq!((pong["result"].clone(), pong["id"].clone()), (json!("ping"), json!(3)));
assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false);
assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection");
}
#[test]
fn connections_are_limited_and_idle_ones_time_out() {
let addr = server();
let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect();
// Let the server take every idle connection before the one over the limit.
std::thread::sleep(Duration::from_millis(300));
// Read without writing: the server closes at once, and unread input would reset the
// connection before its reply arrives.
let (_, mut r) = connect(addr);
let mut full = String::new();
r.read_line(&mut full).unwrap();
assert_eq!(serde_json::from_str::<Value>(&full).unwrap()["error"], "too many connections");
// Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots.
for (_, mut r) in idle {
let mut rest = String::new();
assert_eq!(r.read_line(&mut rest).unwrap(), 0);
}
// A slot frees once its thread has ended, which can trail the client's EOF a little.
let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#);
let authed = (0..50).any(|_| {
let (mut w, mut r) = connect(addr);
let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true);
if !ok {
std::thread::sleep(Duration::from_millis(100));
}
ok
});
assert!(authed, "slots are freed after the auth deadline");
}
}
+38 -16
View File
@@ -1,6 +1,6 @@
//! MaterialCraft desktop app.
//!
//! Usage: `materialcraft [package.mcraft] [--control <port>] [--empty] [--version]`
//! Usage: `materialcraft [package.sbs|package.mcraft] [--control <port>] [--empty] [--version]`
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -26,11 +26,10 @@ fn version() -> String {
struct Args {
file: Option<String>,
control: Option<u16>,
empty: bool,
}
fn parse_args() -> Result<Option<Args>, String> {
let mut args = Args { file: None, control: None, empty: false };
let mut args = Args { file: None, control: None };
let mut it = std::env::args().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
@@ -39,14 +38,15 @@ fn parse_args() -> Result<Option<Args>, String> {
return Ok(None);
}
"--help" | "-h" => {
println!("{}\n\nUsage: materialcraft [package.mcraft] [--control <port>] [--empty]", version());
println!("{}\n\nUsage: materialcraft [package.sbs|package.mcraft] [--control <port>] [--empty]", version());
return Ok(None);
}
"--control" => {
let p = it.next().ok_or("--control needs a port")?;
args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?);
}
"--empty" => args.empty = true,
// Kept for scripts written before empty startup became the default.
"--empty" => {}
f if !f.starts_with('-') => args.file = Some(f.to_string()),
other => return Err(format!("unknown option `{other}`")),
}
@@ -55,18 +55,9 @@ fn parse_args() -> Result<Option<Args>, String> {
}
fn initial_session(args: &Args) -> Session {
let mut s = if args.empty {
let mut pkg = materialcraft_engine::core::Package::new("Untitled package");
pkg.graphs.push(materialcraft_engine::samples::template("pbr", "New_graph", 10));
Session::new(pkg)
} else {
materialcraft_engine::sample_session()
};
let mut s = materialcraft_engine::new_session();
if let Some(f) = &args.file {
match std::fs::read(f)
.map_err(|e| e.to_string())
.and_then(|b| materialcraft_engine::file_cmds::open_bytes(&mut s, &b, Some(f.clone())).map_err(|e| e.to_string()))
{
match materialcraft_engine::file_cmds::open_file(&mut s, f).map_err(|e| e.to_string()) {
Ok(()) => {}
Err(e) => eprintln!("materialcraft: could not open {f}: {e}"),
}
@@ -121,3 +112,34 @@ fn main() {
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn startup_without_a_file_has_one_empty_graph() {
let s = initial_session(&Args { file: None, control: None });
assert_eq!(s.pkg.name, "Untitled package");
assert_eq!(s.pkg.graphs.len(), 1);
let g = s.graph().unwrap();
assert_eq!(g.name, "New_graph");
assert!(g.nodes.is_empty());
assert!(g.connections.is_empty());
assert!(s.path.is_none());
assert!(!s.modified);
assert!(s.history().is_empty());
}
#[test]
fn startup_opens_the_requested_package() {
let path = std::env::temp_dir().join(format!("mc-startup-{}.mcraft", std::process::id()));
let original = materialcraft_engine::sample_session();
std::fs::write(&path, materialcraft_engine::file_cmds::save_bytes(&original).unwrap()).unwrap();
let s = initial_session(&Args { file: Some(path.to_string_lossy().into_owned()), control: None });
assert_eq!(s.pkg.graphs, original.pkg.graphs);
assert_eq!(s.path.as_deref(), path.to_str());
assert!(!s.modified);
std::fs::remove_file(path).unwrap();
}
}
+3
View File
@@ -24,5 +24,8 @@ base64 = { workspace = true }
cap-std = { workspace = true }
getrandom = { workspace = true }
[target.'cfg(unix)'.dependencies]
rustix = { workspace = true }
[dev-dependencies]
rmcp = { workspace = true, features = ["client"] }
+39 -20
View File
@@ -63,6 +63,21 @@ pub struct Headless {
light: Option<Lighting>,
}
/// Read a file under `fs`'s access rules.
fn read_file(fs: &Filesystem, path: &str) -> Result<Vec<u8>, AutomationError> {
match fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root <dir>")),
Filesystem::TrustedLocal => {
let len = std::fs::metadata(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))?.len();
if len > MAX_READ_BYTES {
return Err(bad(format!("{path} is {len} bytes (limit {MAX_READ_BYTES})")));
}
std::fs::read(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))
}
Filesystem::Workspace(w) => w.read(path),
}
}
impl Headless {
pub fn new(session: Session, fs: Filesystem) -> Headless {
Headless { session, fs, scene: None, light: None }
@@ -78,17 +93,7 @@ impl Headless {
}
fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
match &self.fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root <dir>")),
Filesystem::TrustedLocal => {
let len = std::fs::metadata(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))?.len();
if len > MAX_READ_BYTES {
return Err(bad(format!("{path} is {len} bytes (limit {MAX_READ_BYTES})")));
}
std::fs::read(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))
}
Filesystem::Workspace(w) => w.read(path),
}
read_file(&self.fs, path)
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
@@ -138,21 +143,33 @@ impl Headless {
batch_reply(results, None)
}
/// Open a `.mcraft` package.
/// Open an `.sbs` or `.mcraft` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules.
pub fn open(&mut self, path: &str) -> Result<Value, AutomationError> {
let bytes = self.read(path)?;
file_cmds::open_bytes(&mut self.session, &bytes, Some(path.to_string()))?;
let folder = path.replace('\\', "/").rsplit_once('/').map(|(folder, _)| format!("{folder}/")).unwrap_or_default();
let fs = &self.fs;
let linked = |relative: &str| -> Option<Vec<u8>> {
let relative = relative.trim().replace('\\', "/");
let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/');
let inside = relative.split('/').all(|part| !part.is_empty() && part != "." && part != "..");
if !plain || !inside {
return None;
}
read_file(fs, &format!("{folder}{relative}")).ok()
};
file_cmds::open_bytes_linked(&mut self.session, &bytes, Some(path.to_string()), &linked)?;
Ok(self.inspect())
}
/// Save the package (`.mcraft` appended when missing) to `path` or its own file.
/// Save to `path` (`.sbs` appended without a package extension) or the package's own file; SBS unless it is a `.mcraft`.
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError> {
let path = match path {
Some(p) if p.to_ascii_lowercase().ends_with(".mcraft") => p.to_string(),
Some(p) => format!("{p}.mcraft"),
None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet: give a `path`"))?,
Some(p) => file_cmds::package_path(p),
None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet (new, or opened from another program): give a `path`"))?,
};
let bytes = file_cmds::save_bytes(&self.session)?;
let bytes = file_cmds::save_bytes_as(&self.session, file_cmds::PackageFormat::of_path(&path))?;
self.write(&path, &bytes)?;
self.session.path = Some(path.clone());
self.session.modified = false;
@@ -170,8 +187,8 @@ 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) = file_cmds::export_params(&self.session, p)?;
let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth)?;
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)?;
self.create_dir_all(dir)?;
let mut written = Vec::new();
for f in files {
@@ -243,6 +260,8 @@ impl Headless {
height_scale: v.height_scale,
show_env: false,
supersample: 2,
transparency: v.transparency,
alpha_view: v.alpha_view,
..Settings::default()
};
let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max));
+20 -4
View File
@@ -18,7 +18,9 @@ use serde_json::{Value, json};
use crate::budgets::json_text;
use crate::headless::RenderOptions;
use crate::security::{ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches};
use crate::security::{
AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches,
};
use crate::{AutomationError, Headless, bad};
pub const METHODS: &[&str] = &[
@@ -160,6 +162,7 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st
let mut w = stream;
let mut line = String::new();
let mut authed = false;
let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?);
loop {
match read_bounded_line(&mut r, &mut line)? {
LineRead::Eof => return Ok(()),
@@ -178,15 +181,26 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st
if !authed {
return write_reply(&mut w, &json!({"id": id, "ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}));
}
drop(deadline.take());
write_reply(&mut w, &json!({"id": id, "ok": true}))?;
}
}
/// Listen on `127.0.0.1:port` (0 picks a port).
pub fn bind_tcp(port: u16) -> Result<TcpListener, AutomationError> {
TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))
}
/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared
/// session. `ready` gets the bound address.
pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> {
let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))?;
let listener = bind_tcp(port)?;
ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?);
serve_listener(listener, h, token)
}
/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session.
pub fn serve_listener(listener: TcpListener, h: Arc<Mutex<Headless>>, token: String) -> Result<(), AutomationError> {
let limiter = ConnectionLimiter::default();
let token = Arc::new(token);
for stream in listener.incoming() {
@@ -196,10 +210,12 @@ pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl
continue;
};
let (h, token) = (h.clone(), token.clone());
std::thread::spawn(move || {
if let Err(e) = std::thread::Builder::new().name("materialcraft-rpc-client".into()).spawn(move || {
let _permit = permit;
let _ = serve_connection(&h, stream, &token);
});
}) {
eprintln!("materialcraft: could not start an RPC connection: {e}");
}
}
Ok(())
}
+174 -8
View File
@@ -1,10 +1,13 @@
//! Tokens and bounded framing for the loopback JSON-lines transports (the app's control channel
//! and `materialcraft-cli serve` share the token conventions).
use std::io::BufRead;
use std::path::PathBuf;
use std::io::{BufRead, Read, Write};
use std::net::{Shutdown, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{RecvTimeoutError, Sender, channel};
use std::time::Duration;
use crate::{AutomationError, bad};
@@ -14,6 +17,10 @@ pub const TOKEN_ENV: &str = "MATERIALCRAFT_CONTROL_TOKEN";
pub const MAX_REQUEST_BYTES: usize = 8 << 20;
/// Simultaneous TCP connections served by `serve --port`.
pub const MAX_CONNECTIONS: usize = 16;
/// Largest token file read (a token is at most 1024 characters, plus whitespace).
const MAX_TOKEN_FILE_BYTES: u64 = 4096;
/// Time a TCP client has to authenticate before its connection is closed.
pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
/// Steps in one `command_batch`.
pub const MAX_BATCH_STEPS: usize = 256;
@@ -44,7 +51,7 @@ pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, Autom
Some(t) => t,
None => {
let path = token_file(port);
std::fs::read_to_string(&path)
read_token_file(&path)
.map_err(|e| bad(format!("no control token: set {TOKEN_ENV} or start the app with `--control {port}` so it writes {} ({e})", path.display())))?
}
};
@@ -54,7 +61,8 @@ pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, Autom
}
/// Token for a server on `port`: `MATERIALCRAFT_CONTROL_TOKEN`, else a fresh one written to
/// [`token_file`] (owner-only on Unix). Returns the token and where it was written.
/// [`token_file`] (owner-only on Unix). Returns the token and where it was written. Call it
/// once the port is bound, so a server that cannot listen never replaces another's token.
pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationError> {
if let Ok(t) = std::env::var(TOKEN_ENV) {
validate_token(t.trim())?;
@@ -62,13 +70,60 @@ pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationEr
}
let token = generate_token()?;
let path = token_file(port);
write_token_file(&path, &token).map_err(|e| {
AutomationError::Io(format!("cannot write the control token to {} ({e}); set {TOKEN_ENV} to a token of your own instead", path.display()))
})?;
Ok((token, Some(path)))
}
/// Write `token` to a new file at `path`, readable by the owner only on Unix. Whatever was at
/// `path` is removed first and the file is created exclusively (`O_EXCL`, which never follows
/// a symlink), so a file or link planted in a shared temp folder can neither keep its
/// permissions nor redirect the write; one that cannot be removed (another user's, in a sticky
/// `/tmp`) fails the call.
fn write_token_file(path: &Path, token: &str) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
let mut o = std::fs::OpenOptions::new();
o.write(true).create(true).truncate(true);
o.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes()));
res.map_err(|e| AutomationError::Io(format!("cannot write the control token to {}: {e}", path.display())))?;
Ok((token, Some(path)))
let mut f = o.open(path)?;
f.write_all(token.as_bytes())?;
f.sync_all()
}
/// Read a token file written by [`write_token_file`]. On Unix the file must be a regular file
/// (not a symlink, FIFO or device) owned by this user with no group or other permissions, so a
/// file another user planted is never trusted and a link can't make a client send one of its
/// own secrets as the token.
fn read_token_file(path: &Path) -> std::io::Result<String> {
#[cfg(unix)]
let file = {
use rustix::fs::{Mode, OFlags};
use std::os::unix::fs::MetadataExt;
let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
let file = std::fs::File::from(rustix::fs::open(path, flags, Mode::empty())?);
let meta = file.metadata()?;
let refuse = |why: &str| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("refusing the token file: {why}")));
if !meta.is_file() {
return refuse("not a regular file");
}
if meta.uid() != rustix::process::geteuid().as_raw() {
return refuse("owned by another user");
}
if meta.mode() & 0o077 != 0 {
return refuse("readable or writable by other users");
}
file
};
#[cfg(not(unix))]
let file = std::fs::File::open(path)?;
let mut out = String::new();
file.take(MAX_TOKEN_FILE_BYTES).read_to_string(&mut out)?;
Ok(out)
}
/// Compare equal-length tokens without an early exit.
@@ -134,6 +189,27 @@ impl Drop for Permit {
}
}
/// Closes a connection that has not authenticated in time, so idle or trickling clients can't
/// hold the few connection slots. Drop it once the client is authenticated (or gone).
pub struct AuthDeadline {
_cancel: Sender<()>,
}
impl AuthDeadline {
/// Shut `stream` down after `timeout` unless the returned deadline is dropped first.
pub fn start(stream: &TcpStream, timeout: Duration) -> std::io::Result<AuthDeadline> {
let stream = stream.try_clone()?;
let (tx, rx) = channel::<()>();
std::thread::Builder::new().name("materialcraft-auth-deadline".into()).spawn(move || {
// Dropping the deadline disconnects the channel and ends this thread at once.
if let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(timeout) {
let _ = stream.shutdown(Shutdown::Both);
}
})?;
Ok(AuthDeadline { _cancel: tx })
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -149,6 +225,76 @@ mod tests {
assert!(client_token(1, Some(format!(" {a}\n"))).is_ok());
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("mc-token-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn token_files_round_trip_and_replace_old_ones() {
let dir = scratch("round-trip");
let path = dir.join("t.token");
write_token_file(&path, "first-token-0123456789").unwrap();
assert_eq!(read_token_file(&path).unwrap(), "first-token-0123456789");
write_token_file(&path, "second-token-0123456789").unwrap();
assert_eq!(read_token_file(&path).unwrap(), "second-token-0123456789");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn token_files_are_owner_only_even_over_an_open_file() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch("perms");
let path = dir.join("t.token");
std::fs::write(&path, "old").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap();
write_token_file(&path, "fresh-token-0123456789").unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn token_files_never_write_through_a_symlink() {
let dir = scratch("symlink-write");
let (path, victim) = (dir.join("t.token"), dir.join("victim"));
std::fs::write(&victim, "keep me").unwrap();
std::os::unix::fs::symlink(&victim, &path).unwrap();
write_token_file(&path, "fresh-token-0123456789").unwrap();
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me");
assert!(!std::fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn unsafe_token_files_are_refused() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch("refuse");
// Readable by others: another user may have planted or read it.
let open = dir.join("open.token");
std::fs::write(&open, "planted-token-0123456789").unwrap();
std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(read_token_file(&open).is_err());
// A symlink, even to an owner-only file: a client must not send that file as its token.
let secret = dir.join("secret");
write_token_file(&secret, "private-0123456789abcdef").unwrap();
let link = dir.join("link.token");
std::os::unix::fs::symlink(&secret, &link).unwrap();
assert!(read_token_file(&link).is_err());
// A FIFO is refused without blocking on open or read.
let fifo = dir.join("fifo.token");
if std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) {
assert!(read_token_file(&fifo).is_err());
}
// A directory is not a token.
assert!(read_token_file(&dir).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn oversized_lines_are_skipped() {
let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10));
@@ -160,6 +306,26 @@ mod tests {
assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Eof));
}
#[test]
fn auth_deadline_closes_idle_connections_only() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let idle = TcpStream::connect(addr).unwrap();
let (server_idle, _) = listener.accept().unwrap();
let _deadline = AuthDeadline::start(&server_idle, Duration::from_millis(200)).unwrap();
let mut buf = [0u8; 1];
idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
assert_eq!(std::io::Read::read(&mut &idle, &mut buf).unwrap(), 0, "closed by the deadline");
let kept = TcpStream::connect(addr).unwrap();
let (server_kept, _) = listener.accept().unwrap();
drop(AuthDeadline::start(&server_kept, Duration::from_millis(200)).unwrap());
std::thread::sleep(Duration::from_millis(400));
(&server_kept).write_all(b"x").unwrap();
kept.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
assert_eq!(std::io::Read::read(&mut &kept, &mut buf).unwrap(), 1, "a met deadline leaves the connection open");
}
#[test]
fn limiter_releases() {
let l = ConnectionLimiter::default();
+11 -4
View File
@@ -126,8 +126,8 @@ pub struct PathParams {
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct SaveParams {
/// Forward-slash path relative to the write root (`.mcraft` is appended if missing). Omit to
/// save to the package's own file.
/// Forward-slash path relative to the write root (`.sbs` is appended unless it ends in `.sbs`
/// or `.mcraft`). Omit to save to the package's own file.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
@@ -154,6 +154,9 @@ pub struct ExportParams {
/// 8, 16 or 32 bits (default: the graph's output format).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub depth: Option<u32>,
/// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Graph index (default: the open graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
@@ -404,12 +407,16 @@ impl MaterialcraftMcp {
to_result(self.run("graph.node.param", params(&p)).await)
}
#[tool(description = "Open a .mcraft package (path relative to the read root). Returns the session.")]
#[tool(
description = "Open an .sbs or .mcraft package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
)]
async fn package_open(&self, Parameters(p): Parameters<PathParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.open", params(&p)).await)
}
#[tool(description = "Save the package as .mcraft (path relative to the write root; omit to save to its own file).")]
#[tool(
description = "Save the package (path relative to the write root; omit to save to its own file). Saves SBS (.sbs, the main format) unless the path ends in .mcraft."
)]
async fn package_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.save", params(&p)).await)
}
+25
View File
@@ -124,6 +124,31 @@ impl Node {
}
}
/// The definition id of a placeholder for a node MaterialCraft does not have (a library node or
/// atomic filter named in an SBS file). The node keeps its wires and the data needed to write it
/// back; its ports come from [`missing_ports`] and it cooks to a soft error.
pub const MISSING_NODE: &str = "missing_node";
/// The ports of a [`MISSING_NODE`] placeholder: input ids, and output ids with whether each is
/// grayscale. They are stored as comma-separated text in its `inputs` and `outputs` parameters
/// (`outputs` entries are `id` or `id:gray`).
pub fn missing_ports(node: &Node) -> (Vec<String>, Vec<(String, bool)>) {
let list = |key: &str| -> Vec<String> {
match node.params.get(key) {
Some(Value::Text(s)) => s.split(',').map(str::trim).filter(|p| !p.is_empty()).take(64).map(str::to_string).collect(),
_ => Vec::new(),
}
};
let outputs = list("outputs")
.into_iter()
.map(|o| match o.split_once(':') {
Some((id, kind)) => (id.to_string(), kind == "gray"),
None => (o, false),
})
.collect();
(list("inputs"), outputs)
}
/// A link from an output port to an input port.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
+2 -2
View File
@@ -14,8 +14,8 @@ pub mod package;
pub mod value;
pub use graph::{
Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, Node, NodeId, OutputFormat, Pin, Preset,
SizeMode,
Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat,
Pin, Preset, SizeMode, missing_ports,
};
pub use package::{PACKAGE_EXT, Package, Resource, ResourceBytes};
pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear};
+1
View File
@@ -54,6 +54,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::graph_cmds::specs());
v.extend(crate::node_cmds::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::wire_cmds::specs());
v
})
}
+160 -29
View File
@@ -1,6 +1,9 @@
//! File menu: new/open/save packages, new graphs from templates, bitmap resources and texture
//! export. Host-path commands are native only; the browser and agents use the byte-based
//! functions (`open_bytes`, `save_bytes`, `export_outputs`).
//!
//! SBS (`.sbs`) is the main project format; `.mcraft` packages still open and save as `.mcraft`.
//! What an SBS file holds that MaterialCraft can't read is a warning (Console, `package.warnings`), never an error.
use serde_json::{Value as J, json};
@@ -23,15 +26,31 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
new_graph
),
cmd!("file.newPackage", "Empty package", ["File", "New"], None, "{name?} replaces the session with an empty package", always, new_package),
cmd!("file.open", "Open...", ["File"], Some("Ctrl+O"), "{path} opens a .mcraft package", always, open),
cmd!("file.save", "Save", ["File"], Some("Ctrl+S"), "{path?} saves the package (.mcraft) to its own file or `path`", always, save),
cmd!(
"file.open",
"Open...",
["File"],
Some("Ctrl+O"),
"{path} opens an .sbs or .mcraft package (or a .mcmat material's source); returns `warnings` for what an SBS file holds that MaterialCraft can't read yet, and `path`, null for a file another program wrote (Save then needs a new `path`)",
always,
open
),
cmd!(
"file.save",
"Save",
["File"],
Some("Ctrl+S"),
"{path?} saves the package to its own file or `path`: SBS (.sbs, the default; appended when `path` has no package extension) or .mcraft",
always,
save
),
cmd!("file.saveAs", "Save as...", ["File"], Some("Ctrl+Shift+S"), "{path} saves the package under a new name", always, save),
cmd!(
"file.export",
"Export outputs...",
["File"],
Some("Ctrl+Shift+E"),
"{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), graph?} cooks the graph at full size and writes every output",
"{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",
has_graph,
export
),
@@ -84,34 +103,135 @@ pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
s.reset_history();
s.modified = false;
s.dirty = true;
s.load_warnings.clear();
}
/// Open package bytes (any platform). A portable material (`.mcmat`) opens the package it was
/// cooked from, on its graph, with no file name (saving must not overwrite the material).
/// A package file format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PackageFormat {
/// SBS XML, the main project format.
Sbs,
/// The older native zip format.
Mcraft,
}
impl PackageFormat {
/// The format a file at `path` is saved in: `.mcraft` stays `.mcraft`, anything else is SBS.
pub fn of_path(path: &str) -> PackageFormat {
if has_extension(path, PackageFormat::Mcraft.ext()) { PackageFormat::Mcraft } else { PackageFormat::Sbs }
}
pub fn ext(self) -> &'static str {
match self {
PackageFormat::Sbs => materialcraft_formats::sbs::SBS_EXT,
PackageFormat::Mcraft => materialcraft_core::PACKAGE_EXT,
}
}
}
fn has_extension(path: &str, ext: &str) -> bool {
path.rsplit_once('.').is_some_and(|(_, e)| e.eq_ignore_ascii_case(ext))
}
/// `path` with `.sbs` appended unless it already ends in `.sbs` or `.mcraft`.
pub fn package_path(path: &str) -> String {
if [PackageFormat::Sbs, PackageFormat::Mcraft].iter().any(|f| has_extension(path, f.ext())) {
path.to_string()
} else {
format!("{path}.{}", PackageFormat::Sbs.ext())
}
}
/// Open package bytes on any platform: SBS, `.mcraft`, or a `.mcmat` material's source package.
pub fn open_bytes(s: &mut Session, bytes: &[u8], name: Option<String>) -> Result<()> {
open_bytes_linked(s, bytes, name, &|_| None)
}
/// [`open_bytes`] with `linked` loading files an SBS package links to; materials and SBS files from other programs open unnamed so Save can't overwrite them.
pub fn open_bytes_linked(s: &mut Session, bytes: &[u8], name: Option<String>, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<()> {
if materialcraft_formats::material::is_material(bytes) {
let (manifest, source) = materialcraft_formats::material::read_material(bytes)?;
replace_package(s, materialcraft_formats::load_package(&source)?, None);
s.graph = s.pkg.graph_by_name(&manifest.graph).map_or(0, |(i, _)| i);
return Ok(());
}
let pkg = materialcraft_formats::load_package(bytes)?;
replace_package(s, pkg, name);
// A broken `.sbs` should report an SBS error, but a renamed zip package still opens
let named_sbs = name.as_deref().is_some_and(|n| has_extension(n, PackageFormat::Sbs.ext())) && !bytes.starts_with(b"PK");
if !named_sbs && !materialcraft_formats::sbs::is_sbs(bytes) {
replace_package(s, materialcraft_formats::load_package(bytes)?, name);
return Ok(());
}
let read = materialcraft_formats::sbs::read_sbs(bytes, name.as_deref().unwrap_or(""), linked)?;
let from_elsewhere = !read.exact;
replace_package(s, read.pkg, if from_elsewhere { None } else { name.clone() });
if !read.warnings.is_empty() {
s.warn(format!("{} opened with {} warning(s): what MaterialCraft can't read yet is listed below", s.pkg.name, read.warnings.len()));
for warning in &read.warnings {
s.warn(warning.clone());
}
}
if from_elsewhere && let Some(file) = &name {
s.log(format!("{file} was not saved by MaterialCraft: Save asks for a new file, so the original keeps everything MaterialCraft can't read"));
}
s.load_warnings = read.warnings;
Ok(())
}
/// The package as `.mcraft` bytes.
/// The package as SBS bytes, the main project format.
pub fn save_bytes(s: &Session) -> Result<Vec<u8>> {
Ok(materialcraft_formats::save_package(&s.pkg)?)
save_bytes_as(s, PackageFormat::Sbs)
}
pub fn save_bytes_as(s: &Session, format: PackageFormat) -> Result<Vec<u8>> {
Ok(match format {
PackageFormat::Sbs => materialcraft_formats::sbs::write_sbs(&s.pkg)?,
PackageFormat::Mcraft => materialcraft_formats::save_package(&s.pkg)?,
})
}
/// Largest file an SBS package may link to.
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINKED_FILE_BYTES: u64 = 256 << 20;
/// Reads files an SBS package at `path` links to: plain relative paths that resolve inside its folder.
#[cfg(not(target_arch = "wasm32"))]
pub fn linked_files(path: &str) -> impl Fn(&str) -> Option<Vec<u8>> + use<> {
let parent = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));
let folder = std::fs::canonicalize(parent).ok();
move |relative: &str| {
let relative = relative.trim().replace('\\', "/");
let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/');
if !plain || std::path::Path::new(&relative).components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
return None;
}
let folder = folder.as_ref()?;
let file = std::fs::canonicalize(folder.join(&relative)).ok()?;
let metadata = std::fs::metadata(&file).ok()?;
if !file.starts_with(folder) || !metadata.is_file() || metadata.len() > MAX_LINKED_FILE_BYTES {
return None;
}
std::fs::read(file).ok()
}
}
/// Open the package file at `path` (native), with the bitmaps an SBS package keeps next to it.
#[cfg(not(target_arch = "wasm32"))]
pub fn open_file(s: &mut Session, path: &str) -> Result<()> {
let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?;
open_bytes_linked(s, &bytes, Some(path.to_string()), &linked_files(path))
}
#[cfg(not(target_arch = "wasm32"))]
fn open(s: &mut Session, p: &J) -> Result<J> {
let path = strp(p, "path").ok_or_else(|| bad("file.open", "`path` is required"))?;
let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?;
open_bytes(s, &bytes, Some(path.to_string()))?;
open_file(s, path)?;
s.log(format!("Opened {path}"));
Ok(json!({"name": s.pkg.name, "graphs": s.pkg.graphs.len()}))
Ok(json!({"name": s.pkg.name, "graphs": s.pkg.graphs.len(), "path": s.path, "warnings": s.load_warnings}))
}
#[cfg(target_arch = "wasm32")]
@@ -122,16 +242,11 @@ fn open(_: &mut Session, _: &J) -> Result<J> {
#[cfg(not(target_arch = "wasm32"))]
fn save(s: &mut Session, p: &J) -> Result<J> {
let path = match strp(p, "path") {
Some(path) => {
let mut path = path.to_string();
if !path.to_ascii_lowercase().ends_with(".mcraft") {
path.push_str(".mcraft");
}
path
}
None => s.path.clone().ok_or_else(|| bad("file.save", "the package has no file yet: give a `path`"))?,
Some(path) => package_path(path),
None => s.path.clone().ok_or_else(|| bad("file.save", "the package has no file yet (new, or opened from another program): give a `path`"))?,
};
let bytes = save_bytes(s)?;
let bytes = save_bytes_as(s, PackageFormat::of_path(&path))?;
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
s.path = Some(path.clone());
s.modified = false;
@@ -151,9 +266,22 @@ pub struct Exported {
}
/// 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>) -> Result<Vec<Exported>> {
let g = s.pkg.graph(gi)?;
let cooked = s.cook_full(gi);
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));
}
let g = pkg.graph(gi)?;
let dec = s.resource_decoder();
let cooked = {
let mut cache = s.cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &mut cache)
};
let mut out = Vec::new();
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
let Some(img) = img else { continue };
@@ -169,8 +297,10 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
Ok(out)
}
/// Export params: (graph index, extension, pattern, depth).
pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option<Depth>)> {
/// 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();
@@ -185,14 +315,15 @@ pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Optio
Some(32) => Some(Depth::F32),
Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))),
};
Ok((gi, ext, pattern, depth))
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))
}
#[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) = export_params(s, p)?;
let files = export_outputs(s, gi, &ext, &pattern, depth)?;
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}")))?;
let mut written = Vec::new();
for f in files {
+1 -1
View File
@@ -49,7 +49,7 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
})
});
json!({
"package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::<Vec<_>>()},
"package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::<Vec<_>>()},
"graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "nodes": g.nodes.len(), "kind": g.kind})).collect::<Vec<_>>(),
"openGraph": s.graph,
"graph": graph_json,
+9 -1
View File
@@ -17,9 +17,10 @@ pub mod node_cmds;
pub mod samples;
pub mod session;
pub mod view_cmds;
pub mod wire_cmds;
pub use commands::{CommandSpec, command_specs, execute, find};
pub use session::{CameraPrefs, Clip, Session, View2d, View3d};
pub use session::{CameraPrefs, Clip, Session, View2d, View3d, WARNING_PREFIX};
pub use materialcraft_core as core;
pub use materialcraft_eval as eval;
@@ -48,6 +49,13 @@ pub type Result<T> = std::result::Result<T, EngineError>;
/// Version string shown in About, `--version` and window titles.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// A fresh, unsaved package with one empty graph, used at desktop and browser startup.
pub fn new_session() -> Session {
let mut pkg = core::Package::new("Untitled package");
pkg.graphs.push(samples::template("empty", "New_graph", 10));
Session::new(pkg)
}
/// A session on the built-in sample package (the brick wall).
pub fn sample_session() -> Session {
Session::new(samples::sample_package())
+34 -1
View File
@@ -36,6 +36,11 @@ pub struct View3d {
pub height_scale: f32,
pub show_axis: bool,
pub show_grid: bool,
/// See through the mesh where the material's alpha (opacity output, else base color alpha)
/// is below one.
pub transparency: bool,
/// Show the material's alpha channel on the mesh instead of the lit material.
pub alpha_view: bool,
}
impl Default for View3d {
@@ -53,6 +58,8 @@ impl Default for View3d {
height_scale: 0.012,
show_axis: false,
show_grid: false,
transparency: true,
alpha_view: false,
}
}
}
@@ -118,6 +125,9 @@ pub struct Clip {
pub connections: Vec<materialcraft_core::Connection>,
}
/// The prefix of warning lines in [`Session::log`].
pub const WARNING_PREFIX: &str = "Warning: ";
pub struct Session {
pub pkg: Package,
/// Where the package was opened from or last saved to.
@@ -133,6 +143,8 @@ pub struct Session {
pub camera: CameraPrefs,
pub modified: bool,
pub log: Vec<String>,
/// What the last opened SBS package held that MaterialCraft couldn't read; empty after a clean open.
pub load_warnings: Vec<String>,
pub clipboard: Option<Clip>,
/// The last cook of the open graph.
pub cooked: Cooked,
@@ -162,6 +174,7 @@ impl Session {
camera: CameraPrefs::default(),
modified: false,
log: Vec::new(),
load_warnings: Vec::new(),
clipboard: None,
cooked: Cooked::default(),
dirty: true,
@@ -320,7 +333,7 @@ impl Session {
&self.cooked
}
/// Cook graph `gi` at full size (exports), without touching the preview results.
/// Cook graph `gi` at full size, without touching the preview results.
pub fn cook_full(&self, gi: usize) -> Cooked {
let dec = self.resource_decoder();
let opts = Options::new(&dec);
@@ -369,6 +382,26 @@ impl Session {
Ok(())
}
/// Nodes of the open graph whose last cook failed, with the error, and how many placeholders for missing SBS nodes failed besides.
pub fn cook_failures(&self) -> (Vec<(NodeId, &str)>, usize) {
let mut failed = Vec::new();
let mut placeholders = 0;
for node in self.graph().map(|g| g.nodes.as_slice()).unwrap_or_default() {
let Some(error) = self.cooked.nodes.get(&node.id).and_then(|r| r.error.as_deref()) else { continue };
if node.def == materialcraft_core::MISSING_NODE {
placeholders += 1;
} else {
failed.push((node.id, error));
}
}
(failed, placeholders)
}
/// Log a warning, shown highlighted in the Console.
pub fn warn(&mut self, msg: impl Into<String>) {
self.log(format!("{WARNING_PREFIX}{}", msg.into()));
}
pub fn log(&mut self, msg: impl Into<String>) {
self.log.push(msg.into());
if self.log.len() > 500 {
+7 -1
View File
@@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"3D view settings",
[],
None,
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?}",
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
always,
view3d
),
@@ -144,6 +144,12 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
if let Some(b) = boolp(p, "grid") {
v.show_grid = b;
}
if let Some(b) = boolp(p, "transparency") {
v.transparency = b;
}
if let Some(b) = boolp(p, "alphaView") {
v.alpha_view = b;
}
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
}
+129
View File
@@ -0,0 +1,129 @@
//! Wire commands: edit wires (connections) of the open graph, each addressed by the input it
//! feeds (`to`, `toPort`): split a wire with a reroute dot so it can be repositioned, delete
//! several wires at once, and swap (reverse) where a set of wires come from.
use serde_json::{Value as J, json};
use materialcraft_core::{Connection, NodeId};
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.wire.insertDot",
"Insert reroute dot",
[],
None,
"{to, toPort, at? [x, y] (graph point, default: midway)} splits the wire feeding to.toPort with a Dot node there, selected",
has_graph,
insert_dot
),
cmd!(
"graph.wire.delete",
"Delete links",
[],
None,
"{wires: [{to, toPort}, ...]} deletes the wires feeding those inputs, in one undo step",
has_graph,
delete
),
cmd!(
"graph.wire.swap",
"Swap links",
[],
None,
"{wires: [{to, toPort}, ...] (two or more)} reverses where the wires come from: sorted by target node and input order, the first wire's source goes to the last input and so on (two wires swap)",
has_graph,
swap
),
]
}
/// Most wires one command takes (a graph has far fewer inputs in practice).
const MAX_WIRES: usize = 4096;
/// The wires named by `wires: [{to, toPort}, ...]`, each existing and named once.
fn wires_param(s: &Session, id: &str, p: &J) -> Result<Vec<Connection>> {
let list = p.get("wires").and_then(J::as_array).ok_or_else(|| bad(id, "`wires` is a list of {to, toPort}"))?;
if list.len() > MAX_WIRES {
return Err(bad(id, format!("at most {MAX_WIRES} wires")));
}
let g = s.graph()?;
let mut out: Vec<Connection> = Vec::with_capacity(list.len());
for w in list {
let to = w.get("to").and_then(J::as_u64).map(NodeId).ok_or_else(|| bad(id, "each wire needs `to`"))?;
let port = w.get("toPort").and_then(J::as_str).ok_or_else(|| bad(id, "each wire needs `toPort`"))?;
let c = g.input_of(to, port).ok_or_else(|| bad(id, format!("no wire feeds `{port}` of node {}", to.0)))?;
if out.iter().any(|o| o.to == c.to && o.to_port == c.to_port) {
return Err(bad(id, format!("the wire into `{port}` of node {} is listed twice", to.0)));
}
out.push(c.clone());
}
Ok(out)
}
fn delete(s: &mut Session, p: &J) -> Result<J> {
let wires = wires_param(s, "graph.wire.delete", p)?;
if wires.is_empty() {
return Err(bad("graph.wire.delete", "no wire given"));
}
s.edit("Delete links", |s| {
let g = s.graph_mut()?;
for c in &wires {
g.disconnect(c.to, &c.to_port);
}
Ok(json!({"deleted": wires.len()}))
})
}
fn swap(s: &mut Session, p: &J) -> Result<J> {
const ID: &str = "graph.wire.swap";
let mut wires = wires_param(s, ID, p)?;
if wires.len() < 2 {
return Err(bad(ID, "select two or more wires to swap"));
}
// A stable order whatever order the wires were picked in: target node, then input order.
let order = |s: &Session, c: &Connection| (c.to.0, s.input_ports(c.to).iter().position(|p| *p == c.to_port).unwrap_or(usize::MAX));
wires.sort_by_key(|c| order(s, c));
let sources: Vec<(NodeId, String)> = wires.iter().rev().map(|c| (c.from, c.from_port.clone())).collect();
s.edit("Swap links", |s| {
let g = s.graph_mut()?;
// Unplug them all first, so no half-swapped state is mistaken for a cycle.
for c in &wires {
g.disconnect(c.to, &c.to_port);
}
for (c, (from, port)) in wires.iter().zip(&sources) {
g.connect(*from, port, c.to, &c.to_port).map_err(|_| bad(ID, format!("swapping would feed node {} into itself (a cycle)", c.to.0)))?;
}
Ok(json!({"swapped": wires.len()}))
})
}
fn insert_dot(s: &mut Session, p: &J) -> Result<J> {
const ID: &str = "graph.wire.insertDot";
let to = NodeId(u64p(p, "to").ok_or_else(|| bad(ID, "`to` is required"))?);
let to_port = strp(p, "toPort").ok_or_else(|| bad(ID, "`toPort` is required"))?.to_string();
let g = s.graph()?;
let c = g.input_of(to, &to_port).cloned().ok_or_else(|| bad(ID, format!("no wire feeds `{to_port}` of node {}", to.0)))?;
let at = match point(p, "at") {
Some(at) => at,
None => {
let (a, b) = (g.node(c.from)?.pos, g.node(to)?.pos);
[(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]
}
};
// Hostile but finite coordinates stay within a sane canvas.
let at = at.map(|v| v.clamp(-1e7, 1e7));
s.edit("Insert reroute dot", |s| {
let id = s.graph_mut()?.add_node("dot", at);
let input = s.input_ports(id).into_iter().next().ok_or_else(|| bad(ID, "the dot has no input"))?;
let output = s.output_ports(id).into_iter().next().ok_or_else(|| bad(ID, "the dot has no output"))?;
let g = s.graph_mut()?;
g.connect(c.from, &c.from_port, id, &input)?;
g.connect(id, &output, to, &to_port)?;
s.selection = vec![id];
Ok(json!({"id": id.0}))
})
}
+253
View File
@@ -83,9 +83,164 @@ fn package_save_and_open_round_trip() {
let out = dir.join("tex");
let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8}));
assert_eq!(r["files"].as_array().unwrap().len(), 6);
let small = dir.join("small");
run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64}));
let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path();
let img = materialcraft_formats::decode(&std::fs::read(file).unwrap()).unwrap();
assert_eq!((img.w, img.h), (64, 64));
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.
#[test]
fn export_size_keeps_proportions_and_clamps() {
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();
files.iter().map(|f| materialcraft_formats::decode(&f.bytes).unwrap()).map(|i| (i.w, i.h)).collect::<Vec<_>>()
};
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));
s.pkg.graphs[0].size = [u32::MAX, u32::MAX];
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32)));
}
/// A scratch folder for one test, removed when dropped.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new(name: &str) -> TempDir {
let dir = std::env::temp_dir().join(format!("mc-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
TempDir(dir)
}
fn file(&self, name: &str) -> String {
self.0.join(name).to_str().unwrap().to_string()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A path without a package extension saves as `.sbs` and opens back exactly; `.mcraft` still saves and opens.
#[test]
fn sbs_is_the_default_save_format_and_mcraft_still_works() {
let dir = TempDir::new("sbs-default");
let mut s = sample_session();
let before = s.pkg.clone();
let sbs = run(&mut s, "file.save", json!({"path": dir.file("bricks")}))["path"].as_str().unwrap().to_string();
assert!(sbs.ends_with("bricks.sbs"), "{sbs}");
assert!(std::fs::read(&sbs).unwrap().starts_with(b"<?xml"));
run(&mut s, "file.newPackage", json!({}));
let opened = run(&mut s, "file.open", json!({"path": sbs}));
assert_eq!(opened["warnings"], json!([]));
assert_eq!(s.pkg.graphs, before.graphs);
assert_eq!(s.pkg.resources, before.resources);
assert_eq!(run(&mut s, "file.save", json!({}))["path"], json!(sbs));
let mcraft = dir.file("bricks.mcraft");
run(&mut s, "file.save", json!({"path": mcraft}));
assert!(std::fs::read(&mcraft).unwrap().starts_with(b"PK"));
run(&mut s, "file.newPackage", json!({}));
run(&mut s, "file.open", json!({"path": mcraft}));
assert_eq!(s.pkg.graphs, before.graphs);
assert_eq!(run(&mut s, "file.save", json!({}))["path"], json!(mcraft));
assert!(std::fs::read(&mcraft).unwrap().starts_with(b"PK"), "an opened .mcraft stays .mcraft");
}
/// Saving an SBS file another program wrote must not overwrite it: MaterialCraft can't write back what it couldn't read.
#[test]
fn saving_an_sbs_file_from_another_program_needs_a_new_name() {
let dir = TempDir::new("sbs-theirs");
let theirs = dir.file("theirs.sbs");
let xml = r#"<?xml version="1.0"?><package><content><graph><identifier v="G"/><compNodes><compNode><uid v="1"/><compImplementation><compFilter><filter v="curve"/><parameters><parameter><name v="curveluminance"/><paramValue><constantValueString v="POINTS"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph><function><identifier v="their_function"/></function></content></package>"#;
std::fs::write(&theirs, xml).unwrap();
let mut s = sample_session();
let opened = run(&mut s, "file.open", json!({"path": theirs}));
assert_eq!(opened["path"], json!(null));
assert!(execute(&mut s, "file.save", &json!({})).is_err());
assert_eq!(std::fs::read_to_string(&theirs).unwrap(), xml, "the original is untouched");
// Saved under a new name it becomes a MaterialCraft file, which saves in place from then on
let mine = run(&mut s, "file.save", json!({"path": dir.file("mine.sbs")}))["path"].as_str().unwrap().to_string();
run(&mut s, "file.open", json!({"path": mine}));
assert_eq!(run(&mut s, "file.save", json!({}))["path"], json!(mine));
}
#[test]
fn a_broken_sbs_file_reports_an_sbs_error_and_a_renamed_mcraft_opens() {
let dir = TempDir::new("sbs-broken");
let broken = dir.file("broken.sbs");
std::fs::write(&broken, b"\xff\xfe<\x00p\x00").unwrap();
let mut s = sample_session();
let error = execute(&mut s, "file.open", &json!({"path": broken})).unwrap_err().to_string();
assert!(error.contains("SBS"), "{error}");
let renamed = dir.file("renamed.sbs");
std::fs::write(&renamed, materialcraft_engine::file_cmds::save_bytes_as(&s, materialcraft_engine::file_cmds::PackageFormat::Mcraft).unwrap()).unwrap();
run(&mut s, "file.open", json!({"path": renamed}));
}
/// An SBS file full of nodes MaterialCraft lacks opens: gaps are warnings, placeholders cook to an error, commands still work.
#[test]
fn an_sbs_file_with_missing_nodes_opens_softly() {
let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs/all_nodes.sbs");
let mut s = sample_session();
s.preview_size = Some(32);
let opened = run(&mut s, "file.open", json!({"path": sample.to_str().unwrap()}));
let warnings = opened["warnings"].as_array().unwrap();
assert!(warnings.len() > 100, "{} warnings", warnings.len());
assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("missing node")));
assert!(s.log.iter().filter(|l| l.starts_with(materialcraft_engine::WARNING_PREFIX)).count() > 100);
let inspect = run(&mut s, "session.inspect", json!({}));
assert_eq!(inspect["package"]["warnings"].as_array().map(Vec::len), Some(warnings.len()));
assert!(s.pkg.resources.iter().any(|r| r.name == "Untitled_Bitmap" && !r.bytes.is_empty()), "the bitmap next to the package loads");
s.cook();
let graph = s.graph().unwrap();
let placeholder = graph.nodes.iter().find(|n| n.def == materialcraft_engine::core::MISSING_NODE).unwrap().id;
let mapped = graph.nodes.iter().find(|n| n.def == "perlin_noise").unwrap().id;
assert!(s.cooked.nodes[&placeholder].error.as_deref().unwrap_or("").contains("not in MaterialCraft's library"));
assert!(s.cooked.nodes[&mapped].error.is_none());
let (failed, placeholders) = s.cook_failures();
assert!(placeholders > 300 && failed.len() < 10, "{} failed, {placeholders} placeholders", failed.len());
// Commands on a placeholder are errors or no-ops, never panics
s.selection = vec![placeholder];
for (id, params) in [
("graph.node.param", json!({"id": placeholder.0, "param": "scale", "value": 2})),
("edit.copy", json!({})),
("edit.paste", json!({})),
("edit.duplicate", json!({})),
("graph.node.delete", json!({"ids": [placeholder.0]})),
("edit.undo", json!({})),
] {
let _ = execute(&mut s, id, &params);
}
for spec in command_specs().iter().filter(|spec| !spec.id.starts_with("file.")) {
let _ = execute(&mut s, spec.id, &json!({}));
}
s.cook();
run(&mut s, "file.newPackage", json!({}));
assert!(s.load_warnings.is_empty(), "a new package clears the warnings");
}
/// Every command, run with empty and hostile params, returns Ok or Err but never panics.
#[test]
fn panic_hunt() {
@@ -203,3 +358,101 @@ fn reimported_bitmap_shows_new_pixels() {
let after = s.resource_decoder()("tex").unwrap().data[0];
assert!(after - before > 0.5, "{before} -> {after}");
}
#[test]
fn a_wire_splits_with_a_reroute_dot_and_deletes() {
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "empty"}));
let a = run(&mut s, "graph.node.add", json!({"def": "clouds_1", "at": [0, 0]}))["id"].as_u64().unwrap();
let b = run(&mut s, "graph.node.add", json!({"def": "levels", "at": [400, 0]}))["id"].as_u64().unwrap();
run(&mut s, "graph.connect", json!({"from": a, "to": b}));
let dot = run(&mut s, "graph.wire.insertDot", json!({"to": b, "toPort": "input", "at": [200, 80]}))["id"].as_u64().unwrap();
let g = s.graph().unwrap();
let d = materialcraft_engine::core::NodeId(dot);
assert_eq!(g.node(d).unwrap().def, "dot");
assert_eq!(g.node(d).unwrap().pos, [200.0, 80.0]);
assert_eq!(g.connections.len(), 2);
assert_eq!(g.input_of(d, "input").unwrap().from.0, a);
assert_eq!(g.input_of(materialcraft_engine::core::NodeId(b), "input").unwrap().from.0, dot);
assert_eq!(s.selection, vec![d]);
// The material still cooks through the dot.
s.cook();
assert!(s.cooked.nodes.values().all(|r| r.error.is_none()));
// One undo step restores the straight wire.
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.graph().unwrap().nodes.len(), 2);
assert_eq!(s.graph().unwrap().input_of(materialcraft_engine::core::NodeId(b), "input").unwrap().from.0, a);
// No wire there: an error, nothing changes.
assert!(execute(&mut s, "graph.wire.insertDot", &json!({"to": a, "toPort": "input"})).is_err());
// Deleting the wire.
run(&mut s, "graph.disconnect", json!({"to": b, "toPort": "input"}));
assert!(s.graph().unwrap().connections.is_empty());
}
#[test]
fn every_template_is_opaque_in_the_3d_view() {
// The 3D view sees through a base color whose alpha is below one: the templates must not.
let mut s = sample_session();
s.preview_size = Some(64);
for (id, _) in materialcraft_engine::samples::TEMPLATES {
run(&mut s, "file.new", json!({"template": id, "size": 64}));
s.cook();
for (usage, img) in s.material_maps() {
if usage == "baseColor" && !img.is_gray() {
let min = img.data.chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min);
assert!(min >= 0.999, "{id}: base color alpha goes down to {min}");
}
}
}
}
#[test]
fn selected_wires_swap_their_sources_and_delete_together() {
use materialcraft_engine::core::NodeId;
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "empty"}));
let a = run(&mut s, "graph.node.add", json!({"def": "clouds_1", "at": [0, 0]}))["id"].as_u64().unwrap();
let b = run(&mut s, "graph.node.add", json!({"def": "perlin_noise", "at": [0, 200]}))["id"].as_u64().unwrap();
let m = run(&mut s, "graph.node.add", json!({"def": "checker", "at": [0, 400]}))["id"].as_u64().unwrap();
let blend = run(&mut s, "graph.node.add", json!({"def": "blend", "at": [300, 100]}))["id"].as_u64().unwrap();
run(&mut s, "graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
run(&mut s, "graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
run(&mut s, "graph.connect", json!({"from": m, "to": blend, "toPort": "mask"}));
let src = |s: &Session, port: &str| s.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0;
let fg_bg = json!({"wires": [{"to": blend, "toPort": "background"}, {"to": blend, "toPort": "foreground"}]});
// Two wires swap, whatever order they are listed in; the other input is left alone.
run(&mut s, "graph.wire.swap", fg_bg.clone());
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (b, a, m));
run(&mut s, "graph.wire.swap", fg_bg.clone());
assert_eq!((src(&s, "foreground"), src(&s, "background")), (a, b));
// Three wires reverse in input order: foreground <-> mask, background stays.
let all = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "background"}, {"to": blend, "toPort": "mask"}]});
run(&mut s, "graph.wire.swap", all.clone());
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (m, b, a));
// One undo step each.
run(&mut s, "edit.undo", json!({}));
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (a, b, m));
// Bad requests change nothing.
for bad in [
json!({}),
json!({"wires": [{"to": blend, "toPort": "foreground"}]}),
json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "foreground"}]}),
json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": a, "toPort": "input"}]}),
] {
assert!(execute(&mut s, "graph.wire.swap", &bad).is_err(), "{bad}");
}
assert_eq!(src(&s, "foreground"), a);
// A swap that would make a cycle is refused and rolled back: blend -> levels, then swap the
// wire into levels with the wire into blend's foreground.
let lv = run(&mut s, "graph.node.add", json!({"def": "levels", "at": [600, 100]}))["id"].as_u64().unwrap();
run(&mut s, "graph.connect", json!({"from": blend, "to": lv}));
let cyc = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": lv, "toPort": "input"}]});
assert!(execute(&mut s, "graph.wire.swap", &cyc).is_err());
assert_eq!(src(&s, "foreground"), a);
assert_eq!(s.graph().unwrap().connections.len(), 4);
// Deleting several wires is one step.
run(&mut s, "graph.wire.delete", all);
assert_eq!(s.graph().unwrap().connections.len(), 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.graph().unwrap().connections.len(), 4);
}
+95 -37
View File
@@ -9,14 +9,14 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value};
use materialcraft_image::{Image, Kind};
use materialcraft_nodes::{Ctx, NodeDef, PortKind, find, resolve_params};
use materialcraft_nodes::{Ctx, NodeDef, PortKind, clamp_params, find, resolve_params};
/// Sub-graphs may nest this deep (a graph instancing itself would recurse forever).
pub const MAX_DEPTH: u32 = 8;
@@ -53,6 +53,12 @@ pub fn ports(pkg: &Package, node: &Node) -> (Vec<Port>, Vec<Port>) {
};
return (io("input"), io("output"));
}
if node.def == materialcraft_core::MISSING_NODE {
let (ins, outs) = materialcraft_core::missing_ports(node);
let ins = ins.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect();
let outs = outs.into_iter().map(|(id, gray)| Port { label: id.clone(), id, kind: if gray { PortKind::Gray } else { PortKind::Color } }).collect();
return (ins, outs);
}
let Some(def) = find(&node.def) else { return (Vec::new(), Vec::new()) };
let conv = |p: &materialcraft_nodes::PortDef| Port { id: p.id.into(), label: p.label.into(), kind: p.kind };
(def.inputs.iter().map(conv).collect(), def.outputs.iter().map(conv).collect())
@@ -297,31 +303,28 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook
out
}
/// A hash of graph `gi` and everything it reaches: its own JSON, the content of every
/// resource its nodes name, and (recursively) every graph it instances. A cycle hashes as a
/// marker; `cook_instance` reports it as an error.
fn graph_tree_hash(pkg: &Package, gi: usize, stack: &mut Vec<usize>) -> u64 {
let Some(graph) = pkg.graphs.get(gi) else { return 0 };
if stack.len() > MAX_DEPTH as usize {
return 1;
}
/// Hash each reachable graph and its resource content once. An iterative walk keeps
/// deep chains and graphs with many shared instances bounded by the package size.
fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 {
let mut h = DefaultHasher::new();
serde_json::to_string(graph).unwrap_or_default().hash(&mut h);
for n in &graph.nodes {
if let Some(Value::Text(name)) = n.params.get("resource") {
pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h);
}
if n.def != "graph_instance" {
let mut pending = vec![gi];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
match instance_graph(pkg, n) {
Some((si, _)) if stack.contains(&si) => "cycle".hash(&mut h),
Some((si, _)) => {
stack.push(si);
graph_tree_hash(pkg, si, stack).hash(&mut h);
stack.pop();
let Some(graph) = pkg.graphs.get(index) else { continue };
index.hash(&mut h);
serde_json::to_string(graph).unwrap_or_default().hash(&mut h);
for n in &graph.nodes {
if let Some(Value::Text(name)) = n.params.get("resource") {
pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h);
}
if n.def == "graph_instance"
&& let Some((si, _)) = instance_graph(pkg, n)
{
pending.push(si);
}
None => 0u64.hash(&mut h),
}
}
h.finish()
@@ -387,6 +390,12 @@ fn cook_node(
Err(e) => return fail(format!("function of `{param}`: {e}"), 0),
}
}
// Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook).
if let Some(d) = def
&& node.def != "graph_instance"
{
clamp_params(d, &mut params);
}
let tile = node.base.tiling[0] && node.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();
@@ -394,7 +403,7 @@ fn cook_node(
Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()),
_ => 0,
};
let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si, &mut vec![si])) } else { 0 };
let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 };
let key = hash_of(&(
&node.def,
serde_json::to_string(&params).unwrap_or_default(),
@@ -414,6 +423,9 @@ fn cook_node(
} else if let Some(img) = input_img {
let img = img.resize(w, h, tile);
Ok(vec![if node.def == "input_grayscale" { img.to_gray() } else { img }])
} else if node.def == materialcraft_core::MISSING_NODE {
let name = if node.label.is_empty() { "this node" } else { node.label.as_str() };
Err(format!("`{name}` is not in MaterialCraft's library yet: kept as a placeholder from the SBS file"))
} else if node.def == "graph_instance" {
cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, &params, (w, h), opts, cache)
} else if let Some(d) = def {
@@ -433,20 +445,23 @@ fn cook_node(
}
}
/// Whether graph `from` instances graph `target`, directly or through other instanced graphs.
/// `seen` holds the graphs already visited.
fn instances_reach(pkg: &Package, from: usize, target: usize, seen: &mut Vec<usize>) -> bool {
let Some(graph) = pkg.graphs.get(from) else { return false };
graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)).any(|(si, _)| {
if si == target {
return true;
/// Whether graph `from` reaches `target`, without recursive stack growth.
fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool {
let mut pending = vec![from];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
if seen.contains(&si) {
return false;
let Some(graph) = pkg.graphs.get(index) else { continue };
for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) {
if si == target {
return true;
}
pending.push(si);
}
seen.push(si);
instances_reach(pkg, si, target, seen)
})
}
false
}
fn cook_instance(
@@ -465,7 +480,7 @@ fn cook_instance(
return Err("graph instances nest too deep (does a graph use itself?)".into());
}
let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?;
if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi, &mut vec![sub_gi]) {
if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) {
return Err(format!("graph `{}` uses itself through a graph instance", sub.name));
}
let mut o = Options::new(opts.resource);
@@ -557,6 +572,18 @@ mod tests {
assert_eq!(outputs(&p.graphs[0], &c).len(), 1);
}
#[test]
fn hostile_param_is_clamped_before_cooking() {
let (mut p, noise, _, _) = sample();
let blur = p.graphs[0].add_node("anisotropic_blur", [150.0, 100.0]);
p.graphs[0].connect(noise, "output", blur, "input").unwrap();
p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30));
let mut cache = Cache::default();
let c = cook(&p, 0, &Options::new(&no_res), &mut cache);
assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error);
assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((64, 64)));
}
#[test]
fn preview_cap_and_unknown_nodes() {
let (mut p, _, _, out) = sample();
@@ -634,6 +661,37 @@ mod tests {
assert!((second.image(out_a, 0).unwrap().mean()[0] - 0.8).abs() < 0.01);
}
#[test]
fn deep_shared_instance_walks_stay_bounded() {
std::thread::Builder::new()
.stack_size(128 * 1024)
.spawn(|| {
let mut pkg = Package::new("deep");
for index in 0..2000 {
let mut graph = Graph::new(&format!("g{index}"));
// Repeated references must visit the next graph only once.
for _ in 0..4 {
let id = graph.add_node("graph_instance", [0.0; 2]);
graph.node_mut(id).unwrap().params.insert("graph".into(), Value::Text(format!("g{}", index + 1)));
}
pkg.graphs.push(graph);
}
assert!(instances_reach(&pkg, 0, 1999));
assert!(!instances_reach(&pkg, 0, 2000));
let before = graph_tree_hash(&pkg, 0);
pkg.graphs[1999].seed = 42;
assert_ne!(before, graph_tree_hash(&pkg, 0));
// A back edge must terminate both traversals too.
pkg.graphs[1999].nodes[0].params.insert("graph".into(), Value::Text("g0".into()));
assert!(instances_reach(&pkg, 1, 0));
assert!(!instances_reach(&pkg, 0, 2000));
assert_ne!(before, graph_tree_hash(&pkg, 0));
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn mutual_instances_are_an_error() {
let (x, xi) = instancing("x", "y");
+5 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "materialcraft-formats"
description = "MaterialCraft file formats: .mcraft packages, bitmap import, texture export"
description = "MaterialCraft file formats: .sbs and .mcraft packages, bitmap import, texture export"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -12,6 +12,7 @@ workspace = true
materialcraft-core = { workspace = true }
materialcraft-image = { workspace = true }
materialcraft-geom = { workspace = true }
materialcraft-nodes = { workspace = true }
gltf = { workspace = true }
tobj = { workspace = true }
image = { workspace = true }
@@ -19,3 +20,6 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
zip = { workspace = true }
roxmltree = { workspace = true }
flate2 = { workspace = true }
base64 = { workspace = true }
+2 -1
View File
@@ -1,6 +1,6 @@
//! # materialcraft-formats
//!
//! File formats, L2: the native `.mcraft` package (a zip holding `package.json` and the embedded
//! File formats, L2: SBS packages (`.sbs`, the main project format, see [`sbs`]), the older native `.mcraft` package (a zip holding `package.json` and the embedded
//! `resources/`), bitmap decoding for Bitmap nodes, and texture export (PNG 8/16, JPEG, TGA,
//! TIFF 8/16, BMP, WEBP, EXR 32F, HDR) with the output naming pattern, and meshes for the 3D view
//! (OBJ, glTF/GLB), and portable materials (`.mcmat`, see [`material`]). Byte-based APIs work
@@ -10,6 +10,7 @@
pub mod material;
pub mod mesh;
pub mod sbs;
use std::collections::HashMap;
use std::io::{Cursor, Read, Write};
File diff suppressed because it is too large. Load diff
+31
View File
@@ -425,6 +425,8 @@ fn hsl(ctx: &Ctx) -> CookResult {
pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 {
let span = in_high - in_low;
let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) };
// NaN (from an input or a hostile parameter) would otherwise spread through the graph.
let t = if t.is_finite() { t } else { 0.0 };
let mid = in_mid.clamp(0.001, 0.999);
let g = 0.5f32.ln() / mid.ln();
out_low + t.powf(g) * (out_high - out_low)
@@ -522,3 +524,32 @@ pub fn output_kind(def: &NodeDef, port: usize, inputs: &[Option<Image>]) -> Kind
_ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind),
}
}
#[cfg(test)]
mod levels_tests {
use super::levels_fn;
#[test]
fn levels_remaps_the_input_range_midtones_and_output_range() {
let close = |a: f32, b: f32| (a - b).abs() < 1e-5;
// Identity by default.
for v in [0.0, 0.25, 0.5, 1.0] {
assert!(close(levels_fn(v, 0.0, 0.5, 1.0, 0.0, 1.0), v));
}
// The input range stretches and clips.
assert!(close(levels_fn(0.4, 0.2, 0.5, 0.6, 0.0, 1.0), 0.5));
assert!(close(levels_fn(0.1, 0.2, 0.5, 0.6, 0.0, 1.0), 0.0));
assert!(close(levels_fn(0.9, 0.2, 0.5, 0.6, 0.0, 1.0), 1.0));
// Mid is relative to the input range: the value there becomes 0.5.
assert!(close(levels_fn(0.25, 0.0, 0.25, 1.0, 0.0, 1.0), 0.5));
assert!(close(levels_fn(0.3, 0.2, 0.25, 0.6, 0.0, 1.0), 0.5));
// The output range, inverted when low > high.
assert!(close(levels_fn(0.5, 0.0, 0.5, 1.0, 0.2, 0.6), 0.4));
assert!(close(levels_fn(0.0, 0.0, 0.5, 1.0, 1.0, 0.0), 1.0));
// A collapsed input range is a threshold; NaN never escapes.
assert_eq!(levels_fn(0.49, 0.5, 0.5, 0.5, 0.0, 1.0), 0.0);
assert_eq!(levels_fn(0.5, 0.5, 0.5, 0.5, 0.0, 1.0), 1.0);
assert!(levels_fn(f32::NAN, 0.0, 0.5, 1.0, 0.0, 1.0).is_finite());
assert!(levels_fn(0.5, f32::NAN, 0.5, f32::NAN, 0.0, 1.0).is_finite());
}
}
+54
View File
@@ -352,6 +352,60 @@ pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> {
out
}
/// How many slider spans the hard limit extends past each end of a parameter's range.
const HARD_SPAN: f32 = 16.0;
/// Clamp `v` to `[lo, hi]`; a non-finite `v` becomes `fallback`.
fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 {
if v.is_finite() { v.clamp(lo, hi) } else { fallback }
}
/// Clamp numeric parameters to hard limits: the declared slider range widened by
/// `HARD_SPAN` spans on each side (the editor lets values past the slider through, so the
/// slider range itself is not a limit). Non-finite values become the default. Keeps cooks
/// bounded whatever a file, binding, function or command supplies.
pub fn clamp_params(def: &NodeDef, params: &mut BTreeMap<String, Value>) {
for p in &def.params {
let Some(v) = params.get_mut(p.id) else { continue };
if let Value::Enum(i) = v {
if !p.options.is_empty() {
*i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX));
}
continue;
}
if let Value::Color(c) = v {
for x in c {
*x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0);
}
continue;
}
if p.min >= p.max {
continue;
}
let span = p.max - p.min;
let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span);
// The default's component `i`, or 0 when the default is a different variant.
let fallback = |i: usize| match &p.default {
Value::Float(d) => [*d].get(i).copied(),
Value::Float2(d) => d.get(i).copied(),
Value::Float3(d) => d.get(i).copied(),
Value::Float4(d) => d.get(i).copied(),
_ => None,
};
let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0));
let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32;
match v {
Value::Float(x) => clamp_at(x, 0),
Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Int(x) => clamp_int(x),
Value::Int2(a) => a.iter_mut().for_each(clamp_int),
_ => {}
}
}
}
/// Parameter values for a node: catalog defaults overlaid with `overrides`.
pub fn resolve_params(def: &NodeDef, overrides: &BTreeMap<String, Value>) -> BTreeMap<String, Value> {
let mut m: BTreeMap<String, Value> = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect();
+14 -4
View File
@@ -361,7 +361,8 @@ fn contrast_luminosity(ctx: &Ctx) -> CookResult {
}
fn exposure(ctx: &Ctx) -> CookResult {
let k = 2f32.powf(ctx.f("stops"));
// Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite.
let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0));
per_value(ctx, |v| v * k)
}
@@ -504,7 +505,15 @@ fn anisotropic_blur(ctx: &Ctx) -> CookResult {
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))])
}
/// Most extra horizontal passes `blur_xy` runs: a cost bound, whatever sigma it is given.
const MAX_BLUR_PASSES: i64 = 64;
/// Widest horizontal kernel half-width `blur_xy` builds: a cost bound on the kernel allocation.
const MAX_KERNEL_RADIUS: i64 = 512;
fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image {
if !sx.is_finite() || !sy.is_finite() {
return img.clone();
}
// Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so
// blur fully with the smaller sigma and add the extra along x by repeated small passes.
let base = ops::gaussian(img, sy, tile);
@@ -512,12 +521,12 @@ fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image {
if extra < 0.1 {
return base;
}
let n = (extra / 2.0).ceil().max(1.0) as i64;
let n = ((extra / 2.0).ceil().max(1.0) as i64).min(MAX_BLUR_PASSES);
let step = extra / (n as f32).sqrt();
let mut out = base;
for _ in 0..n {
let src = out.clone();
let r = (step * 2.0).ceil() as i64;
let r = ((step * 2.0).ceil() as i64).clamp(1, MAX_KERNEL_RADIUS);
let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect();
let sum: f32 = k.iter().sum();
out = Image::generate(src.w, src.h, src.kind, |x, y| {
@@ -687,7 +696,8 @@ fn edge_detect(ctx: &Ctx) -> CookResult {
.map(|(a, b)| {
let d = a.sqrt().max(b.sqrt());
let t = (1.0 - d / w).max(0.0);
t.powf(1.0 - round * 0.8)
// A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2.
t.powf((1.0 - round * 0.8).max(0.01))
})
.collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
+2 -1
View File
@@ -222,7 +222,8 @@ fn smoothstep_node(ctx: &Ctx) -> CookResult {
}
fn s_curve(ctx: &Ctx) -> CookResult {
let (k, p) = (1.0 + ctx.f("amount") * 4.0, ctx.f("pivot").clamp(0.01, 0.99));
// A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1).
let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99));
per_channel(ctx, |v, _| {
let v = v.clamp(0.0, 1.0);
if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) }
+2 -1
View File
@@ -357,7 +357,8 @@ fn plasma(ctx: &Ctx) -> CookResult {
fn turbulence(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).sqrt())])
// A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN.
Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())])
}
fn creased(ctx: &Ctx) -> CookResult {
+46 -1
View File
@@ -28,12 +28,13 @@ pub mod svg;
pub mod text;
pub mod weathering;
pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, find, resolve_params};
pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, clamp_params, find, resolve_params};
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_image::{Image, Kind};
use super::*;
@@ -72,6 +73,50 @@ mod tests {
assert!(catalog().len() >= 200, "{} nodes", catalog().len());
}
/// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN):
/// the hard limits keep the cook bounded, finite and the right size.
#[test]
fn every_node_survives_hostile_params() {
use std::time::{Duration, Instant};
let mut slow: Vec<(String, Duration)> = Vec::new();
let total = Instant::now();
for def in catalog() {
if def.id == "graph_instance" {
continue;
}
for p in &def.params {
for h in [1e30_f32, -1e30, f32::NAN] {
let v = match p.default {
Value::Float(_) => Value::Float(h),
Value::Int(_) => Value::Int(h as i32),
Value::Float2(_) => Value::Float2([h, h]),
Value::Enum(_) => Value::Enum(h as u32),
_ => continue,
};
let mut params = resolve_params(def, &BTreeMap::from([(p.id.to_string(), v)]));
clamp_params(def, &mut params);
let inputs = vec![None; def.inputs.len()];
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let ctx = Ctx { w: 16, h: 16, seed: 7, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
let t = Instant::now();
let out = (def.cook)(&ctx).unwrap_or_else(|e| panic!("{}.{}={h}: {e}", def.id, p.id));
let dt = t.elapsed();
assert!(dt < Duration::from_secs(2), "{}.{}={h} took {dt:?}", def.id, p.id);
if dt > Duration::from_millis(250) {
slow.push((format!("{}.{}={h}", def.id, p.id), dt));
}
for img in &out {
assert_eq!((img.w, img.h), (16, 16), "{}.{}={h}", def.id, p.id);
assert!(img.data.iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id);
}
}
}
}
eprintln!("hostile params: total {:?}; cooks over 250 ms: {slow:?}", total.elapsed());
}
#[test]
fn noises_tile() {
for id in [
+98 -16
View File
@@ -182,6 +182,11 @@ pub struct Settings {
pub ao_rays: u32,
/// Strength of a shadow-casting key light from the camera's upper left (0 = off).
pub key_light: f32,
/// See through the surface where the material's alpha (the opacity output, else the base
/// color's alpha channel) is below one: what lies behind, back faces included, shows through.
pub transparency: bool,
/// Show the material's alpha channel on the mesh, unlit (white = opaque, black = clear).
pub alpha_view: bool,
}
impl Default for Settings {
@@ -199,6 +204,8 @@ impl Default for Settings {
supersample: 1,
ao_rays: 0,
key_light: 0.0,
transparency: true,
alpha_view: false,
}
}
}
@@ -257,10 +264,23 @@ fn rotate_y(v: Vec3, deg: f32) -> Vec3 {
Vec3::new(v.x * c + v.z * s, v.y, -v.x * s + v.z * c)
}
/// The material's alpha at `uv`: the opacity output, else the base color's alpha channel, else
/// opaque.
fn alpha(maps: &Maps, uv: Vec2) -> f32 {
let a = match (&maps.opacity, &maps.base_color) {
(Some(o), _) => o.sample_gray(uv.x, uv.y, true),
(None, Some(b)) if !b.is_gray() => b.sample(uv.x, uv.y, true)[3],
_ => 1.0,
};
if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }
}
/// Transparent surfaces a ray passes through before it gives up (what is left shows the
/// background).
const MAX_LAYERS: usize = 8;
/// Per-pixel inputs of [`shade`] beyond the camera ray.
struct Px {
/// Backdrop color (seen through transparent areas).
bg: Vec3,
/// Direction toward the key light.
key: Vec3,
/// Random rotation of the ambient occlusion ray pattern.
@@ -301,8 +321,16 @@ fn direct(n: Vec3, v: Vec3, l: Vec3, base: Vec3, f0: Vec3, metal: f32, rough: f3
(diff + spec) * ndl
}
/// Shade one camera ray; `None` = missed the mesh.
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Vec3> {
/// A shaded surface point: linear color (or the alpha value in [`Settings::alpha_view`]), its
/// alpha and the ray distance.
struct Shaded {
color: Vec3,
alpha: f32,
t: f32,
}
/// Shade the first surface along one ray; `None` = missed the mesh.
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Shaded> {
let hit = scene.bvh.closest(origin, dir, f32::MAX)?;
let m = &scene.mesh;
let [i0, i1, i2] = m.tri(hit.tri as usize)?;
@@ -310,6 +338,8 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
let w0 = 1.0 - w1 - w2;
let lerp3 = |a: Vec3, b: Vec3, c: Vec3| a * w0 + b * w1 + c * w2;
let nrm = lerp3(*m.normals.get(i0)?, *m.normals.get(i1)?, *m.normals.get(i2)?).normalize_or_zero();
// A back face (seen through a transparent front, or under an open mesh) faces the viewer.
let nrm = if nrm.dot(dir) > 0.0 { -nrm } else { nrm };
let (t0, t1, t2) = (*m.tangents.get(i0)?, *m.tangents.get(i1)?, *m.tangents.get(i2)?);
let tan = (t0.truncate() * w0 + t1.truncate() * w1 + t2.truncate() * w2).normalize_or_zero();
let sign = if t0.w < 0.0 { -1.0 } else { 1.0 };
@@ -346,6 +376,10 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
}
uv = cur;
}
let a = alpha(maps, uv);
if s.alpha_view {
return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t });
}
let base = tex(&maps.base_color, uv).map_or(Vec3::splat(0.5), |c| Vec3::new(c[0], c[1], c[2]));
let rough = tex_gray(&maps.roughness, uv, 0.5).clamp(0.02, 1.0);
let metal = tex_gray(&maps.metallic, uv, 0.0).clamp(0.0, 1.0);
@@ -385,11 +419,27 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
if let Some(e) = tex(&maps.emissive, uv) {
c += Vec3::new(e[0], e[1], e[2]);
}
if let Some(o) = &maps.opacity {
let a = o.sample_gray(uv.x, uv.y, true).clamp(0.0, 1.0);
c = c * a + px.bg * (1.0 - a);
Some(Shaded { color: c, alpha: if s.transparency { a } else { 1.0 }, t: hit.t })
}
/// Follow one camera ray through up to [`MAX_LAYERS`] transparent surfaces, compositing front to
/// back (`miss` is what shows behind the mesh). Shaded colors are scaled by the exposure `k`.
#[allow(clippy::too_many_arguments)]
fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, k: f32, miss: Vec3) -> Vec3 {
let mut acc = Vec3::ZERO;
let mut through = 1.0;
let mut o = origin;
let step = scene.radius * 1e-4;
for _ in 0..MAX_LAYERS {
let Some(h) = shade(scene, maps, light, s, o, dir, px) else { return acc + miss * through };
acc += h.color * k * h.alpha * through;
through *= 1.0 - h.alpha;
if through < 1e-3 {
return acc;
}
o += dir * (h.t + step);
}
Some(c)
acc + miss * through
}
/// The studio backdrop at screen position `p` (−1..1): a soft vignette (linear).
@@ -440,18 +490,27 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0;
let ray = cam.ray(Vec2::new(px, py), aspect);
let bg = backdrop(Vec2::new(px, py));
let p = Px { bg, key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
acc += match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
Some(c) => c * k,
None => match (s.show_env, bg_env) {
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
_ => bg,
},
let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
let miss = match (s.show_env, bg_env) {
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
_ => bg,
};
acc += if s.alpha_view {
// Display values: the alpha as is, the background tone mapped.
match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
Some(h) => h.color,
None => miss.map(|v| linear_to_srgb(aces(v))),
}
} else {
trace(scene, maps, light, s, ray.origin, ray.dir, &p, k, miss)
};
}
}
let c = acc / (ss * ss) as f32;
let q = |v: f32| (linear_to_srgb(aces(v)) * 255.0 + 0.5) as u8;
let q = |v: f32| {
let d = if s.alpha_view { v } else { linear_to_srgb(aces(v)) };
(d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
};
if let Some(px) = row.get_mut(x * 4..x * 4 + 4) {
px.copy_from_slice(&[q(c.x), q(c.y), q(c.z), 255]);
}
@@ -484,6 +543,29 @@ mod tests {
}
}
#[test]
fn alpha_shows_what_lies_behind_and_the_alpha_view_shows_the_channel() {
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
let red = |a: f32| Maps { base_color: Some(Image::filled(16, 16, Kind::Color, [0.8, 0.1, 0.1, a])), ..Maps::default() };
let c = ((24 * 64 + 32) * 4) as usize;
let s = Settings::default();
let opaque = render(&scene, &red(1.0), &light, &s, 64, 48);
let clear = render(&scene, &red(0.0), &light, &s, 64, 48);
assert!(opaque[c] > opaque[c + 1] + 40, "opaque center is red: {:?}", &opaque[c..c + 3]);
// Fully clear: the backdrop shows through both the front and the back of the sphere.
let bg = backdrop(Vec2::new(32.5 / 64.0 * 2.0 - 1.0, 1.0 - 24.5 / 48.0 * 2.0));
let bg = (linear_to_srgb(aces(bg.x)) * 255.0 + 0.5) as u8;
assert!(clear[c..c + 3].iter().all(|v| v.abs_diff(bg) <= 1), "clear {:?} vs backdrop {bg}", &clear[c..c + 3]);
// Transparency off: alpha is ignored.
assert_eq!(render(&scene, &red(0.0), &light, &Settings { transparency: false, ..s }, 64, 48), opaque);
// An opacity output wins over the base color's alpha.
let half = Maps { opacity: Some(Image::filled(16, 16, Kind::Gray, [0.5; 4])), ..red(1.0) };
let px = render(&scene, &half, &light, &Settings { alpha_view: true, ..s }, 64, 48);
assert!(px[c].abs_diff(128) <= 1 && px[c] == px[c + 1], "alpha view: {:?}", &px[c..c + 3]);
let px = render(&scene, &red(1.0), &light, &Settings { alpha_view: true, ..s }, 64, 48);
assert_eq!(&px[c..c + 3], &[255, 255, 255]);
}
#[test]
fn a_cancelled_render_gives_up_and_an_uncancelled_one_matches_render() {
let (scene, light, maps, s) = (Scene::builtin("sphere"), Lighting::new("studio"), Maps::default(), Settings::default());
+2 -1
View File
@@ -23,6 +23,7 @@ image = { workspace = true }
zip = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sys-locale = "0.3"
rfd = { workspace = true }
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
@@ -33,7 +34,7 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration"] }
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] }
# winit needs a window system on Linux, so the crate's own tests build with X11.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
+7 -1
View File
@@ -55,7 +55,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
open = Some(i);
}
resp.context_menu(|ui| {
for (label, a) in [("Open", "open"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
for (label, a) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
if ui.button(tr(label)).clicked() {
action = Some((a, i));
ui.close();
@@ -70,6 +70,12 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
Some(("open", i)) => {
app.run("graph.open", json!({"graph": i}));
}
Some(("export", i)) => {
// The export window works on the open graph.
if app.run("graph.open", json!({"graph": i})).is_some() {
app.ui.windows.export = true;
}
}
Some(("duplicate", i)) => {
app.run("graph.duplicate", json!({"graph": i}));
}
+92
View File
@@ -0,0 +1,92 @@
//! Arabic fallback fonts for the UI. egui's default fonts have no Arabic glyphs, so translated
//! UIs need fallback fonts from the operating system.
//!
//! Windows: Segoe UI, Tahoma, Arial
//! macOS: SF Arabic, Geeza Pro, Arial Unicode
//! Linux: Noto Sans Arabic, DejaVu Sans
use std::sync::Arc;
use egui::{FontData, FontFamily};
/// Candidate system font files: (path, face index in a collection).
#[cfg(not(target_arch = "wasm32"))]
fn system_files() -> Vec<(std::path::PathBuf, u32)> {
use std::path::PathBuf;
let mut v: Vec<(PathBuf, u32)> = Vec::new();
if cfg!(windows) {
let fonts = PathBuf::from(std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into())).join("Fonts");
let files: &[&str] = &["segoeui.ttf", "tahoma.ttf", "arial.ttf"];
v.extend(files.iter().map(|f| (fonts.join(f), 0)));
} else if cfg!(target_os = "macos") {
let files: &[&str] = &["/System/Library/Fonts/SFArabic.ttf", "/System/Library/Fonts/Supplemental/GeezaPro.ttc"];
v.extend(files.iter().map(|f| (PathBuf::from(f), 0)));
v.push((PathBuf::from("/System/Library/Fonts/Supplemental/Arial Unicode.ttf"), 0));
} else {
for f in [
"/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/google-noto/NotoSansArabic-Regular.ttf",
"/usr/local/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
"/usr/local/share/fonts/dejavu/DejaVuSans.ttf",
] {
v.push((PathBuf::from(f), 0));
}
}
v
}
/// Fallback fonts manager for the egui context.
#[derive(Default)]
pub struct UiFonts {
installed: bool,
data: Option<Arc<FontData>>,
}
impl UiFonts {
/// Update fallback fonts according to active language and whether the preferences dialog is open.
pub fn update(&mut self, ctx: &egui::Context, language: &str, preferences_open: bool) {
let want_arabic = language == "ar" || preferences_open;
if !want_arabic || self.installed {
return;
}
let Some(data) = self.load_arabic() else { return };
let mut defs = crate::theme::font_definitions();
let name = "script-Arab".to_string();
defs.font_data.insert(name.clone(), data);
defs.families.entry(FontFamily::Proportional).or_default().push(name.clone());
defs.families.entry(FontFamily::Monospace).or_default().push(name);
ctx.set_fonts(defs);
self.installed = true;
}
/// Whether an Arabic fallback font has been found and loaded.
pub fn covers_arabic(&self) -> bool {
self.data.is_some()
}
fn load_arabic(&mut self) -> Option<Arc<FontData>> {
if let Some(d) = &self.data {
return Some(d.clone());
}
#[cfg(not(target_arch = "wasm32"))]
for (path, index) in system_files() {
let Ok(meta) = std::fs::metadata(&path) else { continue };
if !meta.is_file() || meta.len() == 0 || meta.len() > (128 << 20) {
continue;
}
if let Ok(bytes) = std::fs::read(&path) {
let mut data = FontData::from_owned(bytes);
data.index = index;
let arc = Arc::new(data);
self.data = Some(arc.clone());
log::info!("UI font fallback for Arabic: {}", path.display());
return Some(arc);
}
}
log::warn!("no font found for Arabic text; system fonts may show boxes");
None
}
}
+448 -42
View File
@@ -4,9 +4,12 @@
//! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire
//! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route
//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to
//! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or
//! double-click the canvas for the node search, right-click for menus, drop library items to add
//! them. Every edit is an engine command; the gestures only draw previews until they commit.
//! zoom, click a node to show it in the 2D view (double-click a graph instance to open its graph),
//! Space, Tab or double-click the canvas for the node search, right-click for menus, drop library
//! items to add them. Click a wire to select it (Shift or Ctrl+click adds more; Delete removes them, X swaps
//! where they come from), drag a wire to pull a reroute dot out of it, double-click a wire to drop
//! a dot there, right-click a wire for its menu. Every edit is an
//! engine command; the gestures only draw previews until they commit.
use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
use egui_phosphor::regular as icon;
@@ -32,14 +35,40 @@ pub struct LibraryDrag(pub String);
#[derive(Clone, Debug)]
enum Drag {
Nodes { delta: Vec2 },
Box { start: Pos2 },
Wire { from: (NodeId, String), detached: Option<(NodeId, String)> },
Nodes {
delta: Vec2,
},
Box {
start: Pos2,
},
Wire {
from: (NodeId, String),
detached: Option<(NodeId, String)>,
},
/// Pressed on a wire: a click selects it, a drag pulls a reroute dot out of it.
WirePress {
wire: WireRef,
start: Pos2,
},
Pan,
Frame { id: u64, delta: Vec2, resize: bool, nodes: Vec<NodeId> },
Comment { id: u64, delta: Vec2 },
Frame {
id: u64,
delta: Vec2,
resize: bool,
nodes: Vec<NodeId>,
},
Comment {
id: u64,
delta: Vec2,
},
}
/// A wire, named by the input it feeds: (node, input port).
pub type WireRef = (NodeId, String);
/// Pointer distance (points) within which a wire is hit.
const WIRE_HIT: f32 = 5.0;
/// The node search popup (Space or Tab).
#[derive(Clone, Debug)]
struct Search {
@@ -76,6 +105,12 @@ pub struct GraphView {
menu_at: Pos2,
/// The graph the camera last framed.
framed_graph: Option<usize>,
/// The selected wires, in the order they were picked (Delete removes them, X swaps them).
pub selected_wires: Vec<WireRef>,
/// The wire the context menu is for (right-clicked on a wire).
menu_wire: Option<WireRef>,
/// Wires on screen last frame: the wire and its bezier control points.
pub wires: Vec<(WireRef, [Pos2; 4])>,
}
impl Default for GraphView {
@@ -90,6 +125,9 @@ impl Default for GraphView {
view: Rect::NOTHING,
menu_at: Pos2::ZERO,
framed_graph: None,
selected_wires: Vec::new(),
menu_wire: None,
wires: Vec::new(),
}
}
}
@@ -169,10 +207,47 @@ fn port_pos(r: Rect, i: usize, n: usize, output: bool, dot: bool) -> Pos2 {
pos2(if output { r.right() } else { r.left() }, start + i as f32 * PORT_GAP)
}
fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) {
/// Control points of the wire from output `a` to input `b` (screen space).
fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] {
let dx = ((b.x - a.x).abs() * 0.5).max(30.0);
let shape = egui::epaint::CubicBezierShape::from_points_stroke([a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b], false, Color32::TRANSPARENT, stroke);
p.add(shape);
[a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b]
}
fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) {
p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke));
}
/// The point at `t` (0..1) along a cubic bezier.
fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 {
let u = 1.0 - t;
let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t];
pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum())
}
/// Distance from `p` to a cubic bezier (sampled as a polyline).
fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 {
const N: usize = 32;
let mut best = f32::INFINITY;
let mut prev = c[0];
for i in 1..=N {
let q = bezier_at(c, i as f32 / N as f32);
let (seg, rel) = (q - prev, p - prev);
let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
best = best.min((prev + seg * t).distance(p));
prev = q;
}
best
}
/// The wire nearest `p` within [`WIRE_HIT`] points.
fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> {
wires
.iter()
.filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p))
.map(|(w, c)| (w, bezier_distance(c, p)))
.filter(|(_, d)| *d <= WIRE_HIT)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(w, _)| w)
}
/// The graph panel: toolbar row and canvas.
@@ -333,6 +408,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) {
app.ui.frame_all = false;
app.graph.framed_graph = Some(app.session.graph);
app.graph.selected_wires.clear();
frame(app, rect, false);
}
let painter = ui.painter_at(rect);
@@ -461,6 +537,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
Some(Drag::Wire { detached: Some(d), .. }) => Some(d.clone()),
_ => None,
};
let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(g.connections.len());
for c in &g.connections {
if detached.as_ref().is_some_and(|(n, p)| *n == c.to && *p == c.to_port) {
continue;
@@ -468,11 +545,32 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let a = laid.iter().find(|l| l.id == c.from).and_then(|l| l.outs.iter().find(|p| p.0 == c.from_port));
let b = laid.iter().find(|l| l.id == c.to).and_then(|l| l.ins.iter().find(|p| p.0 == c.to_port));
if let (Some(a), Some(b)) = (a, b) {
let hot = selection.contains(&c.from) || selection.contains(&c.to);
let col = if hot { tk.accent } else { Color32::from_gray(0xb4) };
bezier(&painter, cam.to_screen(a.3), cam.to_screen(b.3), Stroke::new((2.0 * cam.zoom).clamp(1.0, 3.0), col));
wires.push(((c.to, c.to_port.clone()), bezier_points(cam.to_screen(a.3), cam.to_screen(b.3))));
}
}
// Hover: not where a node card or a port sits on top of the wire.
let over_card = |p: Pos2| app.graph.rects.iter().any(|(_, r)| r.contains(p)) || nearest_port(&app.graph.ports, p, 9.0).is_some();
let wire_hover = match &app.graph.drag {
None => pointer.filter(|p| rect.contains(*p) && !over_card(*p)).and_then(|p| wire_at(&wires, p)).cloned(),
Some(Drag::WirePress { wire, .. }) => Some(wire.clone()),
Some(_) => None,
};
for (w, ctrl) in &wires {
let Some(c) = g.input_of(w.0, &w.1) else { continue };
let hot = selection.contains(&c.from) || selection.contains(&c.to);
let picked = app.graph.selected_wires.contains(w);
let hovered = wire_hover.as_ref() == Some(w);
let base = (2.0 * cam.zoom).clamp(1.0, 3.0);
let stroke = if picked {
Stroke::new(base + 2.0, tk.accent)
} else if hovered {
Stroke::new(base + 1.0, Color32::WHITE)
} else {
Stroke::new(base, if hot { tk.accent } else { Color32::from_gray(0xb4) })
};
painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke));
}
app.graph.wires = wires;
// Nodes.
let font = FontId::proportional((10.5 * cam.zoom).clamp(6.0, 16.0));
@@ -594,7 +692,24 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
painter.galley(bg.min + vec2(3.0, 3.0), g_, tk.text_strong);
}
handle_input(app, ui, &resp, rect, &cam, &node_resps, &frame_hits, &comment_hits, port_hover, &laid.iter().map(|l| (l.id, l.rect)).collect::<Vec<_>>());
// A wire under a comment is not hit.
let wire_hover = wire_hover.filter(|_| !pointer.is_some_and(|p| comment_hits.iter().any(|(_, r)| r.contains(p))));
if wire_hover.is_some() {
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
}
handle_input(
app,
ui,
&resp,
rect,
&cam,
&node_resps,
&frame_hits,
&comment_hits,
port_hover,
wire_hover,
&laid.iter().map(|l| (l.id, l.rect)).collect::<Vec<_>>(),
);
// Drag previews.
match &app.graph.drag {
@@ -614,14 +729,17 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
search_popup(app, ui, &cam);
comment_editor(app, ui);
if let Some(e) = cooked_error_count(app) {
painter.text(rect.right_bottom() - vec2(8.0, 8.0), Align2::RIGHT_BOTTOM, e, FontId::proportional(11.0), tk.danger);
let (failed, placeholders) = app.session.cook_failures();
let mut at = rect.right_bottom() - vec2(8.0, 8.0);
if !failed.is_empty() {
let text = format!("{} {} node(s) failed", icon::WARNING, failed.len());
at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.danger).top() - 2.0;
}
// Placeholders for missing SBS nodes are a soft warning, not a failure
if placeholders > 0 {
let text = format!("{} {placeholders} missing node(s), see the Console", icon::WARNING);
painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.warning);
}
}
fn cooked_error_count(app: &MaterialCraftApp) -> Option<String> {
let n = app.session.cooked.nodes.values().filter(|r| r.error.is_some()).count();
(n > 0).then(|| format!("{} {n} node(s) failed", icon::WARNING))
}
fn grid(p: &egui::Painter, cam: &Cam, rect: Rect) {
@@ -663,6 +781,7 @@ fn handle_input(
frames: &[(u64, Rect, Rect)],
comments: &[(u64, Rect)],
port_hover: Option<PortHit>,
wire_hover: Option<WireRef>,
graph_rects: &[(NodeId, Rect)],
) {
let ctx = ui.ctx().clone();
@@ -681,7 +800,15 @@ fn handle_input(
if middle_down || (primary_pressed && mods.alt) {
app.graph.drag = Some(Drag::Pan);
} else if primary_pressed {
if let Some(h) = &port_hover {
let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p));
let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card);
// Any press other than on a wire drops the wire selection.
if wire.is_none() {
app.graph.selected_wires.clear();
}
if let Some(w) = wire {
app.graph.drag = Some(Drag::WirePress { wire: w.clone(), start: p });
} else if let Some(h) = &port_hover {
if h.output {
app.graph.drag = Some(Drag::Wire { from: (h.node, h.port.clone()), detached: None });
} else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) {
@@ -727,6 +854,19 @@ fn handle_input(
app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y];
}
Some(Drag::Nodes { delta }) | Some(Drag::Frame { delta, .. }) | Some(Drag::Comment { delta, .. }) => *delta += motion,
Some(Drag::WirePress { wire, start }) => {
// Dragged far enough: a reroute dot where the press was, carried by the pointer.
if let Some(p) = pointer
&& p.distance(*start) > 4.0
{
let (wire, start) = (wire.clone(), *start);
let at = cam.to_graph(start);
app.graph.drag = None;
if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() {
app.graph.drag = Some(Drag::Nodes { delta: (p - start) / zoom });
}
}
}
_ => {}
}
@@ -735,6 +875,20 @@ fn handle_input(
if ended && let Some(drag) = app.graph.drag.take() {
match drag {
Drag::Pan => {}
Drag::WirePress { wire, .. } => {
app.session.selection.clear();
let sel = &mut app.graph.selected_wires;
if mods.ctrl && sel.contains(&wire) {
// Ctrl+click toggles a wire out of the selection.
sel.retain(|w| *w != wire);
} else if mods.ctrl || mods.shift {
if !sel.contains(&wire) {
sel.push(wire);
}
} else {
*sel = vec![wire];
}
}
Drag::Nodes { delta } => {
if delta.length() > 0.5 {
app.run("graph.node.move", json!({"by": [delta.x, delta.y]}));
@@ -822,6 +976,10 @@ fn handle_input(
app.run("view.2d", json!({"node": id.0, "port": 0}));
}
}
} else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) {
// A click that leaves the node selected shows it, replacing a node shown earlier (a
// Ctrl+click that deselects it does not; the shown node keeps its chosen port).
app.run("view.2d", json!({"node": id.0}));
}
r.context_menu(|ui| node_menu(app, ui, *id));
}
@@ -843,15 +1001,34 @@ fn handle_input(
&& !on_node
&& let Some(p) = pointer
{
open_search(app, cam.to_graph(p), None);
match &wire_hover {
// Double-click a wire: a reroute dot there.
Some(w) => {
let at = cam.to_graph(p);
app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]}));
app.graph.selected_wires.clear();
}
None => open_search(app, cam.to_graph(p), None),
}
}
if canvas.secondary_clicked()
&& let Some(p) = pointer
{
app.graph.menu_at = cam.to_graph(p);
app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node);
// Right-clicking a selected wire keeps the selection (to swap or delete them all).
if let Some(w) = &app.graph.menu_wire
&& !app.graph.selected_wires.contains(w)
{
app.session.selection.clear();
app.graph.selected_wires = vec![w.clone()];
}
}
let at = app.graph.menu_at;
canvas.context_menu(|ui| canvas_menu(app, ui, at));
canvas.context_menu(|ui| match app.graph.menu_wire.clone() {
Some(w) => wire_menu(app, ui, w, at),
None => canvas_menu(app, ui, at),
});
// Library drops.
if let Some(payload) = canvas.dnd_release_payload::<LibraryDrag>()
@@ -1022,6 +1199,55 @@ fn node_menu(app: &mut MaterialCraftApp, ui: &mut Ui, id: NodeId) {
item(ui, "Create graph from selection", "graph.createFromSelection", json!({}));
}
/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands.
fn wires_json(wires: &[WireRef]) -> serde_json::Value {
json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()})
}
/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none
/// is selected.
pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool {
let wires = std::mem::take(&mut app.graph.selected_wires);
if wires.is_empty() {
return false;
}
app.run("graph.wire.delete", wires_json(&wires));
true
}
/// Swap where the selected wires come from (the X key): two wires trade sources, more reverse
/// them in input order. The wires stay selected, so X again swaps back. `false` when no wire is
/// selected.
pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool {
if app.graph.selected_wires.is_empty() {
return false;
}
let params = wires_json(&app.graph.selected_wires);
app.run("graph.wire.swap", params);
true
}
fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) {
let n = app.graph.selected_wires.len();
if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() {
app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]}));
app.graph.selected_wires.clear();
ui.close();
}
if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() {
swap_selected_wires(app);
ui.close();
}
let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") };
if ui.button(format!("{} {label}", icon::TRASH)).clicked() {
if n < 2 {
app.graph.selected_wires = vec![(to, port)];
}
delete_selected_wires(app);
ui.close();
}
}
fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) {
ui.menu_button(tr("Add node"), |ui| {
for (cat, ids) in materialcraft_engine::nodes::categories() {
@@ -1087,33 +1313,196 @@ fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) {
mod tests {
use super::*;
/// The whole app in an offscreen egui context, driven one frame at a time.
struct Frames {
ctx: egui::Context,
app: MaterialCraftApp,
time: f64,
}
impl Frames {
/// `session` after a few frames, so the canvas is laid out.
fn new(session: materialcraft_engine::Session) -> Frames {
let mut f = Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0 };
for _ in 0..3 {
f.run(Vec::new(), egui::Modifiers::NONE);
}
f
}
/// One frame with `events` while `modifiers` are held, in a desktop-sized window (egui's
/// default screen is so large that the 3D view's frame would exceed the texture limit).
fn run(&mut self, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
self.time += 0.05;
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0)));
let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() };
let app = &mut self.app;
self.ctx
.run_ui(input, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
}
/// Press and release the primary button at `pos`, a second after any earlier click so
/// the two never pair into a double-click.
fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) {
self.time += 1.0;
self.run(vec![egui::Event::PointerMoved(pos)], modifiers);
for pressed in [true, false] {
self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers);
}
}
/// The center of node `id` on screen last frame.
fn center(&self, id: NodeId) -> Pos2 {
self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen"))
}
/// The node the 2D view shows once the graph has cooked.
fn shown(&mut self) -> Option<NodeId> {
self.app.session.cook();
self.app.session.view2d_image().map(|(id, _)| id)
}
}
/// A graph with a Perlin noise, a checker and an RGBA split side by side, framed on screen.
fn three_nodes() -> (Frames, [NodeId; 3]) {
let mut s = materialcraft_engine::sample_session();
materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap();
let ids = ["perlin_noise", "checker", "rgba_split"].iter().enumerate().map(|(i, def)| {
let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap();
NodeId(added["id"].as_u64().unwrap())
});
let ids: [NodeId; 3] = ids.collect::<Vec<_>>().try_into().unwrap();
s.selection.clear();
(Frames::new(s), ids)
}
#[test]
fn clicking_a_node_shows_it_in_the_2d_view() {
let (mut f, [noise, checker, _]) = three_nodes();
// Shown explicitly first (a double-click, an output port or "View in 2D view").
f.app.run("view.2d", json!({"node": noise.0}));
assert_eq!(f.shown(), Some(noise));
let at = f.center(checker);
f.click(at, egui::Modifiers::NONE);
assert_eq!(f.app.session.selection, vec![checker]);
assert_eq!(f.app.session.view2d.node, Some(checker));
assert_eq!(f.shown(), Some(checker));
// And back.
let at = f.center(noise);
f.click(at, egui::Modifiers::NONE);
assert_eq!(f.app.session.view2d.node, Some(noise));
assert_eq!(f.shown(), Some(noise));
// Ctrl+click adds a node to the selection and shows it too.
let at = f.center(checker);
f.click(at, egui::Modifiers::CTRL);
assert_eq!(f.app.session.selection, vec![noise, checker]);
assert_eq!(f.shown(), Some(checker));
}
#[test]
fn ctrl_click_that_deselects_a_node_does_not_show_it() {
let (mut f, [noise, checker, _]) = three_nodes();
f.app.session.selection = vec![noise, checker];
f.app.run("view.2d", json!({"node": checker.0}));
let at = f.center(noise);
f.click(at, egui::Modifiers::CTRL);
assert_eq!(f.app.session.selection, vec![checker]);
assert_eq!(f.shown(), Some(checker));
}
#[test]
fn dragging_a_node_keeps_the_2d_view() {
let (mut f, [noise, checker, _]) = three_nodes();
f.app.run("view.2d", json!({"node": noise.0}));
let before = f.app.session.graph().unwrap().node(checker).unwrap().pos;
let from = f.center(checker);
let none = egui::Modifiers::NONE;
f.run(vec![egui::Event::PointerMoved(from)], none);
f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none);
for step in 1..=8 {
f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none);
}
let to = from + vec2(40.0, 0.0);
f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none);
let after = f.app.session.graph().unwrap().node(checker).unwrap().pos;
let moved = 40.0 / f.app.ui.graph_camera.zoom;
assert!((after[0] - before[0] - moved).abs() < 1e-3 && after[1] == before[1], "the checker moved {before:?} -> {after:?}, not {moved} right");
assert_eq!(f.app.session.selection, vec![checker]);
assert_eq!(f.shown(), Some(noise));
}
#[test]
fn clicking_the_shown_node_keeps_its_port() {
let (mut f, [_, _, split]) = three_nodes();
f.app.run("view.2d", json!({"node": split.0, "port": 2}));
let at = f.center(split);
f.click(at, egui::Modifiers::NONE);
assert_eq!(f.app.session.selection, vec![split]);
assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2));
}
#[test]
fn tab_opens_search_in_the_full_workspace() {
let mut f = Frames::new(materialcraft_engine::sample_session());
let pointer = f.app.graph.view.center();
let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE);
assert!(f.app.graph.search.is_some());
}
#[test]
fn clicked_wires_swap_with_x_and_delete_together() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
app.run("file.new", json!({"template": "empty"}));
let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap();
let a = id(app.run("graph.node.add", json!({"def": "clouds_1", "at": [0, -150]})));
let b = id(app.run("graph.node.add", json!({"def": "checker", "at": [0, 150]})));
let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]})));
app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
let ctx = egui::Context::default();
for _ in 0..3 {
ctx.run_ui(egui::RawInput::default(), |ui| {
let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| {
events.insert(0, egui::Event::ModifiersChanged(modifiers));
let input = egui::RawInput { events, ..Default::default() };
ctx.run_ui(input, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
}
let pointer = app.graph.view.center();
let input = egui::RawInput {
events: vec![
egui::Event::PointerMoved(pointer),
egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },
],
..Default::default()
};
ctx.run_ui(input, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
assert!(app.graph.search.is_some());
for _ in 0..3 {
frame(&mut app, Vec::new(), egui::Modifiers::NONE);
}
let mid =
|app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap();
let click =
|app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec<egui::Event>, egui::Modifiers), port: &str, m: egui::Modifiers| {
let p = mid(app, port);
let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m };
frame(app, vec![egui::Event::PointerMoved(p)], m);
frame(app, vec![button(true)], m);
frame(app, vec![button(false)], m);
};
click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE);
click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT);
assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires);
let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0;
frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE);
assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a));
// Still selected: X again swaps back.
frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE);
assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b));
frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE);
assert!(app.session.graph().unwrap().connections.is_empty());
assert!(app.graph.selected_wires.is_empty());
}
#[test]
@@ -1158,6 +1547,23 @@ mod tests {
assert!(matches("zzzz").is_empty());
}
#[test]
fn wires_are_hit_near_their_curve_only() {
let a = (NodeId(1), "input".to_string());
let b = (NodeId(2), "input".to_string());
let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))];
// The midpoint of a symmetric wire lies on the line between its ends.
let mid = bezier_at(&wires[0].1, 0.5);
assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}");
assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a));
assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b));
assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None);
assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None);
// The ends are on the wire.
assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3);
assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3);
}
#[test]
fn port_positions_stay_on_the_card() {
let n = Node::new(NodeId(1), "blend", [0.0, 0.0]);
+161 -6
View File
@@ -1,12 +1,167 @@
//! Interface text. English only for now; every user-facing string goes through [`tr`] (or is
//! marked with [`n_`] where it is stored), so translations can be added without touching callers.
//! UI text lookup. Keys are the English strings, so English needs no table and a missing
//! translation falls back to English. Every user-visible literal goes through [`tr`] (or [`trf`]
//! for text with `{name}` placeholders); each language is a static `(English, translation)`
//! table, indexed into a hash map the first time the language is used. `Prefs::language` picks it.
/// Mark a string for translation where it is stored; translate with [`tr`] where it is shown.
use std::collections::HashMap;
use std::fmt::Display;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
mod ar;
pub struct Language {
/// BCP 47 code ("en", "ar").
pub code: &'static str,
/// The language's own name, for the picker.
pub name: &'static str,
/// Its English name (the picker's fallback when no font can draw `name`).
pub english: &'static str,
/// `(English, translation)` pairs, in any order.
pub table: &'static [(&'static str, &'static str)],
}
const COUNT: usize = 2;
pub static LANGUAGES: [Language; COUNT] =
[Language { code: "en", name: "English", english: "English", table: &[] }, Language { code: "ar", name: "العربية", english: "Arabic", table: ar::TABLE }];
static MAPS: [OnceLock<HashMap<&'static str, &'static str>>; COUNT] = [const { OnceLock::new() }; COUNT];
static CURRENT: AtomicUsize = AtomicUsize::new(0);
/// Switch the UI language (unknown codes fall back to English).
pub fn set_language(code: &str) {
CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed);
}
/// The current UI language.
pub fn current() -> &'static Language {
LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0])
}
/// Returns true if `code` is a right-to-left language (e.g. Arabic `"ar"`).
pub fn is_rtl_code(code: &str) -> bool {
craft_ui::direction::resolve(code, craft_ui::direction::Setting::Language) == craft_ui::direction::Direction::Rtl
}
/// Returns true if the current UI language is right-to-left.
pub fn is_rtl() -> bool {
is_rtl_code(current().code)
}
/// `text` in the current language (unchanged when it has no translation).
pub fn tr(text: &str) -> &str {
let i = CURRENT.load(Ordering::Relaxed);
let (Some(lang), Some(map)) = (LANGUAGES.get(i), MAPS.get(i)) else { return text };
if lang.table.is_empty() {
return text;
}
map.get_or_init(|| lang.table.iter().copied().collect()).get(text).copied().unwrap_or(text)
}
/// Marks a static string for translation where it is defined (gettext's `N_`); it is translated
/// with [`tr`] where it is shown. The key test collects both.
pub const fn n_(text: &'static str) -> &'static str {
text
}
/// The text in the interface language.
pub fn tr(text: &str) -> &str {
text
/// `template` translated, with each `{name}` replaced by its value in `args`.
pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String {
let mut out = String::with_capacity(template.len() + 16);
let mut rest = tr(template);
while let Some(open) = rest.find('{') {
out.push_str(&rest[..open]);
let after = &rest[open + 1..];
match after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (close, v))) {
Some((close, v)) => {
use std::fmt::Write as _;
let _ = write!(out, "{v}");
rest = &after[close + 1..];
}
None => {
out.push('{');
rest = after;
}
}
}
out.push_str(rest);
out
}
/// The supported language for a locale such as "ar-EG", "ar-SA" ("en" when none matches).
pub fn language_for_locale(locale: &str) -> &'static str {
let lang = locale.split(['-', '_', '.', '@']).next().unwrap_or("").to_ascii_lowercase();
match lang.as_str() {
"ar" => "ar",
l => LANGUAGES.iter().find(|x| x.code == l).map_or("en", |x| x.code),
}
}
/// The operating system's (or browser's) UI language, for the first run.
pub fn os_language() -> &'static str {
#[cfg(not(target_arch = "wasm32"))]
let locale = sys_locale::get_locale();
#[cfg(target_arch = "wasm32")]
let locale = web_sys::window().and_then(|w| w.navigator().language());
locale.map_or("en", |l| language_for_locale(&l))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn language_switching_and_arabic_translations_work() {
set_language("en");
assert_eq!(current().code, "en");
assert_eq!(tr("Properties"), "Properties");
assert!(!is_rtl());
set_language("ar");
assert_eq!(current().code, "ar");
assert_eq!(tr("Properties"), "الخصائص");
assert_eq!(tr("Preferences"), "التفضيلات");
assert_eq!(tr("New graph"), "مخطط جديد");
assert_eq!(tr("Export outputs"), "تصدير المخرجات");
assert_eq!(tr("Welcome to MaterialCraft"), "مرحباً بك في MaterialCraft");
assert!(is_rtl());
// Live formatting
let formatted = trf("Hello {name}", &[("name", &"World")]);
assert_eq!(formatted, "Hello World");
// Fallback for unknown text
assert_eq!(tr("Unknown untranslated string 1234"), "Unknown untranslated string 1234");
// Reset to English
set_language("en");
}
#[test]
fn locale_detection() {
assert_eq!(language_for_locale("ar"), "ar");
assert_eq!(language_for_locale("ar-EG"), "ar");
assert_eq!(language_for_locale("ar_SA.UTF-8"), "ar");
assert_eq!(language_for_locale("en-US"), "en");
assert_eq!(language_for_locale("fr-FR"), "en");
}
#[test]
fn arabic_table_has_no_duplicate_keys() {
let mut seen = std::collections::HashSet::new();
for (k, _) in ar::TABLE {
assert!(seen.insert(*k), "duplicate key in ar::TABLE: {k:?}");
}
}
#[test]
fn placeholders_match_between_key_and_arabic_translation() {
for (k, v) in ar::TABLE {
let mut kp: Vec<&str> = k.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect();
let mut vp: Vec<&str> = v.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect();
kp.sort();
vp.sort();
assert_eq!(kp, vp, "mismatched placeholders in {k:?} vs {v:?}");
}
}
}
+373
View File
@@ -0,0 +1,373 @@
//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`.
pub const TABLE: &[(&str, &str)] = &[
("$pos", "$pos"),
("$size", "$size"),
("(checker)", "(رقعة شطرنج)"),
("1024 px", "1024 بكسل"),
("16 bits", "16 بت"),
("16 bits per channel", "16 بت لكل قناة"),
("16 bits per channel float (HDR)", "16 بت لكل قناة فاصلة عائمة (HDR)"),
("2048 px", "2048 بكسل"),
("256 px", "256 بكسل"),
("2D View", "عرض ثنائي الأبعاد"),
("32 bits float", "32 بت فاصلة عائمة"),
("32 bits per channel float (HDR)", "32 بت لكل قناة فاصلة عائمة (HDR)"),
("3D pan limit (mesh radii)", "حد التحريك ثلاثي الأبعاد (أنصاف أقطار المجسم)"),
("3D pan speed", "سرعة التحريك ثلاثي الأبعاد"),
("3D View", "عرض ثلاثي الأبعاد"),
("512 px", "512 بكسل"),
("8 bits", "8 بت"),
("8 bits per channel", "8 بت لكل قناة"),
("About MaterialCraft", "حول MaterialCraft"),
("About MaterialCraft...", "حول MaterialCraft..."),
("Absolute", "مطلق"),
("Accent color", "لون التمييز"),
("Actual pixels", "البكسلات الفعلية"),
("Add", "إضافة"),
("Add Comment", "إضافة تعليق"),
("Add comment", "إضافة تعليق"),
("Add Dot node", "إضافة عقدة نقطية"),
("Add Frame", "إضافة إطار"),
("Add frame around selection", "إضافة إطار حول التحديد"),
("Add frame around the selection", "إضافة إطار حول التحديد"),
("Add Navigation pin", "إضافة دبوس تنقل"),
("Add navigation pin", "إضافة دبوس تنقل"),
("Add node", "إضافة عقدة"),
("Add Output nodes with usages (base color, normal, ...) to see the material", "أضف عُقد مخرجات مع استخداماتها (اللون الأساسي، الناظم، ...) لمعاينة المادة"),
("Align centers horizontally", "محاذاة المراكز أفقياً"),
("Align centers vertically", "محاذاة المراكز رأسياً"),
("Align left", "محاذاة لليسار"),
("Align top", "محاذاة للأعلى"),
("All nodes", "كل العقد"),
("Amber", "كهرماني"),
("An open-source Crafting App by the ArtCraft team and community.", "تطبيق تصميم مفتوح المصدر من قِبل فريق ومجتمع ArtCraft."),
("And", "و (And)"),
("Apply", "تطبيق"),
("Arc tangent 2", "ظل زاوية قوسي 2"),
("ArtCraft website...", "موقع ArtCraft الإلكتروني..."),
("As JSON", "بصيغة JSON"),
("Atomic nodes", "عقد أولية"),
("Attributes", "السمات"),
("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"),
("Bad function", "دالة غير صالحة"),
("Base parameters", "المعلمات الأساسية"),
("Bind to input", "ربط بالمدخل"),
("Bit depth", "عمق البت"),
("Blends", "عمليات الدمج"),
("Blue", "أزرق"),
("Boolean", "منطقي"),
("Brick wall", "جدار طوب"),
("Brightness", "السطوع"),
(
"Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.",
"أنشئ مواد قابلة للتكرار من التشويش والأنماط والمرشحات، وعاينها مباشرة ثنائية وثلاثية الأبعاد، وصدّر الخرائط لأي محرك.",
),
("Cache", "الذاكرة المؤقتة"),
("Camera", "الكاميرا"),
("Cancel", "إلغاء"),
("Cast", "تحويل النوع"),
("Ceil", "الحد الأعلى (Ceil)"),
("Choose a folder to export to", "اختر مجلداً للتصدير إليه"),
("Clamp", "تقييد النطاق (Clamp)"),
("Clear cache", "مسح الذاكرة المؤقتة"),
("Clear recent packages", "مسح الحزم الأخيرة"),
("Close all", "إغلاق الكل"),
("Community (Discord)", "المجتمع (Discord)"),
("Comparison", "مقارنة"),
("Compute graph", "حساب المخطط"),
("Computing...", "جاري الحساب..."),
("Console", "وحدة التحكم"),
("Constant", "ثابت"),
("Control", "تحكم"),
("Copper", "نحاسي"),
("Copy", "نسخ"),
("Copy selection", "نسخ التحديد"),
("Coral", "مرجاني"),
("Cosine", "جيب التمام (Cosine)"),
("Couldn't export", "تعذر التصدير"),
("Couldn't import", "تعذر الاستيراد"),
("Couldn't load", "تعذر التحميل"),
("Couldn't open", "تعذر الفتح"),
("Couldn't save", "تعذر الحفظ"),
("Create", "إنشاء"),
("Create graph from selection", "إنشاء مخطط من التحديد"),
("Create graph in", "إنشاء مخطط في"),
("Cube", "مكعب"),
("Cut", "قص"),
("Cyan", "سماوي"),
("Cylinder", "أسطوانة"),
("Dark", "داكن"),
("Default", "افتراضي"),
("Delete", "حذف"),
("Delete and relink", "حذف وإعادة ربط"),
("Delete input", "حذف المدخل"),
("Delete preset", "حذف الإعداد المسبق"),
("Delete selection", "حذف التحديد"),
("Disable selection", "تعطيل التحديد"),
("Display", "عرض"),
("Distribute horizontally", "توزيع أفقي"),
("Distribute vertically", "توزيع رأسي"),
("Division", "قسمة"),
("Documentation", "التوثيق"),
("Documentation...", "التوثيق..."),
("Dot Product", "الجداء السلمي (Dot Product)"),
("Double-click a node to show it here", "انقر نقراً مزدوجاً على عقدة لعرضها هنا"),
("Downloaded", "تم التنزيل"),
("Duplicate", "تكرار"),
("Duplicate selection", "تكرار التحديد"),
("Duplicate selection without link", "تكرار التحديد بدون ربط"),
("Edit", "تحرير"),
("Edit function graph...", "تحرير مخطط الدوال..."),
("Empty", "فارغ"),
("Empty package", "حزمة فارغة"),
("Engine", "المحرك"),
("Environment", "البيئة"),
("Environment background", "خلفية البيئة"),
("Equal", "مساوٍ"),
("Exit", "خروج"),
("Explorer", "المستكشف"),
("Exponential", "دالة أسية (Exp)"),
("Export", "تصدير"),
("Export material...", "تصدير المادة..."),
("Export outputs", "تصدير المخرجات"),
("Export outputs...", "تصدير المخرجات..."),
("Export outputs... (Ctrl+Shift+E)", "تصدير المخرجات... (Ctrl+Shift+E)"),
("Exported", "تم التصدير"),
("Expose as graph input", "كشف كمدخل للمخطط"),
("Exposure", "التعريض"),
("File", "ملف"),
("File names", "أسماء الملفات"),
("files", "ملفات"),
("Filters", "مرشحات"),
("Fit", "ملاءمة"),
("Float", "فاصلة عائمة (Float)"),
("Float2", "فاصلة عائمة ثنائية (Float2)"),
("Float3", "فاصلة عائمة ثلاثية (Float3)"),
("Float4", "فاصلة عائمة رباعية (Float4)"),
("Flood fill", "تعبئة متصلة (Flood fill)"),
("Floor", "الحد الأدنى (Floor)"),
("Folder", "المجلد"),
("Format", "الصيغة"),
("Fractional part", "الجزء الكسري"),
("Frame all", "تأطير الكل"),
("Frame all (F)", "تأطير الكل (F)"),
("Frame all / the selection", "تأطير الكل / التحديد"),
("Front", "أمامي"),
("Full size", "الحجم الكامل"),
("full size", "الحجم الكامل"),
("Function", "دالة"),
("function", "دالة"),
("Function graph", "مخطط الدوال"),
("function nodes", "عقد الدوال"),
("Function of", "دالة لـ"),
("Get variable", "جلب متغير"),
("Go to pin", "الانتقال إلى الدبوس"),
("Graph", "مخطط"),
("Graph instance", "نسخة المخطط"),
("Graph items", "عناصر المخطط"),
("Graph name", "اسم المخطط"),
("Graph's format", "صيغة المخطط"),
("Graph...", "مخطط..."),
("Graphs in this package", "المخططات في هذه الحزمة"),
("Greater", "أكبر من"),
("Greater or equal", "أكبر من أو يساوي"),
("Green", "أخضر"),
("Height (parallax) depth", "عمق الارتفاع (اختلاف المنظر)"),
("Help", "مساعدة"),
("Histogram", "المخطط البياني (Histogram)"),
("History", "السجل"),
("Home", "الرئيسية"),
("Home screen...", "الشاشة الرئيسية..."),
("Icons", "أيقونات"),
("If...Else", "إذا...وإلا (If...Else)"),
("Import bitmap...", "استيراد صورة نقطية..."),
("Imported", "تم الاستيراد"),
("Input parameters", "معلمات المدخلات"),
("Input previews", "معاينات المدخلات"),
("Instance parameters", "معلمات النسخة"),
("Integer", "عدد صحيح"),
("Interface scale", "حجم واجهة المستخدم"),
("Join the community (Discord)...", "انضم إلى المجتمع (Discord)..."),
("Key at", "مفتاح عند"),
("Language", "اللغة"),
("Last compute", "آخر حساب"),
("Lava rock", "صخور بركانية"),
("Length", "الطول"),
("Library", "المكتبة"),
("Light", "فاتح"),
("Linear interpolation", "استيفاء خطي (Lerp)"),
("List", "قائمة"),
("Load mesh...", "تحميل مجسم..."),
("Logarithm", "لوغاريتم"),
("Logical", "منطقي"),
("Lower", "أصغر من"),
("Lower or equal", "أصغر من أو يساوي"),
("Mat ball", "كرة المادة"),
("Material filters", "مرشحات المواد"),
("Maximum", "الحد الأقصى"),
("Medium dark", "داكن متوسط"),
("Medium light", "فاتح متوسط"),
("Minimum", "الحد الأدنى"),
("Modulo", "باقي القسمة (Modulo)"),
("Mossy ground", "أرضية مغطاة بالطحالب"),
("Multiplication", "ضرب"),
("Name", "الاسم"),
("Negation", "نفي / سالب"),
("New", "جديد"),
("New graph", "مخطط جديد"),
("New graph...", "مخطط جديد..."),
("New graph... (Ctrl+N)", "مخطط جديد... (Ctrl+N)"),
("New random seed", "بذرة عشوائية جديدة"),
("Night", "ليل"),
("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"),
("No graph is open", "لا يوجد مخطط مفتوح"),
("No matching node", "لا توجد عقدة مطابقة"),
("No presets yet", "لا توجد إعدادات مسبقة بعد"),
("No recent packages", "لا توجد حزم حديثة"),
("Node search (over the graph)", "البحث عن عقدة (فوق المخطط)"),
("Node-based procedural materials, built in pure Rust.", "مواد إجرائية قائمة على العقد، مبنية بلغة Rust النقية."),
("Noises", "تشويشات"),
("None", "بلا"),
("Normal", "الناظم (Normal)"),
("Normalize", "تسوية (Normalize)"),
("Not", "ليس (Not)"),
("Not equal", "غير مساوٍ"),
("Nothing matches", "لا توجد تطابقات"),
("Open", "فتح"),
("Open graph", "فتح المخطط"),
("Open package...", "فتح حزمة..."),
("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"),
("Open...", "فتح..."),
("Opened", "تم الفتح"),
("Operator", "معامل حسابي"),
("Ops", "عمليات"),
("Or", "أو (Or)"),
("Output format", "صيغة المخرج"),
("Output size", "حجم المخرج"),
("Outputs", "المخرجات"),
("Overcast", "غائم"),
("Painted metal plates", "صفائح معدنية مطلية"),
("Pan the camera", "تحريك الكاميرا"),
("Pan the graph", "تحريك المخطط"),
("Parent size:", "حجم العنصر الأصل:"),
("Paste", "لصق"),
("Patterns", "أنماط"),
("PBR material (outputs only)", "مادة PBR (مخرجات فقط)"),
("Perlin noise", "تشويش بيرلين (Perlin noise)"),
("Pick an image file (a mesh map baked in TextureCraft)", "اختر ملف صورة (خريطة مجسم مخبوزة في TextureCraft)"),
("Pink", "وردي"),
("Plane", "مستوى"),
("Polished marble", "رخام مصقول"),
("Power", "قوة / أس (Power)"),
("Preferences", "التفضيلات"),
("Preferences...", "التفضيلات..."),
("Preset name", "اسم الإعداد المسبق"),
("Presets", "الإعدادات المسبقة"),
("Preview", "معاينة"),
("Preview size", "حجم المعاينة"),
("Preview size while editing", "حجم المعاينة أثناء التحرير"),
("Properties", "الخصائص"),
("Random", "عشوائي"),
("Random seed", "بذرة عشوائية"),
("Recent", "الأخيرة"),
("Recent packages", "الحزم الأخيرة"),
("Redo", "إعادة"),
("Redo (Ctrl+Y)", "إعادة (Ctrl+Y)"),
("Relative to input", "نسبي إلى المدخل"),
("Relative to parent", "نسبي إلى الأصل"),
("Reload resources", "إعادة تحميل الموارد"),
("Remove function", "إزالة الدالة"),
("Render time", "وقت التصيير"),
("Renderer", "المصير"),
("Report a bug...", "الإبلاغ عن خطأ..."),
("Reset layout", "إعادة ضبط التخطيط"),
("Reset parameters", "إعادة ضبط المعلمات"),
("Reset scene", "إعادة ضبط المشهد"),
("Reset to default", "إعادة ضبط للافتراضي"),
("Resources", "الموارد"),
("Revert", "استرجاع"),
("Right-click a node parameter > Expose as graph input", "انقر بزر الفأرة الأيمن على معلمة العقدة > كشف كمدخل للمخطط"),
(
"Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.",
"انقر بزر الفأرة الأيمن أو مفتاح المسافة لإضافة عمليات؛ اسحب من نقطة المخرج إلى المدخل؛ العقدة المميزة بنجمة هي النتيجة.",
),
("Rotation", "التدوير"),
("Rounded cube", "مكعب مدور الحواف"),
("Rusty metal", "معدن صدئ"),
("Sample Color", "عينة لونية"),
("Sample Gray", "عينة تدرج رمادي"),
("Samplers", "عينات"),
("Samples", "عينات"),
("Save", "حفظ"),
("Save (Ctrl+S)", "حفظ (Ctrl+S)"),
("Save as...", "حفظ باسم..."),
("Save image...", "حفظ الصورة..."),
("Save package", "حفظ الحزمة"),
("Save preset", "حفظ الإعداد المسبق"),
("Saved", "تم الحفظ"),
("Scene", "المشهد"),
("Search", "بحث"),
("Search nodes...", "البحث في العقد..."),
("Select all", "تحديد الكل"),
("Select downstream nodes", "تحديد العقد اللاحقة"),
("Select upstream nodes", "تحديد العقد السابقة"),
("Send to TextureCraft", "إرسال إلى TextureCraft"),
("Sent to TextureCraft: find it on the shelf under My smart materials", "أُرسل إلى TextureCraft: ستجده على الرف ضمن موادي الذكية"),
("Set function...", "تعيين دالة..."),
("Shortcuts", "الاختصارات"),
("Shortcuts list...", "قائمة الاختصارات..."),
("Show at startup", "إظهار عند بدء التشغيل"),
("Show in the 2D view", "إظهار في العرض ثنائي الأبعاد"),
("Show node thumbnails", "إظهار الصور المصغرة للعقد"),
("Showing", "عرض"),
("Side", "جانبي"),
("Sine", "جيب الزاوية (Sine)"),
("Size", "الحجم"),
("Specific parameters", "المعلمات المخصصة"),
("Sphere", "كرة"),
("Square root", "جذر تربيعي"),
("Stone tiles", "بلاط حجري"),
("Studio", "استوديو"),
("Subtraction", "طرح"),
("Sunset", "غروب"),
("SVG", "رسوم متجهة (SVG)"),
("Swizzle", "إعادة ترتيب القنوات (Swizzle)"),
("Tangent", "ظل الزاوية (Tangent)"),
("Templates", "القوالب"),
("Text", "نص"),
("Texture generators", "مولدات الخامات"),
("The instanced graph is missing", "المخطط المنسوخ مفقود"),
("This graph exposes no inputs", "هذا المخطط لا يكشف أي مدخلات"),
("This package", "هذه الحزمة"),
("threads", "خيوط معالجة"),
("Tile 3x3", "تكرار 3x3"),
("Tiling", "التكرار"),
("Tiling (H and V)", "التكرار (أفقياً ورأسياً)"),
("To Float", "إلى فاصلة عائمة"),
("To Integer", "إلى عدد صحيح"),
("Tools", "أدوات"),
("Top", "علوي"),
("Torus", "شكل حلقي (Torus)"),
("Transforms", "التحويلات"),
("Turn the environment", "تدوير البيئة"),
("Unbind", "فك الارتباط"),
("Undo", "تراجع"),
("Undo (Ctrl+Z)", "تراجع (Ctrl+Z)"),
("Use as result", "استخدام كنتيجة"),
("Variables", "متغيرات"),
("Vector", "متجه"),
("Vector Float2", "متجه ثنائي (Float2)"),
("Vector Float3", "متجه ثلاثي (Float3)"),
("Vector Float4", "متجه رباعي (Float4)"),
("Version", "الإصدار"),
("View in 2D view", "عرض في العرض ثنائي الأبعاد"),
("Violet", "بنفسجي"),
("Weathering", "التجوية والتقادم"),
("Welcome to MaterialCraft", "مرحباً بك في MaterialCraft"),
("Wicker weave", "نسيج قش"),
("Windows", "نوافذ"),
("Wood planks", "ألواح خشبية"),
("Woven fabric", "قماش منسوج"),
("Zoom the graph and the views", "تقريب المخطط وطرق العرض"),
];
+243
View File
@@ -0,0 +1,243 @@
//! The Levels node's editor in the properties panel: a histogram of the node's input with the
//! levels transfer curve over it, the input range handles (low, mid, high) under it and the
//! output range handles (low, high) under a black-to-white bar.
//!
//! The mid handle sits where `Level in mid` really acts: relative to the input range, so it moves
//! with the low and high handles. The input low and high handles cannot cross (the low one stays
//! left of the high one); the output handles may, which inverts the result. Every drag is a
//! `graph.node.param` command, merged into one undo step per handle.
use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, Ui, pos2, vec2};
use materialcraft_engine::core::{Node, NodeId, Value};
use materialcraft_engine::image::{Image, Kind};
use materialcraft_engine::nodes::atomic::levels_fn;
use serde_json::json;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
/// Histogram bins (one per 8-bit level).
pub const BINS: usize = 256;
/// Smallest gap kept between the input low and high handles.
const MIN_SPAN: f32 = 0.004;
/// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B.
pub fn histogram(img: &Image) -> Vec<[u32; BINS]> {
let channels = if img.kind == Kind::Gray { 1 } else { 3 };
let stride = img.kind.channels();
let mut h = vec![[0u32; BINS]; channels];
for px in img.data.chunks(stride) {
for (c, bins) in h.iter_mut().enumerate() {
let v = px.get(c).copied().unwrap_or(0.0);
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
if let Some(b) = bins.get_mut(((v * (BINS - 1) as f32).round() as usize).min(BINS - 1)) {
*b = b.saturating_add(1);
}
}
}
h
}
/// The bar height scale: the tallest bin away from pure black and white (masks pile up there and
/// would flatten everything else), at least one.
fn scale(h: &[[u32; BINS]]) -> f32 {
let inner = h.iter().flat_map(|b| b.get(1..BINS - 1).unwrap_or(&[]).iter().copied()).max().unwrap_or(0);
let all = h.iter().flat_map(|b| b.iter().copied()).max().unwrap_or(0);
(if inner > 0 { inner } else { all }).max(1) as f32
}
/// The five levels values of `n`: in low, in mid (relative), in high, out low, out high.
pub fn values(n: &Node) -> [f32; 5] {
let get = |id: &str, d: f32| match n.params.get(id) {
Some(Value::Float(v)) if v.is_finite() => *v,
_ => d,
};
[get("in_low", 0.0), get("in_mid", 0.5), get("in_high", 1.0), get("out_low", 0.0), get("out_high", 1.0)]
}
/// Where the mid handle sits on the 0..1 axis.
pub fn mid_position(v: &[f32; 5]) -> f32 {
v[0] + v[1].clamp(0.0, 1.0) * (v[2] - v[0])
}
/// The new value of handle `k` (0 in low, 1 in mid, 2 in high, 3 out low, 4 out high) dragged to
/// `x` on the 0..1 axis: input low and high cannot cross, mid is stored relative to the range.
pub fn drag_value(v: &[f32; 5], k: usize, x: f32) -> f32 {
let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
let (lo, hi) = (v[0].min(v[2]), v[0].max(v[2]));
match k {
0 => x.min(hi - MIN_SPAN).max(0.0),
2 => x.max(lo + MIN_SPAN).min(1.0),
1 => {
let span = v[2] - v[0];
if span.abs() < 1e-6 { 0.5 } else { ((x - v[0]) / span).clamp(0.01, 0.99) }
}
_ => x,
}
}
/// The histogram of what feeds the node's input, computed once per cooked result.
fn input_histogram(app: &MaterialCraftApp, ui: &Ui, node: NodeId) -> Option<std::sync::Arc<Vec<[u32; BINS]>>> {
let g = app.session.graph().ok()?;
let c = g.input_of(node, "input")?;
let port = app.session.output_ports(c.from).iter().position(|p| *p == c.from_port)?;
let r = app.session.cooked.nodes.get(&c.from)?;
let img = r.outputs.get(port)?;
let id = egui::Id::unique(("levels-histogram", r.key, port));
if let Some(h) = ui.ctx().data(|d| d.get_temp::<std::sync::Arc<Vec<[u32; BINS]>>>(id)) {
return Some(h);
}
let h = std::sync::Arc::new(histogram(img));
ui.ctx().data_mut(|d| d.insert_temp(id, h.clone()));
Some(h)
}
/// A handle: a small triangle pointing up at `x`, filled with `fill`.
fn handle(p: &egui::Painter, x: f32, top: f32, fill: Color32, active: bool, tk: &Tokens) {
let s = 6.0;
let pts = vec![pos2(x, top), pos2(x - s, top + s * 1.6), pos2(x + s, top + s * 1.6)];
p.add(Shape::convex_polygon(pts, fill, Stroke::new(if active { 1.5 } else { 1.0 }, if active { tk.accent } else { Color32::from_gray(0x10) })));
}
/// The editor for Levels node `n`.
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) {
let tk = Tokens::get(ui.ctx());
let v = values(n);
// Handles of parameters driven by an input or a function are left alone.
let locked = |id: &str| n.bindings.contains_key(id) || n.functions.contains_key(id);
let ids = ["in_low", "in_mid", "in_high", "out_low", "out_high"];
let w = ui.available_width().max(120.0);
let pad = 7.0;
let (rect, _) = ui.allocate_exact_size(vec2(w, 96.0 + 16.0 + 12.0 + 16.0), Sense::hover());
let axis = |x: f32| rect.left() + pad + x * (rect.width() - 2.0 * pad);
let unaxis = |sx: f32| (sx - rect.left() - pad) / (rect.width() - 2.0 * pad).max(1.0);
let plot = Rect::from_min_max(pos2(axis(0.0), rect.top()), pos2(axis(1.0), rect.top() + 96.0));
let p = ui.painter_at(rect.expand(2.0));
p.rect_filled(plot, 2.0, Color32::from_gray(0x16));
// The input histogram.
match input_histogram(app, ui, n.id) {
Some(h) => {
let k = scale(&h);
let colors: &[Color32] = if h.len() == 1 {
&[Color32::from_gray(0xb8)]
} else {
&[
Color32::from_rgba_unmultiplied(0xe0, 0x50, 0x50, 110),
Color32::from_rgba_unmultiplied(0x50, 0xd0, 0x60, 110),
Color32::from_rgba_unmultiplied(0x50, 0x80, 0xf0, 110),
]
};
let bw = plot.width() / BINS as f32;
for (bins, col) in h.iter().zip(colors) {
for (i, &c) in bins.iter().enumerate() {
if c == 0 {
continue;
}
let hgt = (c as f32 / k).min(1.0) * (plot.height() - 2.0);
let x0 = plot.left() + i as f32 * bw;
p.rect_filled(Rect::from_min_max(pos2(x0, plot.bottom() - hgt), pos2(x0 + bw.max(1.0), plot.bottom())), 0.0, *col);
}
}
}
None => {
p.text(plot.center(), egui::Align2::CENTER_CENTER, tr("Connect an input to see its histogram"), egui::FontId::proportional(10.5), tk.text_dim);
}
}
// Shade what the input range clips, and draw the transfer curve.
let (lo, hi) = (v[0].min(v[2]), v[0].max(v[2]));
let shade = Color32::from_black_alpha(120);
p.rect_filled(Rect::from_min_max(plot.min, pos2(axis(lo), plot.bottom())), 0.0, shade);
p.rect_filled(Rect::from_min_max(pos2(axis(hi), plot.top()), plot.max), 0.0, shade);
let curve: Vec<Pos2> = (0..=96)
.map(|i| {
let x = i as f32 / 96.0;
let y = levels_fn(x, v[0], v[1], v[2], v[3], v[4]);
let y = if y.is_finite() { y.clamp(0.0, 1.0) } else { 0.0 };
pos2(axis(x), plot.bottom() - y * plot.height())
})
.collect();
p.add(Shape::line(curve, Stroke::new(1.5, tk.accent)));
p.rect_stroke(plot, 2.0, Stroke::new(1.0, Color32::from_gray(0x40)), StrokeKind::Inside);
// Input handles under the histogram, output handles under the gradient bar.
let in_row = plot.bottom() + 2.0;
let bar = Rect::from_min_max(pos2(plot.left(), in_row + 16.0), pos2(plot.right(), in_row + 26.0));
let mesh = {
let mut m = egui::Mesh::default();
m.colored_vertex(bar.left_top(), Color32::BLACK);
m.colored_vertex(bar.right_top(), Color32::WHITE);
m.colored_vertex(bar.right_bottom(), Color32::WHITE);
m.colored_vertex(bar.left_bottom(), Color32::BLACK);
m.add_triangle(0, 1, 2);
m.add_triangle(0, 2, 3);
m
};
p.add(Shape::mesh(mesh));
let out_row = bar.bottom() + 2.0;
let xs = [v[0], mid_position(&v), v[2], v[3], v[4]];
let rows = [in_row, in_row, in_row, out_row, out_row];
let fills = [Color32::from_gray(0x08), Color32::from_gray(0x80), Color32::WHITE, Color32::from_gray(0x08), Color32::WHITE];
let names = ["Level in low", "Level in mid", "Level in high", "Level out low", "Level out high"];
// Mid last, so it wins where it overlaps low or high.
for k in [0usize, 2, 3, 4, 1] {
let x = axis(xs[k].clamp(0.0, 1.0));
let hit = Rect::from_min_size(pos2(x - 7.0, rows[k] - 1.0), vec2(14.0, 13.0));
let resp = ui.interact(hit, ui.scope_id().with(("levels-handle", n.id.0, k)), if locked(ids[k]) { Sense::hover() } else { Sense::drag() });
crate::widgets::name(&resp, egui::Role::Slider, names[k]);
let active = resp.dragged() || resp.hovered();
handle(&p, x, rows[k], fills[k], active, &tk);
if resp.dragged()
&& let Some(ptr) = resp.interact_pointer_pos()
{
let nv = drag_value(&v, k, unaxis(ptr.x));
if (nv - v[k]).abs() > 1e-5 {
app.run("graph.node.param", json!({"id": n.id.0, "param": ids[k], "value": nv}));
}
}
resp.on_hover_text(format!("{}: {:.3}", tr(names[k]), v[k]));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn histogram_counts_every_value_once_per_channel() {
let gray = Image::gray(4, 4, |x, _| x as f32 / 3.0);
let h = histogram(&gray);
assert_eq!(h.len(), 1);
assert_eq!(h[0].iter().sum::<u32>(), 16);
assert_eq!((h[0][0], h[0][85], h[0][170], h[0][255]), (4, 4, 4, 4));
let color = Image::filled(2, 2, Kind::Color, [2.0, f32::NAN, -1.0, 0.5]);
let h = histogram(&color);
assert_eq!(h.len(), 3);
// Out of range and NaN values land in the end bins.
assert_eq!((h[0][255], h[1][0], h[2][0]), (4, 4, 4));
// The scale ignores the end bins when there is anything in between.
assert_eq!(scale(&[[0; BINS]]), 1.0);
}
#[test]
fn input_handles_do_not_cross_and_mid_follows_the_range() {
let v = [0.2, 0.5, 0.6, 0.0, 1.0];
assert!((mid_position(&v) - 0.4).abs() < 1e-6);
// Low cannot pass high, high cannot pass low.
assert!(drag_value(&v, 0, 0.9) < 0.6);
assert!(drag_value(&v, 2, 0.1) > 0.2);
assert_eq!(drag_value(&v, 0, -1.0), 0.0);
assert_eq!(drag_value(&v, 2, 2.0), 1.0);
// Mid is stored relative to the range, kept inside it.
assert!((drag_value(&v, 1, 0.3) - 0.25).abs() < 1e-5);
assert_eq!(drag_value(&v, 1, 0.0), 0.01);
assert_eq!(drag_value(&v, 1, 1.0), 0.99);
// Output handles may cross (that inverts); NaN never escapes.
assert_eq!(drag_value(&v, 3, 0.8), 0.8);
assert_eq!(drag_value(&v, 4, f32::NAN), 0.0);
// A collapsed range keeps mid centered.
assert_eq!(drag_value(&[0.5, 0.3, 0.5, 0.0, 1.0], 1, 0.7), 0.5);
}
}
+11 -2
View File
@@ -11,9 +11,11 @@ pub mod control;
pub mod cook;
pub mod docking;
pub mod explorer;
pub mod fonts;
pub mod function_editor;
pub mod graph_view;
pub mod i18n;
pub mod levels_editor;
pub mod library;
pub mod menus;
pub mod properties;
@@ -69,6 +71,8 @@ pub struct MaterialCraftApp {
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
next_autosave: f64,
styled: Option<(theme::Brightness, theme::Accent)>,
/// Fallback fonts for Arabic.
pub fonts: fonts::UiFonts,
/// The icon font is installed (it takes effect on the frame after `set_fonts`).
fonts_ready: bool,
}
@@ -78,6 +82,7 @@ impl MaterialCraftApp {
let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_default();
theme::install(&cc.egui_ctx);
let mut app = MaterialCraftApp::headless(session, ui);
i18n::set_language(&app.ui.prefs.language);
app.fonts_ready = true;
app.ui.windows.home = app.ui.prefs.show_home;
app
@@ -108,8 +113,10 @@ impl MaterialCraftApp {
last_time: 0.0,
next_autosave,
styled: None,
fonts: fonts::UiFonts::default(),
fonts_ready: false,
};
i18n::set_language(&app.ui.prefs.language);
app.apply_prefs();
app
}
@@ -157,12 +164,12 @@ impl MaterialCraftApp {
}
self.next_autosave = now + period;
let dir = user_dir("autosave");
let path = dir.join(format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
let path = dir.join(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
let pkg = self.session.pkg.clone();
let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || {
let result = std::fs::create_dir_all(&dir)
.map_err(|e| e.to_string())
.and_then(|_| materialcraft_engine::formats::save_package(&pkg).map_err(|e| e.to_string()))
.and_then(|_| materialcraft_engine::formats::sbs::write_sbs(&pkg).map_err(|e| e.to_string()))
.and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string()));
match result {
Ok(()) => log::info!("autosaved {}", path.display()),
@@ -205,6 +212,8 @@ impl MaterialCraftApp {
ctx.request_repaint();
return;
}
i18n::set_language(&self.ui.prefs.language);
self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences);
let now = ctx.input(|i| i.time);
let dt = (now - self.last_time) as f32;
if dt > 0.0 {
+8
View File
@@ -252,6 +252,14 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) {
return;
}
// Selected wires take Delete and Backspace before the node commands do, and X swaps them.
if !app.graph.selected_wires.is_empty() {
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) {
crate::graph_view::delete_selected_wires(app);
} else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) {
crate::graph_view::swap_selected_wires(app);
}
}
let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect();
for c in materialcraft_engine::command_specs() {
if table.iter().any(|(id, _)| *id == c.id) {
+6 -2
View File
@@ -43,10 +43,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.set_width(ui.available_width());
let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned());
match node {
ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node {
Some(n) => node_props(app, ui, &n),
None => graph_props(app, ui),
}
});
});
}
@@ -85,6 +85,10 @@ fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine:
return;
}
section(ui, "specific", tr("Specific parameters"), |ui| {
if n.def == "levels" {
crate::levels_editor::show(app, ui, n);
ui.add_space(6.0);
}
let exposed: Vec<(String, String)> =
app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default();
for p in &def.params {
+6
View File
@@ -11,6 +11,8 @@ use crate::theme::{Accent, Brightness};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Prefs {
/// UI language code (`i18n::LANGUAGES`).
pub language: String,
pub brightness: Brightness,
pub accent: Accent,
pub ui_scale: f32,
@@ -31,6 +33,7 @@ pub struct Prefs {
impl Default for Prefs {
fn default() -> Self {
Prefs {
language: crate::i18n::os_language().into(),
brightness: Brightness::default(),
accent: Accent::default(),
ui_scale: 1.0,
@@ -105,6 +108,8 @@ pub struct UiState {
pub export_dir: String,
pub export_format: String,
pub export_depth: u32,
/// Export size in pixels; 0 = the graph's own size.
pub export_size: u32,
pub export_pattern: String,
/// Frame the whole graph on the next frame.
#[serde(skip)]
@@ -128,6 +133,7 @@ impl Default for UiState {
export_dir: String::new(),
export_format: "png".into(),
export_depth: 0,
export_size: 0,
export_pattern: "$(graph)_$(identifier)".into(),
frame_all: true,
}
+1 -7
View File
@@ -88,13 +88,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let (r, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
crate::widgets::name(&resp, egui::Role::Image, "2D view");
ui.painter().rect_filled(r, 0.0, tk.viewport);
ui.painter().text(
r.center(),
egui::Align2::CENTER_CENTER,
tr("Double-click a node to show it here"),
egui::FontId::proportional(12.0),
tk.viewport_text,
);
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), tk.viewport_text);
return;
};
let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key)
+19 -1
View File
@@ -142,6 +142,15 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
ui.menu_button(tr("Display"), |ui| {
ui.checkbox(&mut app.view3d.show_env, tr("Environment background"));
ui.separator();
let mut t = app.session.view3d.transparency;
if ui.checkbox(&mut t, tr("Transparency (alpha)")).changed() {
app.run("view.3d", json!({"transparency": t}));
}
let mut a = app.session.view3d.alpha_view;
if ui.checkbox(&mut a, tr("Show alpha channel")).changed() {
app.run("view.3d", json!({"alphaView": a}));
}
});
ui.menu_button(tr("Renderer"), |ui| {
let mut h = app.session.view3d.height_scale * 100.0;
@@ -201,6 +210,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
if let Some(t) = &app.view3d.tex {
p.image(t.id(), frame_rect(rect, app.view3d.tex_size), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
if app.session.view3d.alpha_view {
p.text(rect.left_top() + vec2(8.0, 6.0), egui::Align2::LEFT_TOP, tr("Alpha channel"), egui::FontId::proportional(11.0), tk.viewport_text);
}
if app.session.material_maps().is_empty() {
p.text(
rect.center_top() + vec2(0.0, 18.0),
@@ -233,6 +245,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
crate::widgets::name(&r.response, egui::Role::ComboBox, "Scene");
ui.label(egui::RichText::new(format!("{} sRGB / ACES", icon::SUN)).size(11.0).color(tk.text_dim));
let a = app.session.view3d.alpha_view;
if crate::widgets::icon_button(ui, icon::CHECKERBOARD, tr("Show alpha channel"), a, 20.0).clicked() {
app.run("view.3d", json!({"alphaView": !a}));
}
});
});
}
@@ -261,7 +277,7 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hs = DefaultHasher::new();
let v = &app.session.view3d;
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n)).hash(&mut hs);
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view).hash(&mut hs);
for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale] {
f.to_bits().hash(&mut hs);
}
@@ -350,6 +366,8 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A
height_scale: v.height_scale,
show_env: app.view3d.show_env,
supersample,
transparency: v.transparency,
alpha_view: v.alpha_view,
..Settings::default()
};
let maps = Maps::from_usages(app.session.material_maps());
+11 -12
View File
@@ -79,6 +79,7 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool
Ok(()) => {
app.ui.frame_all = true;
app.toast(format!("{} {name}", tr("Opened")), false);
crate::windows::after_open(app);
}
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't open")), true),
}
@@ -91,16 +92,14 @@ pub fn dropped(app: &mut MaterialCraftApp, ctx: &egui::Context, file: &egui::Dro
#[cfg(not(target_arch = "wasm32"))]
{
let _ = ctx;
let lower = name.to_ascii_lowercase();
if (lower.ends_with(".sbs") || lower.ends_with(".mcraft")) && file.path().is_file() {
// Open from the path so an SBS package finds the bitmaps kept next to it.
crate::windows::open_path(app, &file.path().display().to_string());
return;
}
match file.bytes() {
Ok(bytes) => {
let package = name.to_ascii_lowercase().ends_with(".mcraft");
load(app, &name, bytes, false);
if package {
let path = file.path().display().to_string();
app.session.path = Some(path.clone());
app.ui.add_recent(&path);
}
}
Ok(bytes) => load(app, &name, bytes, false),
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't open")), true),
}
}
@@ -173,9 +172,9 @@ mod web {
pick(ctx, "Images", materialcraft_engine::formats::IMAGE_EXTENSIONS, Pick::Bitmap);
}
/// File ▸ Save: download the package as `<name>.mcraft`.
/// File ▸ Save: download the package as `<name>.sbs` (bitmaps embedded).
pub fn save(app: &mut MaterialCraftApp) {
let name = format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
match materialcraft_engine::file_cmds::save_bytes(&app.session).map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) {
Ok(()) => {
app.session.modified = false;
@@ -198,7 +197,7 @@ mod web {
/// Export outputs: one file downloads as is, several as `<graph>_outputs.zip`.
pub fn export(app: &mut MaterialCraftApp, params: &serde_json::Value) {
let result = materialcraft_engine::file_cmds::export_params(&app.session, params)
.and_then(|(gi, ext, pattern, depth)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth))
.and_then(|(gi, ext, pattern, depth, size)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth, size))
.map_err(|e| e.to_string())
.and_then(|files| {
let files: Vec<(String, Vec<u8>)> = files.into_iter().map(|f| (f.file, f.bytes)).collect();
+24 -5
View File
@@ -20,26 +20,45 @@ pub fn dnd_release<T: std::any::Any + Send + Sync>(resp: &Response) -> Option<st
}
/// A labelled slider in two rows: "Label ........ value" over a slim track with a round knob.
/// Returns the response of the track (`.changed()` when dragged, `.drag_stopped()` at the end).
/// Returns the track response (`.changed()` on a drag or valid numeric edit).
pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, decimals: usize) -> Response {
let tk = Tokens::get(ui.ctx());
let (lo, hi) = (*range.start(), *range.end());
let w = ui.available_width();
let mut edited = false;
ui.horizontal(|ui| {
ui.label(RichText::new(label).color(tk.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut text = format!("{:.*}", decimals, value);
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE));
let id = ui.next_auto_id();
// Keep incomplete input (such as "-") across frames while editing.
let draft = id.with("numeric-draft");
let editing = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id));
let mut text = editing.then(|| ui.data(|d| d.get_temp::<String>(draft))).flatten().unwrap_or_else(|| format!("{:.*}", decimals, value));
let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE));
name(&r, egui::Role::TextInput, label);
if r.lost_focus()
if (r.changed() || r.lost_focus())
&& !ui.input(|i| i.key_pressed(egui::Key::Escape))
&& let Ok(v) = text.trim().parse::<f32>()
&& v.is_finite()
{
*value = v.clamp(lo, hi);
let v = v.clamp(lo, hi);
edited = v != *value;
*value = v;
}
let focused = r.has_focus();
ui.data_mut(|d| {
if focused {
d.insert_temp(draft, text);
} else {
d.remove::<String>(draft);
}
});
});
});
let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag());
if edited {
resp.mark_changed();
}
let (v, l) = (*value as f64, label.to_string());
resp.widget_info(move || egui::WidgetInfo::slider(true, v, l.clone()));
if (resp.dragged() || resp.clicked())
+63 -16
View File
@@ -105,7 +105,8 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui
.collapsible(false)
.resizable(false)
.default_size(size)
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
.pivot(egui::Align2::CENTER_CENTER)
.default_pos(ctx.content_rect().center())
.show(ctx, body);
}
@@ -197,7 +198,7 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
let mut go = false;
modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 260.0), |ui| {
modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 290.0), |ui| {
let tk = Tokens::get(ui.ctx());
let g = app.session.graph().map(|g| g.name.clone()).unwrap_or_default();
ui.label(RichText::new(format!("{}: {g}", tr("Graph"))).strong());
@@ -229,6 +230,20 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
ui.selectable_value(&mut app.ui.export_depth, d, tr(l));
}
});
let graph_size = app.session.graph().map_or(String::new(), |g| {
let [w, h] = g.size_px();
format!("{} ({w} x {h})", tr("Graph's size"))
});
let size_label = match app.ui.export_size {
0 => graph_size.clone(),
px => format!("{px} px"),
};
crate::widgets::combo(ui, tr("Resolution"), size_label, |ui| {
ui.selectable_value(&mut app.ui.export_size, 0, graph_size);
for px in [256u32, 512, 1024, 2048, 4096, 8192] {
ui.selectable_value(&mut app.ui.export_size, px, format!("{px} px"));
}
});
ui.horizontal(|ui| {
ui.label(tr("File names"));
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_pattern).desired_width(260.0));
@@ -250,7 +265,7 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
app.toast(tr("Choose a folder to export to"), true);
} else {
let depth = if app.ui.export_depth == 0 { Value::Null } else { json!(app.ui.export_depth) };
let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth});
let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth, "size": if app.ui.export_size == 0 { Value::Null } else { json!(app.ui.export_size) }});
#[cfg(target_arch = "wasm32")]
{
crate::web_files::export(app, &p);
@@ -271,8 +286,17 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 300.0), |ui| {
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 340.0), |ui| {
let p = &mut app.ui.prefs;
let current_lang = crate::i18n::current();
crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| {
for l in &crate::i18n::LANGUAGES {
if ui.selectable_label(p.language == l.code, l.name).clicked() {
p.language = l.code.to_owned();
crate::i18n::set_language(&p.language);
}
}
});
crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| {
for b in Brightness::ALL {
ui.selectable_value(&mut p.brightness, b, tr(b.label()));
@@ -449,14 +473,22 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) {
pub fn console(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let console_line = |text: String, color: Color32| RichText::new(text).monospace().size(11.0).color(color);
egui::ScrollArea::vertical().stick_to_bottom(true).auto_shrink([false, false]).show(ui, |ui| {
for l in &app.session.log {
ui.label(RichText::new(l).monospace().size(11.0).color(tk.text));
for line in &app.session.log {
let warning = line.starts_with(materialcraft_engine::WARNING_PREFIX);
ui.label(console_line(line.clone(), if warning { tk.warning } else { tk.text }));
}
for (id, r) in &app.session.cooked.nodes {
if let Some(e) = &r.error {
ui.label(RichText::new(format!("node {}: {e}", id.0)).monospace().size(11.0).color(tk.danger));
}
// Placeholders for missing SBS nodes are already listed in the warnings, so they get one line
let (failed, placeholders) = app.session.cook_failures();
for (id, error) in failed {
ui.label(console_line(format!("node {}: {error}", id.0), tk.danger));
}
if placeholders > 0 {
let text = format!("{placeholders} {}", tr("placeholder node(s) stand in for nodes MaterialCraft doesn't have yet (see the warnings above)"));
ui.label(console_line(text, tk.warning));
}
});
}
@@ -510,8 +542,17 @@ pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p
});
}
/// Extensions File ▸ Open reads: packages and portable materials (opening their source package).
pub const OPEN_EXTS: &[&str] = &["mcraft", MATERIAL_EXT];
/// Extensions File ▸ Open reads: SBS (the main format) and `.mcraft` packages, and materials (their source package).
pub const OPEN_EXTS: &[&str] = &["sbs", "mcraft", MATERIAL_EXT];
/// After a package opened with warnings (an SBS file using nodes MaterialCraft lacks, say), bring the Console forward.
pub fn after_open(app: &mut MaterialCraftApp) {
let warning_count = app.session.load_warnings.len();
if warning_count > 0 {
app.ui.dock.focus(crate::docking::Panel::Console);
app.toast(format!("{} {warning_count} {}", tr("Opened with"), tr("warnings: see the Console")), false);
}
}
/// File menu actions that need a file dialog. Returns true when handled.
pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> bool {
@@ -521,7 +562,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
{
match id {
"file.open" => {
if let Some(p) = rfd::FileDialog::new().add_filter("MaterialCraft package or material", OPEN_EXTS).pick_file() {
if let Some(p) = rfd::FileDialog::new().add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() {
open_path(app, &p.display().to_string());
}
true
@@ -535,9 +576,14 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
true
}
"file.save" | "file.saveAs" => {
let name = format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("MaterialCraft package", &["mcraft"]).save_file() {
let path = p.display().to_string();
let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
if let Some(p) = rfd::FileDialog::new()
.set_file_name(name)
.add_filter("SBS package", &["sbs"])
.add_filter("MaterialCraft package (older format)", &["mcraft"])
.save_file()
{
let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string());
if app.run("file.save", json!({"path": path})).is_some() {
app.ui.add_recent(&path);
app.toast(format!("{} {path}", tr("Saved")), false);
@@ -598,5 +644,6 @@ pub fn open_path(app: &mut MaterialCraftApp, path: &str) {
app.ui.add_recent(path);
app.ui.frame_all = true;
app.toast(format!("{} {path}", tr("Opened")), false);
after_open(app);
}
}
+76
View File
@@ -0,0 +1,76 @@
//! Home and export dialogs start centered, but their title bars must allow movement.
use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2};
use egui_kittest::Harness;
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
type State = (MaterialCraftApp, Rect);
fn harness(id: &'static str, render: bool) -> Harness<'static, State> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = id == "home";
app.ui.windows.export = id == "export";
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
move |ui, (app, rect): &mut State| {
app.step(&ui.ctx().clone());
app.draw(ui);
*rect = ui.ctx().memory(|m| m.area_rect(egui::Id::unique(id))).unwrap_or(Rect::NOTHING);
},
(app, Rect::NOTHING),
);
h.run_steps(10);
h
}
fn drag_title(h: &mut Harness<'static, State>) {
let from = h.state().1.min + vec2(120.0, 12.0);
h.event(Event::PointerMoved(from));
h.step();
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for step in 1..=8 {
h.event(Event::PointerMoved(from + vec2(10.0, 7.5) * step as f32));
h.step();
}
h.event(Event::PointerButton { pos: from + vec2(80.0, 60.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(10);
}
#[test]
fn home_and_export_can_be_dragged_and_keep_their_position() {
for id in ["home", "export"] {
let mut h = harness(id, false);
let before = h.state().1;
assert!(before.is_finite());
assert!(before.center().distance(pos2(800.0, 480.0)) < 3.0, "{id}: initial rectangle {before:?}");
drag_title(&mut h);
let moved = h.state().1;
assert!(moved.min.distance(before.min + vec2(80.0, 60.0)) < 8.0, "{id}: did not follow the drag: {before:?} -> {moved:?}");
// Later frames and reopening the same dialog must not snap it back to the center.
h.state_mut().0.ui.windows.home = false;
h.state_mut().0.ui.windows.export = false;
h.run_steps(3);
h.state_mut().0.ui.windows.home = id == "home";
h.state_mut().0.ui.windows.export = id == "export";
h.run_steps(10);
assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: reopening lost the dragged position");
h.set_size(vec2(1500.0, 900.0));
h.run_steps(10);
assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: resizing recentered the dialog");
}
}
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn dialog_drag_snapshots() {
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR"));
std::fs::create_dir_all(&dir).unwrap();
for id in ["home", "export"] {
let mut h = harness(id, true);
h.render().unwrap().save(dir.join(format!("{id}-centered.png"))).unwrap();
drag_title(&mut h);
h.render().unwrap().save(dir.join(format!("{id}-moved.png"))).unwrap();
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Exact numeric edits must survive intervening frames and reach engine parameters.
use egui::{Event, Key, Modifiers, vec2};
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_engine::core::{NodeId, Value};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.run("file.new", json!({"template":"empty"})).unwrap();
let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap());
app.session.reset_history();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(8);
(h, id)
}
fn focus_x(h: &mut Harness<'static, MaterialCraftApp>, index: usize) {
h.get_all(By::new().role(egui::accesskit::Role::TextInput).label("X")).nth(index).unwrap().click();
h.step();
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.step();
}
fn type_text(h: &mut Harness<'static, MaterialCraftApp>, text: &str) {
h.event(Event::Text(text.into()));
h.step();
h.run_steps(4);
}
fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32; 2] {
match h.state().session.graph().unwrap().node(id).unwrap().params.get(param) {
Some(Value::Float2(v)) => *v,
None => match materialcraft_engine::nodes::find("transformation").unwrap().params.iter().find(|p| p.id == param).unwrap().default {
Value::Float2(v) => v,
_ => panic!("not a pair"),
},
other => panic!("unexpected value {other:?}"),
}
}
#[test]
fn scale_x_commits_on_enter_and_focus_loss_with_undo() {
for enter in [true, false] {
let (mut h, id) = harness(false);
focus_x(&mut h, 1);
type_text(&mut h, "4");
if enter {
h.key_press(Key::Enter);
h.step();
} else {
h.get_by_label("Node label").click();
h.step();
}
h.run_steps(5);
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0], "Scale X did not persist (Enter={enter})");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(3);
assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]);
h.state_mut().run("edit.redo", json!({})).unwrap();
h.run_steps(3);
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]);
}
}
#[test]
fn a_negative_decimal_can_be_typed_across_frames() {
let (mut h, id) = harness(false);
focus_x(&mut h, 0);
for part in ["-", ".", "5"] {
type_text(&mut h, part);
}
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [-0.5, 0.0]);
assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]);
}
#[test]
fn clicking_the_canvas_and_switching_nodes_keep_the_right_values() {
let (mut h, id) = harness(false);
focus_x(&mut h, 1);
type_text(&mut h, "4");
let pos = h.state().graph.view.left_top() + vec2(20.0, 20.0);
h.event(Event::PointerMoved(pos));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(4);
assert!(h.state().session.selection.is_empty());
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]);
h.state_mut().run("graph.select", json!({"ids": [id.0]})).unwrap();
h.run_steps(4);
focus_x(&mut h, 1);
type_text(&mut h, "5");
let other = NodeId(h.state_mut().run("graph.node.add", json!({"def":"transformation","at":[300,0]})).unwrap()["id"].as_u64().unwrap());
h.run_steps(4);
h.key_press(Key::Enter);
h.step();
assert_eq!(pair(&h, id, "scale"), [5.0, 1.0]);
assert_eq!(pair(&h, other, "scale"), [1.0, 1.0], "an edit leaked into the newly selected node");
}
#[test]
fn invalid_input_is_ignored_and_values_are_clamped() {
let (mut h, id) = harness(false);
focus_x(&mut h, 0);
type_text(&mut h, "NaN");
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [0.0, 0.0]);
focus_x(&mut h, 0);
type_text(&mut h, "123");
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]);
focus_x(&mut h, 0);
type_text(&mut h, "-");
h.key_press(Key::Escape);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]);
}
#[test]
fn integer_input_and_slider_track_both_update_the_node() {
let (mut h, id) = harness(false);
let input = By::new().role(egui::accesskit::Role::TextInput).label("Random seed");
h.get(input).click();
h.step();
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.step();
type_text(&mut h, "42");
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 42);
let pos = h.get(By::new().role(egui::accesskit::Role::Slider).label("Random seed")).rect().center();
h.event(Event::PointerMoved(pos));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(4);
assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 500);
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn exact_scale_screenshot() {
let (mut h, id) = harness(true);
focus_x(&mut h, 1);
type_text(&mut h, "4");
h.key_press(Key::Enter);
h.step();
h.run_steps(8);
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]);
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR"));
std::fs::create_dir_all(&dir).unwrap();
h.render().unwrap().save(dir.join("scale-x-4.png")).unwrap();
}
+98 -1
View File
@@ -5,7 +5,10 @@
use std::time::Duration;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
@@ -33,6 +36,55 @@ fn save(h: &mut Harness<'static, MaterialCraftApp>, dir: &std::path::Path, name:
println!("wrote {}", dir.join(format!("{name}.png")).display());
}
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn explorer_export_opens_the_clicked_graph() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.run("graph.duplicate", json!({"graph": 0}));
app.session.pkg.graphs[1].name = "Export target".into();
app.run("graph.open", json!({"graph": 0}));
let mut h = harness(app, 1600.0, 960.0);
settle(&mut h, 5);
h.get_by_label("Export target").click_secondary();
settle(&mut h, 3);
h.get_all(By::new().label("Export outputs...")).last().unwrap().click();
settle(&mut h, 3);
assert_eq!(h.state().session.graph, 1);
assert!(h.state().ui.windows.export);
if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) {
std::fs::create_dir_all(&dir).unwrap();
save(&mut h, &dir, "explorer-export");
}
}
/// The startup graph stays empty through real UI frames; templates are still available on demand.
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn empty_startup_can_create_a_template() {
let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let mut h = harness(app, 1600.0, 960.0);
settle(&mut h, 40);
assert_eq!(h.state().session.pkg.graphs.len(), 1);
assert!(h.state().session.graph().unwrap().nodes.is_empty());
assert!(h.state().graph.rects.is_empty());
if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) {
std::fs::create_dir_all(&dir).unwrap();
save(&mut h, &dir, "empty-startup");
}
h.get_by_label("New graph...").click();
settle(&mut h, 4);
h.get_by_label("Brick wall").click();
settle(&mut h, 4);
h.get_by_label("Create").click();
settle(&mut h, 40);
assert_eq!(h.state().session.pkg.graphs.len(), 2);
assert!(!h.state().session.graph().unwrap().nodes.is_empty());
assert!(!h.state().graph.rects.is_empty());
if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) {
save(&mut h, &dir, "chosen-template");
}
}
#[test]
#[ignore]
fn snapshots() {
@@ -63,6 +115,26 @@ fn snapshots() {
save(&mut h, &dir, "new-graph");
h.state_mut().ui.windows.new_graph = false;
// A cut-out material in the 3D view (an opacity output), a reroute dot pulled out of a wire
// and another wire selected; then the alpha channel view.
h.state_mut().run("file.new", json!({"template": "wood", "size": 512}));
let holes = h.state_mut().run("graph.node.add", json!({"def": "grid_lines", "at": [0, -260]})).unwrap()["id"].as_u64().unwrap();
let out = h.state_mut().run("graph.node.add", json!({"def": "output", "at": [420, -260], "connectFrom": {"node": holes}, "params": {"usage": 7}})).unwrap()
["id"]
.as_u64()
.unwrap();
h.state_mut().run("graph.wire.insertDot", json!({"to": out, "toPort": "input", "at": [210, -330]}));
let wire = h.state().session.graph().unwrap().connections.iter().find(|c| c.to.0 != out).map(|c| (c.to, c.to_port.clone()));
h.state_mut().graph.selected_wires = wire.into_iter().collect();
h.state_mut().run("view.3d", json!({"scene": "sphere"}));
h.state_mut().ui.frame_all = true;
settle(&mut h, 60);
save(&mut h, &dir, "alpha-transparency");
h.state_mut().run("view.3d", json!({"alphaView": true}));
settle(&mut h, 40);
save(&mut h, &dir, "alpha-channel");
h.state_mut().run("view.3d", json!({"alphaView": false, "scene": "rounded_cube"}));
// A pixel processor drawing rings, with its function graph open.
h.state_mut().run("file.new", json!({"template": "empty", "name": "Rings"}));
let f = json!({"t": "function", "v": {"nodes": [
@@ -85,6 +157,31 @@ fn snapshots() {
h.state_mut().ui.frame_all = true;
settle(&mut h, 40);
save(&mut h, &dir, "function-editor");
h.state_mut().fn_editor = None;
// The Levels editor: the input histogram under the transfer curve, with its handles.
h.state_mut().run("file.new", json!({"template": "stone_tiles", "size": 512}));
let levels = {
let g = h.state().session.graph().unwrap();
g.nodes.iter().find(|n| n.def == "levels" && g.connections.iter().any(|c| c.to == n.id)).map(|n| n.id.0)
};
if let Some(id) = levels {
h.state_mut().run("graph.select", json!({"ids": [id]}));
h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_low", "value": 0.3}));
h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_mid", "value": 0.35}));
h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_high", "value": 0.85}));
h.state_mut().run("view.2d", json!({"node": id}));
}
h.state_mut().ui.frame_all = true;
settle(&mut h, 40);
save(&mut h, &dir, "levels-editor");
// An SBS file with nodes MaterialCraft doesn't have: placeholders on the canvas, the warnings
// in the Console, which comes forward by itself.
let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs/all_nodes.sbs");
materialcraft_ui_egui::windows::open_path(h.state_mut(), sample.to_str().unwrap());
settle(&mut h, 60);
save(&mut h, &dir, "sbs-warnings");
}
/// Steady-state UI build time per frame with each panel closed in turn (release):
+24 -5
View File
@@ -18,12 +18,14 @@ L1 nodes the node library: NodeDef (ports, parameters, category, cook fn) f
L2 eval cooking: topological order, output sizes (relative to input / parent, absolute, preview
cap), parameter resolution (defaults, overrides, bindings to exposed inputs), the
content-addressed LRU cache, graph instances (sub-graphs, recursion-guarded)
L2 formats .mcraft packages (zip: package.json + resources/), .mcmat portable materials, bitmap
L2 formats .sbs packages (the main format, sbs.rs), .mcraft packages (zip: package.json +
resources/), .mcmat portable materials, bitmap
decode, texture encode (PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR at 8/16/32 bits), atomic writes
L3 engine Session (package, open graph, selection, 2D/3D view state, snapshot undo, cache),
the command registry, inspect, sample materials and graph templates
L3 render the 3D view: BVH ray casts, parallax occlusion from the height output, GGX PBR with
prefiltered IBL + SH diffuse, ACES tone mapping; procedural environments
prefiltered IBL + SH diffuse, alpha transparency (layered ray compositing) and an
alpha channel view, ACES tone mapping; procedural environments
L4 automation MCP server (rmcp), JSON-lines RPC (stdio/TCP with token), bridge client, workspace sandbox
L5 ui-egui the egui shell: docking (craft-ui), graph editor, library, properties, 2D/3D views,
dialogs, menus, control channel with synthetic input
@@ -61,16 +63,33 @@ drag) into one undo step. See [control-protocol.md](control-protocol.md).
`MaterialCraftApp` owns the session and `UiState` (serde, persisted by eframe, readable and writable
through `ui.inspect` / `ui.set`). The dock (craft-ui) hosts eight panels around the protected graph
panel. The graph editor lays nodes out in graph space, draws cards with thumbnails from the cook
results (uploaded once per cache key), wires as cubic beziers between typed ports, and turns
gestures into commands only when they complete. The 3D view renders with `materialcraft-render`
results (uploaded once per cache key), wires as cubic beziers between typed ports (hit-tested
against the curve, so wires can be selected, deleted, swapped or split with a reroute dot), and turns
gestures into commands only when they complete. See [wires-and-alpha.md](wires-and-alpha.md). The 3D view renders with `materialcraft-render`
on the CPU: half resolution while the camera moves, 2×2 supersampled when it rests.
`crates/ui-egui/tests/snapshot.rs` renders the real UI offscreen with egui_kittest + wgpu for visual
checks and README screenshots.
The properties panel builds every parameter editor from the node catalog; the Levels node adds a
histogram editor with range handles on top of its sliders ([levels-editor.md](levels-editor.md)).
## Files
A `.mcraft` package is a zip: `package.json` (the serde `Package`, format version 1) and
SBS (`.sbs`, `formats/src/sbs.rs`) is the main project format: XML with the package's graphs, nodes,
wires, parameters, graph inputs and outputs, frames and comments, and bitmaps embedded as
zlib/base64 data. MaterialCraft writes the SBS data plus, in a trailing XML comment, its own exact
copy of the package with a hash of the `<content>` it belongs to; reading uses the exact copy while
the hash matches (so nothing MaterialCraft-specific is lost) and the SBS data otherwise. Reading never
fails on what MaterialCraft lacks: atomic filters map to atomic nodes, library nodes map by name,
instances of graphs in the same file become graph instances, and anything else becomes a
`missing_node` placeholder (`core::MISSING_NODE`) that keeps its ports, wires and raw SBS parameters,
cooks to a soft error, and is written back unchanged. Every gap is a warning in
`Session::load_warnings`, the Console (`Session::warn`) and `session.inspect` (`package.warnings`).
Bitmaps an SBS file keeps next to it load from its folder only (`file_cmds::linked_files`).
A `.mcraft` package (the older format, still read and written: packages opened from a `.mcraft`
save back to it) is a zip: `package.json` (the serde `Package`, format version 1) and
`resources/<name>` for embedded bitmaps. Node parameters are stored only where they differ from the
catalog defaults, so new defaults reach old files and files stay small.
+15 -4
View File
@@ -11,7 +11,15 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands:
3. **The app's control channel** (`materialcraft --control <port>`): one JSON request per line,
`{"id", "method", "params"}` → `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`.
The first request must be `{"method":"auth","params":{"token":"…"}}` with the token from
`MATERIALCRAFT_CONTROL_TOKEN` or the file `<temp>/materialcraft-control-<port>.token`.
`MATERIALCRAFT_CONTROL_TOKEN` (16 to 1024 printable ASCII characters) or the file
`<temp>/materialcraft-control-<port>.token`, a fresh random 256-bit token written after the port
is bound. On Unix the file is created new with mode 0600 (owner only); if an existing file there
cannot be replaced, the control server stays off and `MATERIALCRAFT_CONTROL_TOKEN` is the
alternative. Clients (`materialcraft-cli mcp --bridge`) refuse a token file that is a symlink,
not a regular file, not owned by them, or accessible to group or others. A connection gets one
authentication attempt, within 10 s; a wrong token, any other first request or malformed JSON
closes it. At most 16 connections are served at once. Whoever holds the token has full
engine-command authority, including host file access.
Set `MATERIALCRAFT_NO_PREFS=1` for scripted runs so the user's layout is left alone.
## Methods
@@ -25,7 +33,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands:
| `session.inspect` | all | package, graphs, the open graph's nodes (def, params, bindings, base, ports, cook error/size/mean/ms), wires, frames, comments, pins, exposed inputs, views, history |
| `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O |
| `bitmap.import {path, name?}` | headless | embed an image as a resource |
| `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output |
| `outputs.export {dir, format?, pattern?, depth?, size?, graph?}` | headless | cook at full size and write every output |
| `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii |
| `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts |
| `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click |
@@ -62,13 +70,15 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
| `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) |
| `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` |
| `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` |
| `graph.wire.insertDot` | `{to, toPort, at?}`: split the wire feeding `to.toPort` with a reroute Dot node at `at` (graph point, default midway), selected |
| `graph.wire.swap` / `graph.wire.delete` | `{wires: [{to, toPort}, ...]}`: swap (two) or reverse (more, in input order) where the wires come from / delete them, one undo step each |
| `graph.node.param` | `{id?, param, value}`: numbers, `[x, y]`, `"#rrggbb"`, enum index, curve `[[x, y], …]`, gradient `[[pos, color], …]`, or a typed value `{"t": "function", "v": {...}}` |
| `graph.node.base` | `{id?, sizeMode?, size?, format?, seed?, tiling?}` |
| `graph.exposed.add` / `graph.exposed.set` | `{id, label?, default?, bind?: {node, param}}` / `{id, value}` |
| `graph.node.function` | `{id?, param, function}` drives a parameter by a function graph of the graph's inputs (dynamic parameter); `{id?, param, remove: true}` removes it |
| `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values |
| `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance |
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, parallax depth |
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, parallax depth, `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) |
| `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) |
| `library.list` | `{filter?, category?}`: every node with ports and parameters |
@@ -116,7 +126,8 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k
| `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.mcraft file.exportMaterial {...}` to re-cook at its texture set's resolution with its own values and baked mesh maps |
| `file.sendToTextureCraft` | `{graph?}`: export into TextureCraft's library folder (`Documents/TextureCraft/library`), where its shelf lists it |
| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package |
| `file.open` | also opens a `.mcmat`'s source package, on its graph, with no file name |
| `file.open` | opens `.sbs` (by content) and `.mcraft` packages, and a `.mcmat`'s source package, on its graph, with no file name. Returns `warnings`: what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders); also in `session.inspect` as `package.warnings` |
| `file.save` | `{path?}`: SBS unless the file is `.mcraft`; `.sbs` is appended when `path` has no package extension |
## MCP tools
+8 -5
View File
@@ -1,14 +1,16 @@
# File format parity
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (`.mcmat` portable materials) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-04 · **Change:** major (SBS is the main project format) · **Target:** the professional node-based material workflow
MaterialCraft does not read or write the reference app's proprietary package or archive formats
(a non-goal of the clean room). It has its own package format and reads and writes the open image
formats material artists exchange.
SBS packages are MaterialCraft's main project format (issue #49), read and written with its own
clean-room code from the format's public documentation and sample files. The older `.mcraft`
package is still read and written. MaterialCraft also reads and writes the open image formats
material artists exchange.
| Format | Read | Write | Fidelity | Tests |
|---|---|---|---|---|
| `.mcraft` package (zip: `package.json` + `resources/`) | Yes | Yes | Lossless (graphs, parameters, frames, comments, pins, exposed inputs, embedded bitmaps) | `formats::tests::package_round_trip`, engine `package_save_and_open_round_trip` |
| `.sbs` package (XML), the main format | Yes: atomic filters, library nodes with a MaterialCraft node of the same name (88 of the 491 in `assets/sbs/all_nodes.sbs`), graph instances, graph inputs/outputs, exposed values, parameters linked to inputs, base parameters, frames, comments, embedded and linked bitmaps and SVGs. Anything else (missing nodes, curve points, gradient keys, function graphs, environment maps) is a Console warning; missing nodes stay as placeholders | Yes: SBS data with bitmaps embedded, plus MaterialCraft's exact copy | Lossless for files MaterialCraft saved (exact copy, guarded by a content hash); placeholders round-trip their SBS data | `formats::sbs::tests`, engine `sbs_is_the_default_save_format_and_mcraft_still_works`, `an_sbs_file_with_missing_nodes_opens_softly` |
| `.mcraft` package (zip: `package.json` + `resources/`), older | Yes | Yes | Lossless (graphs, parameters, frames, comments, pins, exposed inputs, embedded bitmaps) | `formats::tests::package_round_trip`, engine `package_save_and_open_round_trip` |
| PNG | Yes (8/16-bit, gray and color) | Yes (8/16-bit) | 16-bit gray round-trips within 1/65535 | `formats::tests::export_every_format` |
| JPEG | Yes | Yes (8-bit) | Lossy | same |
| TGA | Yes | Yes (8-bit) | Lossless | same |
@@ -28,5 +30,6 @@ roughness, metallic, height, ambient occlusion, opacity) linear.
| Date | Change | Summary |
|---|---|---|
| 2026-11-04 | major | SBS packages become the main project format; `.mcraft` kept |
| 2026-11-02 | minor | `.mcmat` portable materials replace the published-archive gap |
| 2026-11-02 | major | First version |
Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 660 KiB

+76
View File
@@ -0,0 +1,76 @@
# The Levels editor
The **Levels** node remaps its input: it stretches the input range (*Level in low* to *Level in
high*), bends the midtones (*Level in mid*) and squeezes the result into the output range (*Level
out low* to *Level out high*). Select a Levels node and the **Specific parameters** section of the
properties panel shows a visual editor above the usual sliders. This is a clean-room
implementation.
<p align="center">
<img src="images/materialcraft-levels-editor.png" alt="The stone tiles material with a Levels node selected: in the properties panel, a histogram of the node's input with the levels curve over it, three input handles under it and two output handles under a black-to-white bar" width="100%">
<br><sub>The Levels editor: the input histogram, the transfer curve and the handles</sub>
</p>
## What it shows
- **The input histogram**: how many pixels of the image feeding the node have each value, in
256 bins over 0..1. A grayscale input shows one gray histogram; a color input shows red, green
and blue on top of each other. Values outside 0..1 count in the end bins. The bar heights scale
to the tallest bin *between* pure black and pure white, because masks pile up at the ends and
would flatten everything else. Without an input wire the editor says so.
- **The clipped areas**: the parts of the histogram outside the input range are darkened. Those
values all become the output low or high.
- **The transfer curve** (accent line): the output value for every input value, so the effect
of all five parameters can be read at a glance.
The histogram is computed once per cooked result of the input and reused until that result
changes.
## Handles
| Handle | Row | Parameter | Behavior |
|---|---|---|---|
| Black triangle | under the histogram | *Level in low* | Cannot pass the high handle |
| Gray triangle | under the histogram | *Level in mid* | Sits where the midtone acts: `in low + in mid × (in high − in low)`. It moves with the low and high handles and stays strictly inside the range (stored as 0.01..0.99) |
| White triangle | under the histogram | *Level in high* | Cannot pass the low handle |
| Black triangle | under the gradient bar | *Level out low* | Free |
| White triangle | under the gradient bar | *Level out high* | Free; dragging it left of the low handle inverts the output |
- Hovering a handle highlights it and shows its parameter and value.
- Dragging a handle sets its parameter live. One drag is one undo step.
- A parameter bound to a graph input or driven by a function shows its handle but cannot be
dragged; edit it where it is driven.
- The sliders below still give exact values and the right-click menu (reset, expose, bind,
function).
## What changed in the node
- *Level in mid* was always relative to the input range (0.5 = linear), but the only editor was
an absolute 0..1 slider, so its position meant nothing next to *Level in low* and *Level in
high*. The gray handle now shows where it really acts.
- Dragging the input low handle past the high one used to flip the remap without warning. The
editor keeps them apart. The sliders and commands still accept any values, so existing files
cook exactly as before.
- `levels_fn` no longer lets a NaN (from an input or a hostile parameter) spread through the
graph: it is treated as 0.
## For agents and scripts
The editor only sets the node's existing parameters, so there is nothing new to drive:
```json
{"id": 1, "method": "command.run", "params": {"id": "graph.node.param", "params": {"id": 42, "param": "in_mid", "value": 0.35}}}
```
`session.inspect` reports the parameters and the input's cooked `mean`; the 2D view's histogram
(`view.2d {"histogram": true}`) shows the node's output.
## Implementation and tests
- `crates/ui-egui/src/levels_editor.rs`: `histogram`, `values`, `mid_position`, `drag_value`
(the handle constraints) and the drawing; called from `properties.rs` for `levels` nodes.
- `crates/nodes/src/atomic.rs`: the NaN guard in `levels_fn`.
- Tests: `levels_editor::tests` (histogram counts, end bins and NaN; handle constraints and the
relative mid), `atomic::levels_tests` (identity, stretch and clip, the relative mid, output
range and inversion, threshold, NaN), and the `levels-editor` scene of the `snapshots` UI test,
which renders the screenshot above.
+2
View File
@@ -8,6 +8,7 @@ so catalogs can be added without touching callers. Today only English ships.
| Language | Code | Status | Notes |
|---|---|---|---|
| English | `en` | Complete | Source language |
| Arabic | `ar` | Complete | Full UI translation table (`crates/ui-egui/src/i18n/ar.rs`), system font fallbacks (Segoe UI / SF Arabic / Noto Sans Arabic), live language picker in Preferences |
| French, German, Spanish, Portuguese (Brazil), Italian | `fr`, `de`, `es`, `pt-br`, `it` | Not started | Planned with the shared craft-i18n catalogs |
| Japanese, Chinese (Simplified), Korean | `ja`, `zh-hans`, `ko` | Not started | Needs the craft-fonts CJK faces (`CRAFT_FONTS_DIR`), as in TextureCraft |
@@ -15,4 +16,5 @@ so catalogs can be added without touching callers. Today only English ships.
| Date | Change | Summary |
|---|---|---|
| 2026-11-03 | minor | Add complete Arabic (`ar`) UI localization and font fallbacks |
| 2026-11-02 | major | First version |
+3 -3
View File
@@ -8,15 +8,15 @@ automation + tests), weighted by how much of the day each area carries. **Remain
| Area | Weight | Done | What works | Main gaps |
|---|---:|---:|---|---|
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
| Atomic nodes | 12 | 95% | Bitmap, Blend (16 modes, masks, alpha), Blur, Channels Shuffle, Curve, Directional Blur, Directional Warp, Distance (with color propagation), Emboss, FX-Map (grid, quadtree and scatter modes with per-instance randomness), Gradient (Dynamic), Gradient Map, Grayscale Conversion, HSL, Levels, Normal, Pixel Processor, Value Processor, Sharpen, SVG (path data, fill rules, stroke), Text (own stroke font), Transformation 2D, Uniform Color, Warp, inputs, outputs, dots, graph instances | FX-Map driven by per-iteration functions, SVG arcs and SVG files, font choice for Text |
| Node library | 20 | 45% | 227 nodes: noises (tileable 3D Perlin, simplex and Worley, cracks, stones, dirt, grunge maps and more), patterns (tile generator and sampler, bricks, hexagons, weave, shape splatter, paint strokes, scratches), filters (adjustments, blending, blurs, channels, effects, normal map tools, tiling, transforms), the flood fill family, whole-material and height blending, weathering (rust, moss, leaks, edge damage, edge wear, dust) | The rest of the reference library's ~400 graphs: more grunge and scan processing, mesh-based generators and bakers, spline tools, SDF functions |
| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items |
| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages |
| 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources |
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
| Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run |
| **Total** | **100** | **≈ 67%** | | |
+170
View File
@@ -0,0 +1,170 @@
# Editing wires and viewing alpha in the 3D view
This page documents two editor features: selecting, deleting, swapping and rerouting wires in
the graph editor, and the alpha (transparency) support of the 3D view. Both are clean-room implementations;
every action is an engine command, so the CLI, the control channel and MCP can do the same as the
mouse.
<p align="center">
<img src="images/materialcraft-alpha-transparency.png" alt="The wood planks material with a Grid Lines opacity output on a sphere in the 3D view: the gaps are see-through and the back of the sphere shows through them; in the graph, a reroute dot bends the wire from Grid Lines to the opacity output" width="100%">
<br><sub>A cut-out material in the 3D view, and a reroute dot pulled out of a wire</sub>
</p>
## Wires in the graph editor
A wire runs from an output port to an input port. Every input takes at most one wire, so a wire is
named by the input it feeds: the target node and its input port (`to`, `toPort`).
### Gestures
| Gesture | What it does |
|---|---|
| Hover a wire | The wire turns white and the pointer becomes a hand: it can be clicked |
| Click a wire | Selects it alone (drawn thicker, in the accent color); the node selection is cleared |
| **Shift**+click a wire | Adds it to the wire selection |
| **Ctrl**+click a wire | Adds it to the wire selection, or removes it when it is already selected |
| **Delete** or **Backspace** with wires selected | Deletes every selected wire (one undo step) |
| **X** with two or more wires selected | Swaps where the selected wires come from (see below); they stay selected, so **X** again swaps back |
| Drag a wire | Pulls a reroute **Dot** out of the wire where it was pressed and moves it with the pointer, in one gesture |
| Double-click a wire | Drops a reroute Dot at that point |
| Right-click a wire | Opens the wire menu: **Insert reroute dot**, **Swap selected links (X)** (with two or more selected), **Delete link** / **Delete selected links**. Right-clicking a wire that is already selected keeps the selection |
| Click anywhere else | Drops the wire selection |
A wire is hit within 5 points of its curve. Node cards, ports and comments sit on top of wires, so
a press there acts on them, not on the wire underneath. Alt+drag and middle-drag still pan the
canvas.
### Swapping wires
Select the wires going into a node and press **X** to swap their sources. On a **Blend** node, select
the *Foreground* and *Background* wires and press **X**: what fed the foreground now feeds the
background and the other way around, so the two layers trade places without rewiring by hand.
- **Two wires** trade sources.
- **More than two** reverse their sources. The wires are ordered by target node, then by the order
of the inputs on the node (top to bottom), and the first wire's source goes to the last input,
the second's to the one before it, and so on. With *Foreground*, *Background* and *Opacity*
selected on a Blend, the foreground and opacity sources trade places and the background keeps
its own.
- The order you click the wires in does not matter, so the result is predictable.
- Wires into different nodes can be swapped too. A swap that would feed a node into itself (a
cycle) is refused with a message, and nothing changes.
- One wire alone cannot be swapped: the editor says to select two or more.
- The swap is one undo step.
### Reroute dots
A Dot is the existing `dot` node: one input, one output, passing its input through unchanged. It
lets a wire bend around other nodes. After a dot is inserted it is selected, so it can be dragged,
deleted (**Delete** removes it with both of its wires; **Backspace**, *Delete and relink*, removes
it and joins the wire back up) or given more dots. Inserting a dot is one undo step: **Ctrl+Z**
restores the straight wire.
### Commands
| Command | Params | Result |
|---|---|---|
| `graph.wire.insertDot` | `{to, toPort, at?: [x, y]}` | Splits the wire feeding `to.toPort` with a Dot centered at `at` (graph space; default: midway between the two nodes). Returns `{"id": <dot id>}` and selects the dot. Errors when no wire feeds that input. |
| `graph.wire.swap` | `{wires: [{to, toPort}, ...]}` | Swaps (two wires) or reverses (more) the sources of the listed wires, as described above. Returns `{"swapped": n}`. Errors with fewer than two wires, a wire listed twice, a missing wire or a cycle; nothing changes then. |
| `graph.wire.delete` | `{wires: [{to, toPort}, ...]}` | Deletes the listed wires in one undo step (what the Delete key and the menu run). Returns `{"deleted": n}`. |
| `graph.disconnect` | `{to, toPort}` | Deletes the single wire feeding `to.toPort`. |
Over the control channel (see [control-protocol.md](control-protocol.md)), splitting the wire
feeding node 12's `input` with a dot at (240, 80), then deleting the wire from the dot to node 12:
```json
{"id": 1, "method": "command.run", "params": {"id": "graph.wire.insertDot", "params": {"to": 12, "toPort": "input", "at": [240, 80]}}}
{"id": 2, "method": "command.run", "params": {"id": "graph.disconnect", "params": {"to": 12, "toPort": "input"}}}
```
Swapping the two layers of Blend node 7:
```json
{"id": 3, "method": "command.run", "params": {"id": "graph.wire.swap", "params": {"wires": [{"to": 7, "toPort": "foreground"}, {"to": 7, "toPort": "background"}]}}}
```
`session.inspect` lists every wire under `graph.connections` and the dot under `graph.nodes`
(`"def": "dot"`). The wire selection itself is editor state, like hover, and is not part of the
session.
## Alpha in the 3D view
<p align="center">
<img src="images/materialcraft-alpha-channel.png" alt="The same sphere in the alpha channel view: the opaque grid lines are white and the clear gaps black" width="100%">
<br><sub>The alpha channel view: white is opaque, black is clear</sub>
</p>
### Where the alpha comes from
1. The output with the **Opacity** usage, read as grayscale, when the graph has one.
2. Otherwise the alpha channel of the **Base color** output, when it is a color image.
3. Otherwise the material is opaque.
### Transparency
Where the alpha is below one, the surface lets light through: each camera ray composites the
surfaces it meets front to back (`color × alpha`, the rest passes on) through up to eight layers,
then shows what lies behind: the backdrop, or the environment when **Display ▸ Environment
background** is on. Back faces seen through a clear front are shaded facing the viewer, so a
cut-out sphere shows its inside. Parallax from the height output applies to every layer.
**Display ▸ Transparency (alpha)** turns this off, so the alpha is ignored and the mesh is opaque.
It is on by default.
Before this change, the opacity output only mixed each pixel with the flat backdrop color; the
back of the mesh and the environment never showed through.
### Alpha channel view
**Display ▸ Show alpha channel**, or the checkerboard button in the 3D view's bottom bar, shows the
alpha on the mesh unlit: white is opaque, black is clear, values in between are linear (0.5 shows
as 50% gray, without tone mapping). The view is labeled *Alpha channel* in its top-left corner.
It shows the first surface only, so the channel reads clearly.
### Commands
`view.3d` takes two booleans; both are part of the session's `view3d` state and of
`session.inspect`:
| Param | Default | Meaning |
|---|---|---|
| `transparency` | `true` | See through the mesh where the alpha is below one |
| `alphaView` | `false` | Show the alpha channel instead of the lit material |
```json
{"id": 4, "method": "command.run", "params": {"id": "view.3d", "params": {"alphaView": true}}}
```
Headless renders (`materialcraft-cli render`, the `render` RPC) use the same settings.
## Implementation notes
- `crates/render/src/preview.rs`: `alpha()` picks the alpha source; `shade()` returns color, alpha
and hit distance; `trace()` composites the layers (`MAX_LAYERS = 8`, stops once less than 0.1%
of the light gets through); `Settings::{transparency, alpha_view}`.
- `crates/engine/src/wire_cmds.rs`: `graph.wire.insertDot`, `graph.wire.swap` (unplugs every
listed wire first, then reconnects, so a half-swapped state is never mistaken for a cycle) and
`graph.wire.delete`.
- `crates/ui-egui/src/graph_view.rs`: wire hit testing (`bezier_points`, `bezier_at`,
`bezier_distance`, `wire_at`), the `WirePress` gesture, the multi-wire selection
(`GraphView::selected_wires`), the wire menu, `delete_selected_wires` and
`swap_selected_wires`; `crates/ui-egui/src/menus.rs` gives Delete, Backspace and X to selected
wires before the node commands and shortcuts.
- `crates/ui-egui/src/view3d.rs`: the Display menu toggles and the bottom-bar button.
## Tests
- `preview::tests::alpha_shows_what_lies_behind_and_the_alpha_view_shows_the_channel`: a clear
sphere shows the backdrop, transparency off ignores alpha, the opacity output wins over the base
color alpha, the alpha view shows exact values.
- `a_wire_splits_with_a_reroute_dot_and_deletes` (engine): insertion, wiring, selection, cooking
through the dot, single-step undo, the error with no wire, deletion.
- `selected_wires_swap_their_sources_and_delete_together` (engine): two-wire swap in any order,
three-wire reverse, single-step undo, refused requests (one wire, duplicates, missing wires),
a refused cycle that leaves the graph unchanged, deleting several wires in one step.
- `graph_view::tests::clicked_wires_swap_with_x_and_delete_together`: real clicks on a Blend
node's two wires (the second with Shift), X swaps, X again swaps back, Delete removes both.
- `every_template_is_opaque_in_the_3d_view` (engine): no built-in template turns see-through.
- `graph_view::tests::wires_are_hit_near_their_curve_only`: wire hit testing.
- The `snapshots` UI test renders both screenshots on this page (`alpha-transparency`,
`alpha-channel`).
+1 -1
View File
@@ -21,7 +21,7 @@ workspace_version() {
' "$ROOT/Cargo.toml"
}
VERSION="${MATERIALCRAFT_VERSION:-$(workspace_version)}"
VERSION="${MATERIALCRAFT_VERSION:-${RELEASE_VERSION:-$(workspace_version)}}"
if [ -z "$VERSION" ]; then
echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2
exit 1