diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml
new file mode 100644
index 00000000..de64ad3e
--- /dev/null
+++ b/.github/workflows/house-rules.yml
@@ -0,0 +1,28 @@
+name: House rules
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - AGENTS.md
+ - CLAUDE.md
+ - .github/workflows/house-rules.yml
+ pull_request:
+ paths:
+ - AGENTS.md
+ - CLAUDE.md
+ - .github/workflows/house-rules.yml
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: house-rules-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ house-rules:
+ uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
+ with:
+ rust: true
diff --git a/AGENTS.md b/AGENTS.md
index 19ce8f5d..2d250fed 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,3 +1,56 @@
+
+## House rules
+
+These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
+
+1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
+2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
+3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
+4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
+5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
+6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
+7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
+8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
+9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
+10. **Keep secrets and personal details out** of the repository, logs and requests.
+11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
+12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
+13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
+14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
+15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
+
+
+## Rust Craft repositories
+
+These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
+
+1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
+2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
+3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
+4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
+5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
+6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
+
+## Licence allowlist
+
+Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
+
+- `ISC`
+- `MIT`
+- `BSD-2-Clause`
+- `BSD-3-Clause`
+- `Apache-2.0`
+- `OFL-1.1`
+- `Ubuntu-font-1.0`
+- `Bitstream-Vera`
+- `CC0-1.0`
+- `CC-BY-4.0`
+- `CC-BY-SA-4.0`
+- `LicenseRef-Public-Domain`
+
+`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
+
+
# AGENTS.md: guide for AI agents and contributors
MaterialCraft is an open-source, native **node-based procedural material designer**: a clean-room
@@ -11,13 +64,9 @@ 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 main project format is SBS (`.sbs`); the older native
-package extension `.mcraft` is still read and written.
+(`ai.storyteller.materialcraft`). The project format is SBS (`.sbs`). Legacy package compatibility is not required.
-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
-standards, and contribute reusable learnings back there. Shared code goes only in craft-libs
-(`standards/shared-libraries.md`); otherwise copy, don't depend. TextureCraft is the sibling this
+Shared code goes only in craft-libs; otherwise copy, don't depend. TextureCraft is the sibling this
repository's infrastructure (xtask, automation, packaging, docking, theme) was copied from.
The goal is full parity with the professional node-based material workflow (the same panels,
@@ -41,8 +90,8 @@ file first, then `docs/`.
```text
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); .sbs and .mcraft packages, bitmaps, texture export
+ nodes L1 the node library: native primitive definitions + CPU cooks, function evaluator and pattern graphs
+ eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); native .sbs 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)
@@ -98,7 +147,7 @@ and simplex gradient noise, Worley/cellular noise, fractal sums, Gaussian and bo
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 or presets.
-SBS packages are the main project format (issue #49): `crates/formats/src/sbs.rs` reads and writes
+SBS packages are the main project format (issue #49): `crates/formats/src/sbs/` 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.
@@ -107,7 +156,7 @@ implementation, in code, docs and commits.
People trust MaterialCraft with hours of work. A malformed package, a hostile command or MCP
parameter, an odd keystroke or a full disk must produce an error the user or agent can act on,
-never a panic. The shared standard is `../craftrules/standards/never-crash.md`.
+never a panic.
- Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or
`unimplemented!`. Every production crate root carries
@@ -184,6 +233,6 @@ after every arc of work that builds and passes.
- `ROADMAP.md`: milestones, parity estimate and remaining effort.
- `docs/target-app-parity.md` and `docs/gaps.md`: the assessment and the work list.
-- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing.
-- `plan/` (local, gitignored): execution plan and notes.
+- `docs/releasing.md`: release builds and signing.
+- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent.
- `log/` (local, gitignored): the dev log.
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 80e577f3..631c6cf0 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -31,7 +31,8 @@ images, materials, sample graphs, presets, environments) may ever be added.
| `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 |
+| `crates/nodes/src/atomic/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 |
+| `examples/atomic_sample.sbs` | Atomic sample graph | MaterialCraft contributors | Original graph built by `crates/engine/src/atomic_sample.rs` | MIT OR Apache-2.0 |
## Third-party assets compiled into the binary
@@ -44,10 +45,10 @@ These come from Rust crate dependencies (not files in this repository) and keep
## Procedural content (no asset files)
-The node library's noises and patterns (`crates/nodes`), the sample materials and graph templates
+The node library's primitives (`crates/nodes`), the sample materials and graph templates
(`crates/engine/src/samples.rs`), the 3D view's environments (`crates/render/src/ibl.rs`, procedural
HDR skies and soft boxes), the built-in meshes (`crates/geom/src/primitives.rs`), the library's node
-previews (`crates/ui-egui/src/thumbs.rs`, each node cooked on sample noise) and the New graph
+previews (`crates/ui-egui/src/thumbs.rs`, each node cooked on sample waves) and the New graph
dialog's template spheres (`crates/ui-egui/src/windows.rs`) are generated in code by MaterialCraft
contributors (MIT OR Apache-2.0). None of them is derived from another product's presets,
shaders, materials, sample graphs or images.
diff --git a/CLAUDE.md b/CLAUDE.md
index 911603ec..43c994c2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,5 +1 @@
-# MaterialCraft: instructions for Claude
-
-Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository
-(workspace map, golden rules including the asset and attribution rules, the definition of done).
-Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps.
+@AGENTS.md
diff --git a/Cargo.lock b/Cargo.lock
index 7c190929..c3134a01 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -214,6 +214,12 @@ dependencies = [
"x11rb",
]
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
[[package]]
name = "arrayvec"
version = "0.7.8"
@@ -875,6 +881,12 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "data-url"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
+
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
@@ -1327,6 +1339,12 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "float-cmp"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -2013,6 +2031,12 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "imagesize"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
+
[[package]]
name = "indexmap"
version = "2.14.2"
@@ -2307,21 +2331,23 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "materialcraft"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"eframe",
"egui",
"image",
"log",
+ "materialcraft-automation",
"materialcraft-engine",
"materialcraft-ui-egui",
+ "rfd",
"serde_json",
"winresource",
]
[[package]]
name = "materialcraft-automation"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -2332,6 +2358,7 @@ dependencies = [
"materialcraft-render",
"rayon",
"rmcp",
+ "rustix 1.1.6",
"schemars",
"serde",
"serde_json",
@@ -2341,7 +2368,7 @@ dependencies = [
[[package]]
name = "materialcraft-cli"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"materialcraft-automation",
"materialcraft-engine",
@@ -2352,7 +2379,7 @@ dependencies = [
[[package]]
name = "materialcraft-core"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"serde",
"serde_json",
@@ -2361,7 +2388,7 @@ dependencies = [
[[package]]
name = "materialcraft-engine"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"materialcraft-core",
"materialcraft-eval",
@@ -2376,7 +2403,7 @@ dependencies = [
[[package]]
name = "materialcraft-eval"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2386,7 +2413,7 @@ dependencies = [
[[package]]
name = "materialcraft-formats"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"base64 0.22.1",
"flate2",
@@ -2396,7 +2423,8 @@ dependencies = [
"materialcraft-geom",
"materialcraft-image",
"materialcraft-nodes",
- "roxmltree",
+ "resvg",
+ "roxmltree 0.20.0",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -2406,7 +2434,7 @@ dependencies = [
[[package]]
name = "materialcraft-geom"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -2417,7 +2445,7 @@ dependencies = [
[[package]]
name = "materialcraft-image"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"rayon",
"thiserror 2.0.21",
@@ -2425,7 +2453,7 @@ dependencies = [
[[package]]
name = "materialcraft-nodes"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2434,8 +2462,9 @@ dependencies = [
[[package]]
name = "materialcraft-render"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
+ "materialcraft-core",
"materialcraft-geom",
"materialcraft-image",
"rayon",
@@ -2443,7 +2472,7 @@ dependencies = [
[[package]]
name = "materialcraft-ui-egui"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"base64 0.22.1",
"craft-ui",
@@ -2459,6 +2488,7 @@ dependencies = [
"rfd",
"serde",
"serde_json",
+ "sys-locale",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -2467,7 +2497,7 @@ dependencies = [
[[package]]
name = "materialcraft-web"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"eframe",
"js-sys",
@@ -3164,6 +3194,12 @@ dependencies = [
"siphasher",
]
+[[package]]
+name = "pico-args"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
+
[[package]]
name = "pin-project"
version = "1.1.13"
@@ -3515,6 +3551,20 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+[[package]]
+name = "resvg"
+version = "0.47.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9be183ad6a216aa96f33e4c8033b0988b8b3ea6fd2359d19af5bac4643fd8e81"
+dependencies = [
+ "log",
+ "pico-args",
+ "rgb",
+ "svgtypes",
+ "tiny-skia",
+ "usvg",
+]
+
[[package]]
name = "rfd"
version = "0.17.2"
@@ -3542,6 +3592,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rgb"
+version = "0.8.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "rmcp"
version = "3.8.0"
@@ -3598,6 +3657,15 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+[[package]]
+name = "roxmltree"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3838,6 +3906,15 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+[[package]]
+name = "simplecss"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "siphasher"
version = "1.0.4"
@@ -3943,12 +4020,31 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+[[package]]
+name = "strict-num"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+dependencies = [
+ "float-cmp",
+]
+
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "svgtypes"
+version = "0.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"
+dependencies = [
+ "kurbo",
+ "siphasher",
+]
+
[[package]]
name = "syn"
version = "2.0.119"
@@ -4070,6 +4166,32 @@ dependencies = [
"zune-jpeg",
]
+[[package]]
+name = "tiny-skia"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "bytemuck",
+ "cfg-if",
+ "log",
+ "png",
+ "tiny-skia-path",
+]
+
+[[package]]
+name = "tiny-skia-path"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
+dependencies = [
+ "arrayref",
+ "bytemuck",
+ "strict-num",
+]
+
[[package]]
name = "tinystr"
version = "0.8.5"
@@ -4299,6 +4421,28 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
+[[package]]
+name = "usvg"
+version = "0.47.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d46cf96c5f498d36b7a9693bc6a7075c0bb9303189d61b2249b0dc3d309c07de"
+dependencies = [
+ "base64 0.22.1",
+ "data-url",
+ "flate2",
+ "imagesize",
+ "kurbo",
+ "log",
+ "pico-args",
+ "roxmltree 0.21.2",
+ "simplecss",
+ "siphasher",
+ "strict-num",
+ "svgtypes",
+ "tiny-skia-path",
+ "xmlwriter",
+]
+
[[package]]
name = "utf16_iter"
version = "1.1.0"
@@ -5242,9 +5386,15 @@ version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
+[[package]]
+name = "xmlwriter"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+
[[package]]
name = "xtask"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"serde_json",
]
diff --git a/Cargo.toml b/Cargo.toml
index 1bf7d2a7..03d0173d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -35,13 +35,14 @@ default-members = [
]
[workspace.package]
-version = "0.1.2"
+version = "0.1.3"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/materialcraft"
[workspace.dependencies]
+resvg = { version = "0.47", default-features = false }
# internal
materialcraft-core = { path = "crates/core" }
materialcraft-image = { path = "crates/image" }
@@ -68,6 +69,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 }
diff --git a/README.md b/README.md
index 6c2f537d..be0fae14 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@
- Build tileable PBR materials from noises, patterns and filters in a node graph, watch them
+ Build procedural materials from primitives and functions in a node graph, watch them
update live in 2D and on a 3D model, and export the maps for any engine. It runs natively on
macOS, Windows, Linux and FreeBSD, and in the browser via WebAssembly. Built by the ArtCraft team.
@@ -67,6 +67,9 @@
## A look around
+These screenshots show the earlier procedural library. The current build uses the primitive
+catalog described in [the primitive workflow](docs/atomic-workflow.md).
+
@@ -92,7 +95,8 @@
## Made in MaterialCraft
-Every material below is a node graph that ships with MaterialCraft as a template, built only from
+These historical renders used the former Rust library and are no longer bundled as templates.
+They were built from
its own procedural nodes (no photos, scans or textures from anywhere else) and rendered by
`materialcraft-cli render --scene sphere --full --hq` (the height output displaces the mesh, with
ray-traced ambient occlusion and a shadowed key light).
@@ -110,12 +114,12 @@ ray-traced ambient occlusion and a shadowed key light).
histogram of its input, see [docs/levels-editor.md](docs/levels-editor.md)). Space opens the
node search.
- **Fast.** Every node cooks on every CPU core, and a content-addressed cache means an edit
- re-cooks only what lies downstream: the brick wall sample cooks in about 40 ms at preview size.
+ re-cooks only what lies downstream.
Cooking runs on a worker thread, so the UI never waits.
- **Tileable by design.** Noises and patterns live on whole-number lattices, so everything tiles
seamlessly at any resolution, from 16 px to 8K.
- **Robust.** No panics in shipped code, every command tested with hostile input, every node cooked
- with odd inputs in tests, unlimited undo from snapshots, and lossless project files.
+ with odd inputs in tests, undo from snapshots, and native SBS project files.
- **Open.** Export base color, normal, roughness, metallic, height and ambient occlusion as PNG,
JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with your own file name pattern.
- **Works with TextureCraft.** **File ▸ Send to TextureCraft** puts a material on TextureCraft's
@@ -134,7 +138,7 @@ git clone https://github.com/storytold/materialcraft
cd materialcraft
cargo run --release -p materialcraft # desktop app
-cargo run --release -p materialcraft -- package.sbs # open a package (.sbs or .mcraft)
+cargo run --release -p materialcraft -- package.sbs # open an SBS package
cargo run --release -p materialcraft -- --control 7878 # + JSON control channel
cargo run --release -p materialcraft-cli -- mcp # MCP server (stdio)
cargo run --release -p materialcraft-cli -- new wood wood.sbs
@@ -170,21 +174,12 @@ The details are in [`docs/control-protocol.md`](docs/control-protocol.md).
MaterialCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the parity estimate by
area, the remaining work and what's next.
-**Where we are (2026-11-02):** the node engine and 227 nodes (the atomic nodes including FX-Map,
-SVG and Text, noises including tileable 3D ones, patterns, filters, the flood fill family,
-whole-material blending and weathering), function graphs with a visual editor and dynamic
-parameters, sub-graphs with exposed inputs and presets, the full editor (graph, library,
-properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes, alpha transparency and an
-alpha channel view; wires you can select, delete, swap (X) and reroute with dots, see
-[docs/wires-and-alpha.md](docs/wires-and-alpha.md)), SBS project files (`.mcraft` too),
-texture export, portable `.mcmat` materials that TextureCraft paints with (inputs stay editable
-there), the browser build with file I/O, the CLI, the control channel and the MCP server
-all work today. We estimate about two thirds (≈ 67%) of a material artist's daily workflow works
-end to end; [docs/target-app-parity.md](docs/target-app-parity.md) has the breakdown.
+**Current focus (2026-11-05):** primitive editing and native SBS save/load. The old Rust
+procedural library has been removed. The replacement includes 30 main-graph entries, 85 function
+operations and three pattern node kinds. Start with **File → New → Atomic sample**.
-**What's missing:** the rest of the node library, a GPU 3D view with tessellation and lights,
-mesh-based nodes, translations and the first signed release. The ranked list is in
-[`docs/gaps.md`](docs/gaps.md).
+See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scope and limitations.
+Reference-app rendering parity and full SBS library loading are still pending.
**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}`
and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own
diff --git a/ROADMAP.md b/ROADMAP.md
index 9a58e922..0e97d7b7 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,46 +1,20 @@
# MaterialCraft roadmap
-> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (≈ 67%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow
+**Current focus (2026-11-05):** native primitive editing, evaluation and SBS save/load.
-**Stage:** alpha (in active development). MaterialCraft aims for full parity with the professional
-node-based procedural material workflow, with better performance, every feature drivable by agents
-(MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web.
+The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native
+primitives and four graph input/output items. Functions have 85 operations; pattern graphs have
+Quadrant, Switch, Iterate and Dot. See [the primitive workflow](docs/atomic-workflow.md) for usage and limits.
-## Headline numbers
+Earlier percentage estimates and node counts are superseded by this change. Reference-app
+rendering parity and arbitrary SBS round trips have not been established.
-- **Parity: ≈ 67%** of a material artist's daily workflow works end to end
- ([docs/target-app-parity.md](docs/target-app-parity.md)).
-- **Remaining: ≈ 83 Opus 5.5 agent hours** ([docs/roadmap.md](docs/roadmap.md)).
-- **Nodes:** 227 (all tileable), cooked on every CPU core through a content-addressed cache; the
- brick wall sample cooks in about 40 ms at preview size.
+## Next steps
-## By area
-
-| Area | Weight | Done |
-|---|---:|---:|
-| Graph editing | 15 | 75% |
-| Atomic nodes | 12 | 95% |
-| Node library | 20 | 45% |
-| Function graphs | 10 | 70% |
-| Graph parameters and instances | 8 | 70% |
-| 2D view | 5 | 80% |
-| 3D view | 10 | 55% |
-| Files | 8 | 70% |
-| UI and UX | 8 | 70% |
-| Platforms | 4 | 50% |
-| **Total** | **100** | **≈ 67%** |
-
-## What's next
-
-1. The rest of the node library: scan processing, more grunges, spline tools, SDF shapes.
-2. A GPU 3D view with tessellation and lights.
-3. Mesh-based generators and bakers.
-4. Function loops and reusable functions.
-5. The first release on every platform.
-
-The ranked work list is [docs/gaps.md](docs/gaps.md); file formats are in
-[docs/file-format-parity.md](docs/file-format-parity.md) and languages in
-[docs/localization-parity.md](docs/localization-parity.md).
+1. Verify the original atomic sample in the reference application
+2. Compare primitive outputs and parameter semantics against reference results
+3. Add SBS graph references with cycle-safe resolution
+4. Build the library from SBS definitions instead of duplicate Rust nodes
## Progress log
diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs
index 57868c09..fa7a15ef 100644
--- a/apps/materialcraft-cli/src/main.rs
+++ b/apps/materialcraft-cli/src/main.rs
@@ -1,12 +1,11 @@
-//! Headless MaterialCraft command line: inspect, script, cook, export and render packages, and
-//! serve agents over MCP or JSON lines. Never opens a window.
+//! Headless MaterialCraft command line: inspect, script, cook, export and render packages, and serve agents over MCP or JSON lines. Never opens a window
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::sync::{Arc, Mutex};
use materialcraft_automation::security::{client_token, server_token};
-use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialcraftMcp, RenderOptions, rpc};
+use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialCraftMcp, RenderOptions, rpc};
use serde_json::{Value, json};
const USAGE: &str = "\
@@ -14,7 +13,7 @@ materialcraft-cli: headless MaterialCraft
USAGE:
materialcraft-cli --version
- materialcraft-cli info
+ materialcraft-cli info
Graphs, nodes, outputs and cook results, as JSON.
materialcraft-cli commands [--filter ]
List the engine commands (id, label, params).
@@ -25,27 +24,26 @@ USAGE:
materialcraft-cli batch
Run [{\"id\", \"params\"}, ...] or {\"open\": , \"steps\": [...], \"save\": }.
materialcraft-cli new [--size ] [--name ]
- A new package with one graph from a template (empty, pbr, bricks, stone_tiles, wood,
- metal_plates, rusty_metal, lava, marble, wicker, fabric, ground).
+ A new package with one graph from a template (empty, pbr, atomics).
materialcraft-cli cook [--graph ] [--set =]... [--full]
Cook a graph and print per-node timings and errors.
materialcraft-cli export [--graph ] [--set =]... [--format ]
- [--depth 8|16|32] [--pattern
]
+ [--depth 8|16|32] [--size ] [--pattern
]
Cook at full size and write every output (png, jpg, tga, tif, bmp, webp, exr, hdr).
materialcraft-cli render [--size x] [--view 3d|2d] [--scene ] [--node ]
[--yaw ] [--pitch ] [--graph ] [--set =]... [--full]
[--tiling ] [--hq [--displacement ]]
Render the material on a 3D scene (rounded_cube, cube, sphere, cylinder, plane, torus,
- material_ball), or one node's output (--view 2d), to PNG. No GPU needed. --hq is a beauty
- render: real displacement from the height output, ambient occlusion and a key light.
+ material_ball), or one node's output (--view 2d), to PNG. No GPU needed. The height output
+ raises the surface; --hq is a beauty render with a finer mesh, ambient occlusion and a key light.
materialcraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ]
MCP server on stdio: headless (file access only below the roots), or bridged to
- `materialcraft --control `.
+ `materialcraft --control `. --automation-read-root / --automation-write-root are
+ the same as --read-root / --write-root (mcp and serve).
materialcraft-cli serve [--port ] [--read-root ] [--write-root ]
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token.
- is an .sbs or .mcraft package or `sample` (the built-in brick wall). Packages save as SBS
-unless the output path ends in .mcraft. --set gives a graph input a value
+ is an .sbs package or `sample` (the built-in atomic sample). Packages save as native SBS. --set gives a graph input a value
(JSON, e.g. `--set roughness=0.4 --set tint=\"#aa7744\"`) before cooking. See docs/control-protocol.md.
";
@@ -58,12 +56,16 @@ 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"], &[]),
+ ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
+ ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
];
+/// (alias, flag): the `--automation-*-root` spelling the other crafting apps use, stored under the
+/// short name so the last root given wins whichever spelling it used.
+const ALIASES: &[(&str, &str)] = &[("--automation-read-root", "--read-root"), ("--automation-write-root", "--write-root")];
+
struct Args {
pos: Vec,
flags: Vec<(String, Option)>,
@@ -91,7 +93,8 @@ fn parse(cmd: &str, raw: &[String]) -> Result {
while let Some(x) = it.next() {
if valued.contains(&x.as_str()) {
let v = it.next().ok_or_else(|| format!("{x} needs a value"))?;
- a.flags.push((x.clone(), Some(v.clone())));
+ let name = ALIASES.iter().find(|(alias, _)| alias == x).map_or(x.as_str(), |(_, flag)| flag);
+ a.flags.push((name.to_string(), Some(v.clone())));
} else if bare.contains(&x.as_str()) {
a.flags.push((x.clone(), None));
} else if x.starts_with('-') && x.len() > 1 && x.parse::().is_err() {
@@ -114,7 +117,7 @@ fn version() -> String {
}
}
-/// A headless session on `input` (an .sbs or .mcraft package, or `sample`), with local file access.
+/// A headless session on `input` (an .sbs package, or `sample`), with local file access
fn open(input: &str) -> Result {
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
if input != "sample" {
@@ -127,7 +130,7 @@ fn print(v: &Value) {
println!("{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}")));
}
-/// Open `--graph` and apply every `--set =` (the value is JSON, else a string).
+/// Open `--graph` and apply every `--set =` (the value is JSON, else a string)
fn select_graph(h: &mut Headless, a: &Args) -> Result<(), String> {
if let Some(g) = a.num::("--graph")? {
h.command_run("graph.open", json!({"graph": g})).map_err(|e| e.to_string())?;
@@ -183,6 +186,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
Some(p) => serde_json::from_str(p).map_err(|e| format!("params: {e}"))?,
None => Value::Null,
};
+
print(&h.command_run(id, params).map_err(|e| e.to_string())?);
if let Some(out) = a.get("-o") {
h.save(Some(out)).map_err(|e| e.to_string())?;
@@ -199,6 +203,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
obj.get("save").and_then(Value::as_str),
),
};
+
let mut h = open(input)?;
let r = h.batch(&steps);
print(&r);
@@ -228,7 +233,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let mut h = open(a.pos(0, "")?)?;
select_graph(&mut h, a)?;
let dir = a.pos(1, "")?;
- let p = json!({"dir": dir, "graph": a.num::("--graph")?, "format": a.get("--format"), "depth": a.num::("--depth")?, "pattern": a.get("--pattern")});
+ let p = json!({"dir": dir, "graph": a.num::("--graph")?, "format": a.get("--format"), "depth": a.num::("--depth")?, "size": a.num::("--size")?, "pattern": a.get("--pattern")});
print(&h.export(&p).map_err(|e| e.to_string())?);
}
"render" => {
@@ -242,6 +247,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
}
None => (None, None),
};
+
let o = RenderOptions {
view: a.get("--view").map(str::to_string),
width: w,
@@ -256,6 +262,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
hq: a.has("--hq"),
displacement: a.num("--displacement")?,
};
+
let r = h.render_png(&o).map_err(|e| e.to_string())?;
materialcraft_engine::formats::write_atomic(std::path::Path::new(out), &r.png).map_err(|e| e.to_string())?;
print(&json!({"path": out, "width": r.width, "height": r.height}));
@@ -265,24 +272,26 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let server = match a.num::("--bridge")? {
Some(port) => {
let token = client_token(port, a.get("--token").map(str::to_string)).map_err(|e| e.to_string())?;
- MaterialcraftMcp::bridge(BridgeClient::new(port, token))
+ MaterialCraftMcp::bridge(BridgeClient::new(port, token))
}
- None => MaterialcraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)),
+ None => MaterialCraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)),
};
+
rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())?;
}
"serve" => {
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?)));
match a.num::("--port")? {
Some(port) => {
- 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())?,
}
@@ -292,7 +301,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
Ok(())
}
-/// File access for servers: none without roots, else only below them.
+/// File access for servers: none without roots, else only below them
fn workspace(a: &Args) -> Result {
let (r, w) = (a.get("--read-root"), a.get("--write-root"));
if r.is_none() && w.is_none() {
@@ -301,3 +310,36 @@ fn workspace(a: &Args) -> Result {
let ws = AuthorizedWorkspace::new(r.map(std::path::Path::new), w.map(std::path::Path::new)).map_err(|e| e.to_string())?;
Ok(Filesystem::Workspace(ws))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn strings(v: &[&str]) -> Vec {
+ v.iter().map(|s| s.to_string()).collect()
+ }
+
+ #[test]
+ fn automation_root_flags_are_aliases_of_the_short_ones() {
+ for cmd in ["mcp", "serve"] {
+ let a = parse(cmd, &strings(&["--automation-read-root", "/r", "--automation-write-root", "/w"])).unwrap();
+ assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}");
+ let a = parse(cmd, &strings(&["--read-root", "/r", "--write-root", "/w"])).unwrap();
+ assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}");
+ }
+ }
+
+ #[test]
+ fn the_last_root_flag_wins_whatever_its_spelling() {
+ let a = parse("mcp", &strings(&["--read-root", "/a", "--automation-read-root", "/b"])).unwrap();
+ assert_eq!(a.get("--read-root"), Some("/b"));
+ let a = parse("mcp", &strings(&["--automation-write-root", "/a", "--write-root", "/b"])).unwrap();
+ assert_eq!(a.get("--write-root"), Some("/b"));
+ }
+
+ #[test]
+ fn automation_root_flags_need_a_value_and_stay_unknown_elsewhere() {
+ assert!(parse("mcp", &strings(&["--automation-read-root"])).is_err());
+ assert!(parse("cook", &strings(&["--automation-read-root", "/r"])).is_err());
+ }
+}
diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml
index 64a1ca49..83f388f9 100644
--- a/apps/materialcraft/Cargo.toml
+++ b/apps/materialcraft/Cargo.toml
@@ -12,12 +12,15 @@ 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 }
image = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
+# A start that never opens a window says why in an error dialog (src/start_failure.rs).
+rfd = { workspace = true }
[build-dependencies]
winresource = "0.1"
diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs
index a094e2dc..7e1c94f2 100644
--- a/apps/materialcraft/src/control_server.rs
+++ b/apps/materialcraft/src/control_server.rs
@@ -1,80 +1,125 @@
//! Loopback JSON-lines control server (`--control `): 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 `/materialcraft-control-.token`.
+//! or, when that is unset, the token written (owner-only) to
+//! `/materialcraft-control-.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;
+#[cfg(test)]
+#[path = "control_server.test.rs"]
+mod exact_token_tests;
-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
+fn auth_ok(token: &str, method: &str, params: &Value) -> bool {
+ method == "auth" && params.get("token").and_then(Value::as_str).is_some_and(|t| token_matches(token, t))
}
+/// 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 {
- let (tx, rx) = channel::();
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 {
+ let (tx, rx) = channel::();
+ 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, 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, 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, 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) => return,
+ Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
+ let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": "request is not UTF-8"}));
+ if !sent || deadline.is_some() {
+ return;
+ }
+ continue;
+ }
+ Err(_) => return,
}
if line.trim().is_empty() {
continue;
@@ -82,33 +127,156 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, 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() {
+ if !auth_ok(token, &method, ¶ms) {
+ // 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::();
+ 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) {
+ 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, line: &str) -> Option {
+ 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 non_utf8_line_before_auth_gets_refusal_reply() {
+ let addr = server();
+ let (mut w, mut r) = connect(addr);
+ w.write_all(b"\xff\n").unwrap();
+ w.flush().unwrap();
+ let mut reply = String::new();
+ let n = r.read_line(&mut reply).unwrap();
+ assert!(n > 0, "a non-UTF8 first line gets a refusal reply, not a silent close");
+ assert_eq!(serde_json::from_str::(&reply).unwrap()["ok"], false);
+ }
+
+ #[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::(&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");
+ }
+}
diff --git a/apps/materialcraft/src/control_server.test.rs b/apps/materialcraft/src/control_server.test.rs
new file mode 100644
index 00000000..50b02a30
--- /dev/null
+++ b/apps/materialcraft/src/control_server.test.rs
@@ -0,0 +1,16 @@
+#[cfg(test)]
+mod auth_tests {
+ use crate::control_server::auth_ok;
+ use serde_json::json;
+
+ #[test]
+ fn only_the_exact_token_on_an_auth_request_passes() {
+ let token = "0123456789abcdef0123456789abcdef";
+ assert!(auth_ok(token, "auth", &json!({"token": token})));
+ assert!(!auth_ok(token, "auth", &json!({"token": "0123456789abcdef0123456789abcdee"})));
+ assert!(!auth_ok(token, "auth", &json!({"token": "short"})));
+ assert!(!auth_ok(token, "auth", &json!({})));
+ assert!(!auth_ok(token, "auth", &json!({"token": 5})));
+ assert!(!auth_ok(token, "command.run", &json!({"token": token})));
+ }
+}
diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs
index 4e9b18bf..f5e691fa 100644
--- a/apps/materialcraft/src/main.rs
+++ b/apps/materialcraft/src/main.rs
@@ -1,11 +1,11 @@
-//! MaterialCraft desktop app.
-//!
-//! Usage: `materialcraft [package.sbs|package.mcraft] [--control ] [--empty] [--version]`
+//! MaterialCraft desktop app
+//! Usage: `materialcraft [package.sbs] [--control ] [--empty] [--version]`
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod control_server;
+mod start_failure;
use materialcraft_engine::Session;
use materialcraft_ui_egui::MaterialCraftApp;
@@ -38,14 +38,14 @@ fn parse_args() -> Result