mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-30 18:13:53 +01:00
Merge main into release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
27fa868074
475 files changed
+26989
-16395
No files matched your search
@@ -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
|
||||
@@ -1,3 +1,56 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## 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.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## 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.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# 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.
|
||||
+4
-3
@@ -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.
|
||||
@@ -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
|
||||
Generated
+165
-15
@@ -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",
|
||||
]
|
||||
|
||||
+3
-1
@@ -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 }
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
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.
|
||||
</p>
|
||||
@@ -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).
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
@@ -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
|
||||
|
||||
+11
-37
@@ -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
|
||||
|
||||
|
||||
@@ -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 <package.sbs | package.mcraft | sample>
|
||||
materialcraft-cli info <package.sbs | sample>
|
||||
Graphs, nodes, outputs and cook results, as JSON.
|
||||
materialcraft-cli commands [--filter <text>]
|
||||
List the engine commands (id, label, params).
|
||||
@@ -25,27 +24,26 @@ USAGE:
|
||||
materialcraft-cli batch <script.json>
|
||||
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).
|
||||
A new package with one graph from a template (empty, pbr, atomics).
|
||||
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]
|
||||
[--tiling <n>] [--hq [--displacement <radii>]]
|
||||
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 <port>] [--token <token>] [--read-root <dir>] [--write-root <dir>]
|
||||
MCP server on stdio: headless (file access only below the roots), or bridged to
|
||||
`materialcraft --control <port>`.
|
||||
`materialcraft --control <port>`. --automation-read-root / --automation-write-root are
|
||||
the same as --read-root / --write-root (mcp and serve).
|
||||
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 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
|
||||
<input> 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<String>,
|
||||
flags: Vec<(String, Option<String>)>,
|
||||
@@ -91,7 +93,8 @@ fn parse(cmd: &str, raw: &[String]) -> Result<Args, String> {
|
||||
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::<f64>().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<Headless, String> {
|
||||
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 <input>=<value>` (the value is JSON, else a string).
|
||||
/// Open `--graph` and apply every `--set <input>=<value>` (the value is JSON, else a string)
|
||||
fn select_graph(h: &mut Headless, a: &Args) -> Result<(), String> {
|
||||
if let Some(g) = a.num::<u64>("--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, "<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" => {
|
||||
@@ -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::<u16>("--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::<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())?,
|
||||
}
|
||||
@@ -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<Filesystem, String> {
|
||||
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<Filesystem, String> {
|
||||
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<String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -1,80 +1,125 @@
|
||||
//! 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;
|
||||
#[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<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) => 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<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() {
|
||||
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::<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 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::<Value>(&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::<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");
|
||||
}
|
||||
}
|
||||
@@ -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})));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
//! MaterialCraft desktop app.
|
||||
//!
|
||||
//! Usage: `materialcraft [package.sbs|package.mcraft] [--control <port>] [--empty] [--version]`
|
||||
//! MaterialCraft desktop app
|
||||
//! Usage: `materialcraft [package.sbs] [--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)]
|
||||
|
||||
mod control_server;
|
||||
mod start_failure;
|
||||
|
||||
use materialcraft_engine::Session;
|
||||
use materialcraft_ui_egui::MaterialCraftApp;
|
||||
@@ -38,14 +38,14 @@ fn parse_args() -> Result<Option<Args>, String> {
|
||||
return Ok(None);
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("{}\n\nUsage: materialcraft [package.sbs|package.mcraft] [--control <port>] [--empty]", version());
|
||||
println!("{}\n\nUsage: materialcraft [package.sbs] [--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}`"))?);
|
||||
}
|
||||
// Kept for scripts written before empty startup became the default.
|
||||
// Kept for scripts written before empty startup became the default
|
||||
"--empty" => {}
|
||||
f if !f.starts_with('-') => args.file = Some(f.to_string()),
|
||||
other => return Err(format!("unknown option `{other}`")),
|
||||
@@ -80,6 +80,7 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
|
||||
let prev = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
eprintln!("materialcraft: internal error: {info}");
|
||||
@@ -90,8 +91,7 @@ fn main() {
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
// Scripted runs (agents, tests) set MATERIALCRAFT_NO_PREFS so they neither read nor overwrite
|
||||
// the user's saved layout and settings: state goes to a throwaway file.
|
||||
// Scripted runs (agents, tests) set MATERIALCRAFT_NO_PREFS so they neither read nor overwrite the user's saved layout and settings: state goes to a throwaway file
|
||||
let persistence_path =
|
||||
std::env::var_os("MATERIALCRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("materialcraft-noprefs-{}.ron", std::process::id())));
|
||||
let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
|
||||
@@ -109,6 +109,8 @@ fn main() {
|
||||
);
|
||||
if let Err(e) = r {
|
||||
eprintln!("materialcraft: {e}");
|
||||
// Say why instead of exiting silently (`start_failure`).
|
||||
start_failure::report(&e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -133,11 +135,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn startup_opens_the_requested_package() {
|
||||
let path = std::env::temp_dir().join(format!("mc-startup-{}.mcraft", std::process::id()));
|
||||
let path = std::env::temp_dir().join(format!("mc-startup-{}.sbs", std::process::id()));
|
||||
let original = materialcraft_engine::sample_session();
|
||||
std::fs::write(&path, materialcraft_engine::file_cmds::save_bytes(&original).unwrap()).unwrap();
|
||||
let s = initial_session(&Args { file: Some(path.to_string_lossy().into_owned()), control: None });
|
||||
assert_eq!(s.pkg.graphs, original.pkg.graphs);
|
||||
assert_eq!(s.pkg.graphs.len(), original.pkg.graphs.len());
|
||||
assert_eq!(s.pkg.graphs[0].name, original.pkg.graphs[0].name);
|
||||
assert_eq!(materialcraft_engine::file_cmds::save_bytes(&s).unwrap(), materialcraft_engine::file_cmds::save_bytes(&original).unwrap());
|
||||
assert_eq!(s.path.as_deref(), path.to_str());
|
||||
assert!(!s.modified);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! A window that can't start, or stops, says why instead of the app quitting silently.
|
||||
//!
|
||||
//! Without a usable GPU, graphics driver or desktop (a broken or very old driver, a remote or
|
||||
//! virtual machine, a program started by a service or a test harness), the window's surface
|
||||
//! can't be configured and eframe returns an error. MaterialCraft used to log it and exit with no
|
||||
//! window, which looks like "the app doesn't open".
|
||||
//! winget-pkgs validation starts installed programs without a desktop, so a version that fails
|
||||
//! like this never reaches WinGet.
|
||||
//!
|
||||
//! Now the reason also goes to an error dialog, as FilmCraft does since 0.14.0. The dialog keeps
|
||||
//! the process alive until it is dismissed; the exit code afterwards is still the error's.
|
||||
|
||||
/// What the dialog and the log say. Any error `run_native` returns lands here. One from the app's
|
||||
/// own start-up (`AppCreation`, e.g. a `--control` file it can't write) says only that it couldn't
|
||||
/// start. Any other comes from the window or graphics, possibly after the window was up, so
|
||||
/// graphics is named as the likely cause, not the certain one.
|
||||
pub(crate) fn message(error: &eframe::Error) -> String {
|
||||
match error {
|
||||
eframe::Error::AppCreation(_) => format!("MaterialCraft could not start: {error}"),
|
||||
_ => format!(
|
||||
"MaterialCraft's window could not start or stopped with an error: {error}\n\nIf this keeps happening, updating the graphics driver often fixes it."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs the failure and shows it in a dialog, which stays until the user closes it.
|
||||
pub(crate) fn report(error: &eframe::Error) {
|
||||
let message = message(error);
|
||||
log::error!("{message}");
|
||||
let _ = rfd::MessageDialog::new().set_title("MaterialCraft").set_description(&message).set_level(rfd::MessageLevel::Error).show();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_window_or_graphics_error_names_the_driver_as_the_likely_fix() {
|
||||
let text = message(&eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable));
|
||||
assert!(text.starts_with("MaterialCraft's window could not start or stopped"), "{text}");
|
||||
assert!(text.contains("no valid format for the surface"), "{text}");
|
||||
assert!(text.contains("graphics driver"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_start_up_error_does_not_blame_the_graphics() {
|
||||
let text = message(&eframe::Error::AppCreation("can't write the control file".into()));
|
||||
assert!(text.starts_with("MaterialCraft could not start"), "{text}");
|
||||
assert!(text.contains("can't write the control file"), "{text}");
|
||||
assert!(!text.contains("graphics"), "{text}");
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -0,0 +1,19 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AutomationError {
|
||||
#[error("{0}")]
|
||||
BadRequest(String),
|
||||
#[error("I/O: {0}")]
|
||||
Io(String),
|
||||
#[error(transparent)]
|
||||
Engine(#[from] materialcraft_engine::EngineError),
|
||||
#[error("bridge: {0}")]
|
||||
Bridge(String),
|
||||
#[error("app: {0}")]
|
||||
App(String),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub(crate) fn bad(msg: impl Into<String>) -> AutomationError {
|
||||
AutomationError::BadRequest(msg.into())
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use crate::AuthorizedWorkspace;
|
||||
/// Where file paths given to [`crate::Headless`] may point
|
||||
pub enum Filesystem {
|
||||
/// No file access (an MCP server started without roots)
|
||||
Denied,
|
||||
/// Host paths as given: the local CLI user typed them
|
||||
TrustedLocal,
|
||||
/// Relative paths under the authorized roots (remote or agent callers)
|
||||
Workspace(AuthorizedWorkspace),
|
||||
}
|
||||
@@ -1,60 +1,17 @@
|
||||
//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and
|
||||
//! UI-free; the MCP server, the RPC server and the CLI all drive it.
|
||||
//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and UI-free; the MCP server, the RPC server and the CLI all drive it
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use materialcraft_engine::core::NodeId;
|
||||
use materialcraft_engine::{Session, commands, file_cmds, inspect};
|
||||
use materialcraft_render::{Lighting, Maps, Scene, Settings};
|
||||
use materialcraft_engine::formats::material::MATERIAL_EXT;
|
||||
use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds};
|
||||
use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png};
|
||||
use crate::workspace::{MAX_READ_BYTES, authorize_command};
|
||||
use crate::{AuthorizedWorkspace, AutomationError, bad};
|
||||
|
||||
/// Where file paths given to [`Headless`] may point.
|
||||
pub enum Filesystem {
|
||||
/// No file access (an MCP server started without roots).
|
||||
Denied,
|
||||
/// Host paths as given: the local CLI user typed them.
|
||||
TrustedLocal,
|
||||
/// Relative paths under the authorized roots (remote or agent callers).
|
||||
Workspace(AuthorizedWorkspace),
|
||||
}
|
||||
|
||||
/// What [`Headless::render_png`] draws.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RenderOptions {
|
||||
/// `3d` (default) or `2d` (a node's output; the 2D view's node by default).
|
||||
pub view: Option<String>,
|
||||
pub width: Option<u32>,
|
||||
pub height: Option<u32>,
|
||||
/// Camera overrides in degrees (the session's view is not changed).
|
||||
pub yaw: Option<f32>,
|
||||
pub pitch: Option<f32>,
|
||||
/// 3D scene override (`rounded_cube`, `sphere`, …).
|
||||
pub scene: Option<String>,
|
||||
/// 2D: the node whose output to show.
|
||||
pub node: Option<u64>,
|
||||
/// 2D: the output port.
|
||||
pub port: Option<usize>,
|
||||
/// Cook at full size instead of the preview size.
|
||||
pub full: bool,
|
||||
/// 3D: UV repeats override (the session's view is not changed).
|
||||
pub tiling: Option<f32>,
|
||||
/// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced
|
||||
/// ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills.
|
||||
pub hq: bool,
|
||||
/// 3D, with `hq`: displacement depth in scene radii (default 0.04).
|
||||
pub displacement: Option<f32>,
|
||||
}
|
||||
|
||||
/// A PNG render.
|
||||
pub struct Rendered {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub png: Vec<u8>,
|
||||
}
|
||||
use crate::{AutomationError, bad};
|
||||
pub use crate::{Filesystem, RenderOptions, Rendered};
|
||||
|
||||
pub struct Headless {
|
||||
pub session: Session,
|
||||
@@ -63,7 +20,7 @@ pub struct Headless {
|
||||
light: Option<Lighting>,
|
||||
}
|
||||
|
||||
/// Read a file under `fs`'s access rules.
|
||||
/// 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>")),
|
||||
@@ -83,7 +40,7 @@ impl Headless {
|
||||
Headless { session, fs, scene: None, light: None }
|
||||
}
|
||||
|
||||
/// The session a fresh server starts with: the brick wall sample.
|
||||
/// The session a fresh server starts with: the atomic sample
|
||||
pub fn default_session() -> Session {
|
||||
materialcraft_engine::sample_session()
|
||||
}
|
||||
@@ -122,15 +79,15 @@ impl Headless {
|
||||
commands::list(&self.session, filter)
|
||||
}
|
||||
|
||||
/// Run an engine command. Untrusted callers can't reach host paths through it.
|
||||
/// Run an engine command. Untrusted callers can't reach host paths through it
|
||||
pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError> {
|
||||
if !self.trusted() {
|
||||
authorize_command(id, ¶ms)?;
|
||||
}
|
||||
Ok(materialcraft_engine::execute(&mut self.session, id, ¶ms)?)
|
||||
Ok(materialcraft_engine::commands::execute_request(&mut self.session, id, ¶ms)?)
|
||||
}
|
||||
|
||||
/// Run `[{id, params?}]` in order, stopping at the first error (reported with its index).
|
||||
/// Run `[{id, params?}]` in order, stopping at the first error (reported with its index)
|
||||
pub fn batch(&mut self, steps: &[Value]) -> Value {
|
||||
let mut results = Vec::new();
|
||||
for (i, step) in steps.iter().enumerate() {
|
||||
@@ -143,7 +100,7 @@ impl Headless {
|
||||
batch_reply(results, None)
|
||||
}
|
||||
|
||||
/// Open an `.sbs` or `.mcraft` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules.
|
||||
/// Open an `.sbs` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules
|
||||
pub fn open(&mut self, path: &str) -> Result<Value, AutomationError> {
|
||||
let bytes = self.read(path)?;
|
||||
let folder = path.replace('\\', "/").rsplit_once('/').map(|(folder, _)| format!("{folder}/")).unwrap_or_default();
|
||||
@@ -162,21 +119,21 @@ impl Headless {
|
||||
Ok(self.inspect())
|
||||
}
|
||||
|
||||
/// Save to `path` (`.sbs` appended without a package extension) or the package's own file; SBS unless it is a `.mcraft`.
|
||||
/// Save to `path` (`.sbs` appended without a package extension) or the package's own file; native SBS
|
||||
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError> {
|
||||
let path = match path {
|
||||
Some(p) => file_cmds::package_path(p),
|
||||
None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet (new, or opened from another program): give a `path`"))?,
|
||||
};
|
||||
|
||||
let bytes = file_cmds::save_bytes_as(&self.session, file_cmds::PackageFormat::of_path(&path))?;
|
||||
let bytes = file_cmds::save_bytes(&self.session)?;
|
||||
self.write(&path, &bytes)?;
|
||||
self.session.path = Some(path.clone());
|
||||
self.session.modified = false;
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
/// Embed an image file as a bitmap resource.
|
||||
/// Embed an image file as a bitmap resource
|
||||
pub fn import_bitmap(&mut self, path: &str, name: Option<&str>) -> Result<Value, AutomationError> {
|
||||
let bytes = self.read(path)?;
|
||||
let file = Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string();
|
||||
@@ -184,11 +141,11 @@ impl Headless {
|
||||
Ok(json!({"name": name}))
|
||||
}
|
||||
|
||||
/// Export every output of a graph into folder `dir`.
|
||||
/// Export every output of a graph into folder `dir`
|
||||
pub fn export(&mut self, p: &Value) -> Result<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 {
|
||||
@@ -199,7 +156,25 @@ impl Headless {
|
||||
Ok(json!({"files": written}))
|
||||
}
|
||||
|
||||
/// Render the 3D view or a node's 2D output as PNG.
|
||||
/// Export a portable material below the granted write root
|
||||
pub fn export_material(&mut self, p: &Value) -> Result<Value, AutomationError> {
|
||||
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?;
|
||||
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
|
||||
match &self.fs {
|
||||
Filesystem::Denied => return Err(bad("file access is not granted: start the server with --write-root <dir>")),
|
||||
Filesystem::Workspace(w) => w.check_write(&path)?,
|
||||
Filesystem::TrustedLocal => {}
|
||||
}
|
||||
let (gi, options) = material_cmds::material_request(&self.session, "material.export", p)?;
|
||||
let bytes = material_cmds::material_bytes(&self.session, gi, &options)?;
|
||||
if bytes.len() as u64 > MAX_READ_BYTES {
|
||||
return Err(bad(format!("the material is {} bytes (limit {MAX_READ_BYTES}); export a smaller `size`", bytes.len())));
|
||||
}
|
||||
self.write(&path, &bytes)?;
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
/// Render the assigned material or a node output as PNG
|
||||
pub fn render_png(&mut self, o: &RenderOptions) -> Result<Rendered, AutomationError> {
|
||||
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
|
||||
let saved = self.session.preview_size;
|
||||
@@ -213,6 +188,7 @@ impl Headless {
|
||||
"3d" => Ok(self.render_3d(o, max)),
|
||||
other => Err(bad(format!("unknown view `{other}` (3d or 2d)"))),
|
||||
};
|
||||
|
||||
if o.full {
|
||||
self.session.preview_size = saved;
|
||||
self.session.dirty = true;
|
||||
@@ -228,6 +204,7 @@ impl Headless {
|
||||
Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
|
||||
None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?,
|
||||
};
|
||||
|
||||
let (w, h) = (o.width.unwrap_or(img.w).clamp(16, max), o.height.unwrap_or(img.h).clamp(16, max));
|
||||
let img = img.resize(w, h, true);
|
||||
Ok((w, h, img.to_rgba8_display()))
|
||||
@@ -243,12 +220,15 @@ impl Headless {
|
||||
Some((_, mesh)) => Scene::new((*mesh).clone()),
|
||||
None => Scene::builtin(&scene_id),
|
||||
};
|
||||
|
||||
self.scene = Some((key, scene));
|
||||
}
|
||||
if self.light.as_ref().is_none_or(|l| l.name != v.environment) {
|
||||
self.light = Some(Lighting::new(&v.environment));
|
||||
}
|
||||
let tiling = o.tiling.unwrap_or(v.tiling).clamp(0.1, 64.0);
|
||||
let depth = if o.hq { o.displacement.unwrap_or(v.height_scale) } else { v.height_scale };
|
||||
let relief = Relief { depth: depth.clamp(0.0, 0.5), level: v.height_level };
|
||||
let mut settings = Settings {
|
||||
yaw: o.yaw.unwrap_or(v.yaw),
|
||||
pitch: o.pitch.unwrap_or(v.pitch),
|
||||
@@ -257,23 +237,18 @@ impl Headless {
|
||||
tiling,
|
||||
exposure: v.exposure,
|
||||
env_rotation: v.env_rotation,
|
||||
height_scale: v.height_scale,
|
||||
normal_y_flip: v.normal_y_flip,
|
||||
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));
|
||||
let maps = Maps::from_usages(self.session.material_maps());
|
||||
let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) };
|
||||
let displaced = match (o.hq, &maps.height) {
|
||||
(true, Some(height)) => {
|
||||
settings.height_scale = 0.0;
|
||||
Some(Scene::displaced(&scene.mesh, height, tiling, o.displacement.unwrap_or(0.04).clamp(0.0, 0.5) * scene.radius, HQ_TRIANGLES))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let displaced = scene.with_relief(&maps, relief, tiling, if o.hq { HQ_TRIANGLES } else { VIEW_TRIANGLES });
|
||||
if o.hq {
|
||||
settings.supersample = 3;
|
||||
settings.ao_rays = 8;
|
||||
@@ -290,3 +265,7 @@ pub fn batch_reply(results: Vec<Value>, failed: Option<(usize, &str, String)>) -
|
||||
"failed": failed.map(|(index, id, error)| json!({ "index": index, "id": id, "error": error })),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "headless.test.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,16 @@
|
||||
#[cfg(test)]
|
||||
mod end_merge_tests {
|
||||
use crate::headless::{Filesystem, Headless};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn two_param_requests_are_two_undo_steps() {
|
||||
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
|
||||
h.command_run("file.new", json!({"template": "empty"})).unwrap();
|
||||
let id = h.command_run("graph.node.add", json!({"def": "levels"})).unwrap()["id"].as_u64().unwrap();
|
||||
let sets = |h: &Headless| h.session.history().iter().filter(|l| *l == "Set parameter").count();
|
||||
h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": [0.3, 0.3, 0.3, 0.3]})).unwrap();
|
||||
h.command_run("graph.node.param", json!({"id": id, "param": "in_low", "value": [0.4, 0.4, 0.4, 0.4]})).unwrap();
|
||||
assert_eq!(sets(&h), 2, "separate requests must not merge");
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,3 @@
|
||||
//! # materialcraft-automation
|
||||
//!
|
||||
//! Agent-facing automation, L4 (no UI toolkit):
|
||||
//!
|
||||
//! * [`MaterialcraftMcp`]: an MCP server (official `rmcp` SDK). Headless mode drives an
|
||||
//! in-process [`Headless`] session; bridge mode forwards to a running desktop app over the
|
||||
//! JSON-lines control channel (`docs/control-protocol.md`).
|
||||
//! * [`Headless`]: a [`materialcraft_engine::Session`] plus file I/O through an
|
||||
//! [`AuthorizedWorkspace`] and windowless renders. Shared by the MCP server, the RPC server
|
||||
//! and `materialcraft-cli`.
|
||||
//! * [`rpc`]: the control channel's methods (plus `render`) over stdio or loopback TCP, used by
|
||||
//! `materialcraft-cli serve`.
|
||||
//! * [`BridgeClient`]: the client side of the app's control channel.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -23,26 +10,16 @@ pub mod server;
|
||||
pub mod workspace;
|
||||
|
||||
pub use bridge::BridgeClient;
|
||||
pub use headless::{Filesystem, Headless, RenderOptions};
|
||||
pub use server::{Backend, MaterialcraftMcp};
|
||||
mod filesystem;
|
||||
mod render_options;
|
||||
mod rendered;
|
||||
pub use filesystem::Filesystem;
|
||||
pub use headless::Headless;
|
||||
pub use render_options::RenderOptions;
|
||||
pub use rendered::Rendered;
|
||||
pub use server::{Backend, MaterialCraftMcp};
|
||||
pub use workspace::AuthorizedWorkspace;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AutomationError {
|
||||
#[error("{0}")]
|
||||
BadRequest(String),
|
||||
#[error("I/O: {0}")]
|
||||
Io(String),
|
||||
#[error(transparent)]
|
||||
Engine(#[from] materialcraft_engine::EngineError),
|
||||
#[error("bridge: {0}")]
|
||||
Bridge(String),
|
||||
#[error("app: {0}")]
|
||||
App(String),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub(crate) fn bad(msg: impl Into<String>) -> AutomationError {
|
||||
AutomationError::BadRequest(msg.into())
|
||||
}
|
||||
mod automation_error;
|
||||
pub use automation_error::AutomationError;
|
||||
pub(crate) use automation_error::bad;
|
||||
@@ -0,0 +1,25 @@
|
||||
/// What [`crate::Headless::render_png`] draws
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RenderOptions {
|
||||
/// `3d` (default) or `2d` (a node's output; the 2D view's node by default)
|
||||
pub view: Option<String>,
|
||||
pub width: Option<u32>,
|
||||
pub height: Option<u32>,
|
||||
/// Camera overrides in degrees (the session's view is not changed)
|
||||
pub yaw: Option<f32>,
|
||||
pub pitch: Option<f32>,
|
||||
/// 3D scene override (`rounded_cube`, `sphere`, …)
|
||||
pub scene: Option<String>,
|
||||
/// 2D: the node whose output to show
|
||||
pub node: Option<u64>,
|
||||
/// 2D: the output port
|
||||
pub port: Option<usize>,
|
||||
/// Cook at full size instead of the preview size
|
||||
pub full: bool,
|
||||
/// 3D: UV repeats override (the session's view is not changed)
|
||||
pub tiling: Option<f32>,
|
||||
/// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills
|
||||
pub hq: bool,
|
||||
/// 3D, with `hq`: displacement depth in scene radii (default 0.04)
|
||||
pub displacement: Option<f32>,
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/// A PNG render
|
||||
pub struct Rendered {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub png: Vec<u8>,
|
||||
}
|
||||
+123
-29
@@ -1,14 +1,3 @@
|
||||
//! Headless JSON-lines server with the app's control-channel envelope:
|
||||
//! `{"id","method","params"}` → `{"id","ok":true,"result"}` | `{"id","ok":false,"error"}`.
|
||||
//! `materialcraft-cli serve` runs it on stdio or on a loopback TCP port (first request `auth`).
|
||||
//!
|
||||
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
|
||||
//! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`,
|
||||
//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`
|
||||
//! (workspace-scoped versions of the engine commands), `render {view?, width?, height?, yaw?,
|
||||
//! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`)
|
||||
//! and `methods`.
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
@@ -18,7 +7,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] = &[
|
||||
@@ -32,6 +23,7 @@ pub const METHODS: &[&str] = &[
|
||||
"package.save",
|
||||
"bitmap.import",
|
||||
"outputs.export",
|
||||
"material.export",
|
||||
"render",
|
||||
];
|
||||
|
||||
@@ -65,7 +57,7 @@ fn required<'a>(p: &'a Value, k: &str) -> Result<&'a str, AutomationError> {
|
||||
}
|
||||
|
||||
impl Headless {
|
||||
/// Dispatch one request. Unknown methods and bad params are errors, never panics.
|
||||
/// Dispatch one request. Unknown methods and bad params are errors, never panics
|
||||
pub fn handle(&mut self, method: &str, p: &Value) -> Result<Value, AutomationError> {
|
||||
match method {
|
||||
"ping" => Ok(json!("pong")),
|
||||
@@ -84,6 +76,7 @@ impl Headless {
|
||||
"package.save" => self.save(str_of(p, "path")),
|
||||
"bitmap.import" => self.import_bitmap(required(p, "path")?, str_of(p, "name")),
|
||||
"outputs.export" => self.export(p),
|
||||
"material.export" => self.export_material(p),
|
||||
"render" => {
|
||||
let o = RenderOptions {
|
||||
view: str_of(p, "view").map(str::to_string),
|
||||
@@ -99,6 +92,7 @@ impl Headless {
|
||||
hq: bool_of(p, "hq")?,
|
||||
displacement: f32_of(p, "displacement")?,
|
||||
};
|
||||
|
||||
let r = self.render_png(&o)?;
|
||||
Ok(json!({ "width": r.width, "height": r.height, "png": base64::engine::general_purpose::STANDARD.encode(r.png) }))
|
||||
}
|
||||
@@ -110,17 +104,18 @@ impl Headless {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a
|
||||
/// snapshot, so the session stays consistent).
|
||||
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a snapshot, so the session stays consistent)
|
||||
pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
|
||||
let req: Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}),
|
||||
};
|
||||
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
let Some(method) = req.get("method").and_then(Value::as_str) else {
|
||||
return json!({"id": id, "ok": false, "error": "`method` is required"});
|
||||
};
|
||||
|
||||
let params = req.get("params").cloned().unwrap_or(Value::Null);
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).handle(method, ¶ms)))
|
||||
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))));
|
||||
@@ -130,14 +125,14 @@ pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write one reply line; an oversized reply becomes an error with the same id.
|
||||
/// Write one reply line; an oversized reply becomes an error with the same id
|
||||
fn write_reply(w: &mut impl Write, reply: &Value) -> std::io::Result<()> {
|
||||
let text = json_text(reply).unwrap_or_else(|e| json!({"id": reply.get("id"), "ok": false, "error": e.to_string()}).to_string());
|
||||
writeln!(w, "{text}")?;
|
||||
w.flush()
|
||||
}
|
||||
|
||||
/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication).
|
||||
/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication)
|
||||
pub fn serve_lines(h: &Mutex<Headless>, mut r: impl BufRead, mut w: impl Write) -> std::io::Result<()> {
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
@@ -149,23 +144,33 @@ pub fn serve_lines(h: &Mutex<Headless>, mut r: impl BufRead, mut w: impl Write)
|
||||
Ok(LineRead::Line) if line.trim().is_empty() => continue,
|
||||
Ok(LineRead::Line) => respond(h, &line),
|
||||
};
|
||||
|
||||
write_reply(&mut w, &reply)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// One TCP connection: the first request must be `auth {token}`, as on the app's channel.
|
||||
/// One TCP connection: the first request must be `auth {token}`, as on the app's channel
|
||||
fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &str) -> std::io::Result<()> {
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(600)))?;
|
||||
let mut r = std::io::BufReader::new(stream.try_clone()?);
|
||||
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(()),
|
||||
LineRead::TooLong => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})),
|
||||
LineRead::Line if line.trim().is_empty() => continue,
|
||||
LineRead::Line => {}
|
||||
match read_bounded_line(&mut r, &mut line) {
|
||||
Ok(LineRead::Eof) => return Ok(()),
|
||||
Ok(LineRead::TooLong) => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})),
|
||||
Ok(LineRead::Line) if line.trim().is_empty() => continue,
|
||||
Ok(LineRead::Line) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
|
||||
write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request is not UTF-8"}))?;
|
||||
if !authed {
|
||||
return Ok(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
if authed {
|
||||
write_reply(&mut w, &respond(h, &line))?;
|
||||
@@ -178,15 +183,25 @@ 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}))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared
|
||||
/// session. `ready` gets the bound address.
|
||||
/// 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() {
|
||||
@@ -195,11 +210,14 @@ pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl
|
||||
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"}));
|
||||
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(())
|
||||
}
|
||||
@@ -232,7 +250,7 @@ mod tests {
|
||||
r#"{"id":4,"method":"command.run","params":{"id":"file.open","params":{"path":"/etc/passwd"}}}"#,
|
||||
"
|
||||
",
|
||||
r#"{"id":5,"method":"package.open","params":{"path":"x.mcraft"}}"#,
|
||||
r#"{"id":5,"method":"package.open","params":{"path":"x.sbs"}}"#,
|
||||
"
|
||||
",
|
||||
r#"{"id":6,"method":"command.batch","params":{"steps":[{"id":"edit.selectAll"},{"id":"nope"},{"id":"edit.selectAll"}]}}"#,
|
||||
@@ -253,6 +271,81 @@ mod tests {
|
||||
assert_eq!(r[6]["result"]["failed"]["index"], 1);
|
||||
}
|
||||
|
||||
/// A workspace session rooted at a fresh `inside` folder, with an `outside` sibling.
|
||||
fn workspace_session(name: &str, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex<Headless>) {
|
||||
let base = std::env::temp_dir().join(format!("mc-rpc-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (inside, outside) = (base.join("inside"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let ws = crate::AuthorizedWorkspace::new(Some(&inside), write.then_some(inside.as_path())).unwrap();
|
||||
let h = Mutex::new(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
|
||||
(inside, outside, h)
|
||||
}
|
||||
|
||||
fn call(h: &Mutex<Headless>, method: &str, params: Value) -> Result<Value, String> {
|
||||
h.lock().unwrap().handle(method, ¶ms).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_export_writes_a_portable_material_below_the_write_root() {
|
||||
let (inside, _, h) = workspace_session("mat-ok", true);
|
||||
std::fs::create_dir(inside.join("out")).unwrap();
|
||||
let r = call(&h, "material.export", json!({"path": "out/brick", "size": 32})).unwrap();
|
||||
assert_eq!(r["path"], "out/brick.mcmat");
|
||||
let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap();
|
||||
assert_eq!(r["bytes"], bytes.len());
|
||||
let (m, source) = materialcraft_engine::formats::material::read_material(&bytes).unwrap();
|
||||
assert_eq!(m.size, [32, 32]);
|
||||
assert!(m.maps.iter().any(|e| e.usage == "height"));
|
||||
assert!(!source.is_empty());
|
||||
assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind");
|
||||
// An explicit extension is kept (case-insensitively) and the file can be opened again.
|
||||
let r = call(&h, "material.export", json!({"path": "again.MCMAT", "size": 16})).unwrap();
|
||||
assert_eq!(r["path"], "again.MCMAT");
|
||||
assert!(call(&h, "package.open", json!({"path": "again.MCMAT"})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_export_reports_bad_requests() {
|
||||
let (inside, _, h) = workspace_session("mat-bad", true);
|
||||
for bad in [json!({}), json!({"path": "m", "graph": 99}), json!({"path": "m", "values": {"no_such_input": 1}})] {
|
||||
assert!(call(&h, "material.export", bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
assert!(call(&h, "material.export", json!({"path": "missing/dir/m"})).is_err(), "parent must exist");
|
||||
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0, "failed exports leave nothing behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_export_needs_a_write_root() {
|
||||
let denied = session();
|
||||
let e = call(&denied, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
|
||||
assert!(e.contains("not granted"), "{e}");
|
||||
let (inside, _, read_only) = workspace_session("mat-readonly", false);
|
||||
let e = call(&read_only, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
|
||||
assert!(e.contains("no write root"), "{e}");
|
||||
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_export_cannot_escape_the_write_root() {
|
||||
let (_inside, outside, h) = workspace_session("mat-escape", true);
|
||||
let abs = outside.join("abs.mcmat").display().to_string();
|
||||
for p in ["../outside/m.mcmat", "a/../../outside/m.mcmat", "/tmp/m.mcmat", "a\\b.mcmat", "C:/m.mcmat", "./m.mcmat", abs.as_str()] {
|
||||
let e = call(&h, "material.export", json!({"path": p, "size": 16}));
|
||||
assert!(e.is_err(), "accepted {p:?}");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&outside, _inside.join("link")).unwrap();
|
||||
assert!(call(&h, "material.export", json!({"path": "link/m.mcmat", "size": 16})).is_err());
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "nothing written outside the root");
|
||||
// The generic command path stays closed too: host paths are still refused.
|
||||
let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err();
|
||||
assert!(e.contains("disabled for automation"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_requires_the_token() {
|
||||
use std::io::{BufRead, BufReader};
|
||||
@@ -275,6 +368,7 @@ mod tests {
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let denied = talk(&[r#"{"id":1,"method":"session.inspect"}"#]);
|
||||
assert_eq!(denied[0]["ok"], false);
|
||||
let ok = talk(&[r#"{"id":1,"method":"auth","params":{"token":"0123456789abcdef0123"}}"#, r#"{"id":2,"method":"ping"}"#]);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
use crate::{BridgeClient, Headless};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Where tools run
|
||||
pub enum Backend {
|
||||
/// An in-process session
|
||||
Headless(Arc<Mutex<Headless>>),
|
||||
/// The running desktop app, over its control channel
|
||||
Bridge(Arc<BridgeClient>),
|
||||
}
|
||||
+44
-225
@@ -1,6 +1,4 @@
|
||||
//! The MCP server (rmcp). Tool names are `snake_case`; each tool maps to one control-channel
|
||||
//! method (see [`crate::rpc`]), answered in process (headless) or by the running app (bridge).
|
||||
|
||||
use super::{Backend, parameter::*};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use base64::Engine as _;
|
||||
@@ -8,8 +6,7 @@ use rmcp::handler::server::router::tool::ToolRouter;
|
||||
use rmcp::handler::server::wrapper::Parameters;
|
||||
use rmcp::model::{CallToolResult, ContentBlock as Content};
|
||||
use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text};
|
||||
@@ -18,212 +15,12 @@ use crate::security::MAX_BATCH_STEPS;
|
||||
use crate::workspace::authorize_command;
|
||||
use crate::{AutomationError, BridgeClient, Headless, bad};
|
||||
|
||||
/// Where tools run.
|
||||
pub enum Backend {
|
||||
/// An in-process session.
|
||||
Headless(Arc<Mutex<Headless>>),
|
||||
/// The running desktop app, over its control channel.
|
||||
Bridge(Arc<BridgeClient>),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MaterialcraftMcp {
|
||||
pub struct MaterialCraftMcp {
|
||||
backend: Arc<Backend>,
|
||||
tool_router: ToolRouter<Self>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Parameters (serialized back to JSON as the control method's params)
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct FilterParams {
|
||||
/// Only entries whose id or label contains this text (case-insensitive).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub filter: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct LibraryParams {
|
||||
/// Only nodes whose id or label contains this text.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub filter: Option<String>,
|
||||
/// Only nodes in this library category, e.g. "Noises", "Patterns", "Filters/Blurs".
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub category: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct RunParams {
|
||||
/// Command id from `command_list`, e.g. `graph.node.add`, `graph.connect`, `edit.undo`.
|
||||
pub id: String,
|
||||
/// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub params: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct BatchParams {
|
||||
/// Commands run in order; the batch stops at the first error and reports its index.
|
||||
pub steps: Vec<RunParams>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct NewGraphParams {
|
||||
/// Template id: empty, pbr (default: six material outputs), bricks, stone_tiles, wood, metal_plates, rusty_metal, lava, marble, wicker, fabric, ground.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub template: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Graph size in pixels, a power of two from 16 to 8192 (default 1024).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct NodeAddParams {
|
||||
/// Node definition id from `library_list`, e.g. `perlin_noise`, `blend`, `levels`, `normal`, `output`.
|
||||
pub def: String,
|
||||
/// Graph position `[x, y]` (default: right of `connectFrom`, else the origin).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub at: Option<[f32; 2]>,
|
||||
/// Parameter values by id (see `library_list`): numbers, `[x, y]`, `"#rrggbb"`, enum indices.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub params: Option<Value>,
|
||||
/// Wire `{node, port?}`'s output into the new node's first input.
|
||||
#[serde(default, rename = "connectFrom", skip_serializing_if = "Option::is_none")]
|
||||
pub connect_from: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ConnectParams {
|
||||
/// Source node id.
|
||||
pub from: u64,
|
||||
/// Source output port id (default: its first output).
|
||||
#[serde(default, rename = "fromPort", skip_serializing_if = "Option::is_none")]
|
||||
pub from_port: Option<String>,
|
||||
/// Target node id.
|
||||
pub to: u64,
|
||||
/// Target input port id (default: its first input).
|
||||
#[serde(default, rename = "toPort", skip_serializing_if = "Option::is_none")]
|
||||
pub to_port: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ParamSetParams {
|
||||
/// Node id.
|
||||
pub id: u64,
|
||||
/// Parameter id (see `library_list`).
|
||||
pub param: String,
|
||||
/// The value: a number, `[x, y]`, `"#rrggbb"`, an enum index, a curve `[[x, y], …]` or a gradient `[[pos, color], …]`.
|
||||
pub value: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct PathParams {
|
||||
/// Forward-slash path relative to the workspace root.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct SaveParams {
|
||||
/// Forward-slash path relative to the write root (`.sbs` is appended unless it ends in `.sbs`
|
||||
/// or `.mcraft`). Omit to save to the package's own file.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct BitmapParams {
|
||||
/// Image file relative to the read root (png, jpg, tga, tif, bmp, webp, exr, hdr).
|
||||
pub path: String,
|
||||
/// Resource name (default: the file name).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ExportParams {
|
||||
/// Output folder relative to the write root (created if missing; `.` = the root).
|
||||
pub dir: String,
|
||||
/// png (default), jpg, tga, tif, bmp, webp, exr, hdr.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
/// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pattern: Option<String>,
|
||||
/// 8, 16 or 32 bits (default: the graph's output format).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub depth: Option<u32>,
|
||||
/// Graph index (default: the open graph).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub graph: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct RenderParams {
|
||||
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub view: Option<String>,
|
||||
/// Pixels, 16..2048.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub width: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub height: Option<u32>,
|
||||
/// Camera yaw/pitch in degrees for this render only.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub yaw: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pitch: Option<f32>,
|
||||
/// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scene: Option<String>,
|
||||
/// 2D: the node to show (default: the 2D view's node, else the first output).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub node: Option<u64>,
|
||||
/// 2D: the output port index.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub port: Option<u32>,
|
||||
/// Cook at the full graph size instead of the preview size.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub full: Option<bool>,
|
||||
/// 3D: UV repeats of the material on the scene for this render only.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tiling: Option<f32>,
|
||||
/// 3D beauty render: real displacement from the height output, ambient occlusion and a
|
||||
/// shadowed key light (slower).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hq: Option<bool>,
|
||||
/// With `hq`: displacement depth in scene radii (default 0.04).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub displacement: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ScreenshotParams {
|
||||
/// `3d` (default) or `2d`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub view: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct MenuParams {
|
||||
/// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `ui.newGraph`, `ui.view.library`.
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct InputParams {
|
||||
/// Input events in window points, applied in order on the next frames. Each is one of:
|
||||
/// {"type":"move","pos":[x,y]}, {"type":"down"|"up","pos":[x,y],"button":"left"|"right"|"middle"},
|
||||
/// {"type":"click"|"doubleClick","pos":[x,y],"button"?}, {"type":"drag","from":[x,y],"to":[x,y],"button"?,"steps"?},
|
||||
/// {"type":"scroll","pos":[x,y],"delta":[dx,dy]}, {"type":"key","key":"A"|"Enter"|"Space"|…,"modifiers"?:["ctrl","shift","alt"]},
|
||||
/// {"type":"text","text":"…"}.
|
||||
pub events: Vec<Value>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Results
|
||||
|
||||
fn ok_json(v: &Value) -> CallToolResult {
|
||||
match json_text(v) {
|
||||
Ok(text) => CallToolResult::success(vec![Content::text(text)]),
|
||||
@@ -242,7 +39,7 @@ fn to_result(r: Result<Value, AutomationError>) -> Result<CallToolResult, McpErr
|
||||
})
|
||||
}
|
||||
|
||||
/// A `{width, height, png: base64}` reply (render or app screenshot) as image content.
|
||||
/// A `{width, height, png: base64}` reply (render or app screenshot) as image content
|
||||
fn image_result(r: Result<Value, AutomationError>, note: &str, refit: bool) -> Result<CallToolResult, McpError> {
|
||||
let png = r.and_then(|v| {
|
||||
let b64 = v.get("png").and_then(Value::as_str).ok_or_else(|| AutomationError::Other("the reply has no PNG".into()))?;
|
||||
@@ -263,7 +60,7 @@ fn params<T: Serialize>(p: &T) -> Value {
|
||||
serde_json::to_value(p).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
impl MaterialcraftMcp {
|
||||
impl MaterialCraftMcp {
|
||||
pub fn headless(h: Headless) -> Self {
|
||||
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h))))
|
||||
}
|
||||
@@ -273,10 +70,10 @@ impl MaterialcraftMcp {
|
||||
}
|
||||
|
||||
pub fn with_backend(backend: Backend) -> Self {
|
||||
MaterialcraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
|
||||
MaterialCraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
|
||||
}
|
||||
|
||||
/// Serve MCP on stdin/stdout until the client disconnects.
|
||||
/// Serve MCP on stdin/stdout until the client disconnects
|
||||
pub async fn serve_stdio(self) -> Result<(), AutomationError> {
|
||||
let running = self.serve(rmcp::transport::stdio()).await.map_err(|e| AutomationError::Other(format!("MCP start: {e}")))?;
|
||||
running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()))?;
|
||||
@@ -287,13 +84,12 @@ impl MaterialcraftMcp {
|
||||
matches!(*self.backend, Backend::Bridge(_))
|
||||
}
|
||||
|
||||
/// One control-channel method on the backend.
|
||||
/// One control-channel method on the backend
|
||||
async fn call(&self, method: &str, p: Value) -> Result<Value, AutomationError> {
|
||||
match &*self.backend {
|
||||
Backend::Headless(h) => {
|
||||
let (h, m) = (h.clone(), method.to_string());
|
||||
// Edits run on snapshots (`Session::edit`), so a panicking command leaves the
|
||||
// session consistent: keep serving after a poisoned lock.
|
||||
// Edits run on snapshots (`Session::edit`), so a panicking command leaves the session consistent: keep serving after a poisoned lock
|
||||
tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
|
||||
@@ -305,7 +101,7 @@ impl MaterialcraftMcp {
|
||||
b.call(method, p).await
|
||||
}
|
||||
"package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
|
||||
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "command.batch" | "render" => {
|
||||
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => {
|
||||
Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
|
||||
}
|
||||
_ => b.call(method, p).await,
|
||||
@@ -328,11 +124,10 @@ impl MaterialcraftMcp {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Tools
|
||||
// --------------------------------------------------------------------------------------------- Tools
|
||||
|
||||
#[tool_router]
|
||||
impl MaterialcraftMcp {
|
||||
impl MaterialCraftMcp {
|
||||
#[tool(description = "The whole session as JSON: package, graphs, the open graph's nodes (definition, parameters, base \
|
||||
parameters, ports, cook errors, timings, mean values), connections, frames, comments, pins, exposed inputs, views and history.")]
|
||||
async fn session_inspect(&self) -> Result<CallToolResult, McpError> {
|
||||
@@ -405,15 +200,13 @@ impl MaterialcraftMcp {
|
||||
}
|
||||
|
||||
#[tool(
|
||||
description = "Open an .sbs or .mcraft package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
|
||||
description = "Open an .sbs package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
|
||||
)]
|
||||
async fn package_open(&self, Parameters(p): Parameters<PathParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("package.open", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(
|
||||
description = "Save the package (path relative to the write root; omit to save to its own file). Saves SBS (.sbs, the main format) unless the path ends in .mcraft."
|
||||
)]
|
||||
#[tool(description = "Save the package (path relative to the write root; omit to save to its own file). Saves native SBS (.sbs).")]
|
||||
async fn package_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("package.save", params(&p)).await)
|
||||
}
|
||||
@@ -430,6 +223,13 @@ impl MaterialcraftMcp {
|
||||
to_result(self.call("outputs.export", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \
|
||||
source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \
|
||||
Returns {path, bytes}.")]
|
||||
async fn material_export(&self, Parameters(p): Parameters<MaterialExportParams>) -> Result<CallToolResult, McpError> {
|
||||
to_result(self.call("material.export", params(&p)).await)
|
||||
}
|
||||
|
||||
#[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \
|
||||
2048 px a side. In bridge mode use view_screenshot.")]
|
||||
async fn view_render(&self, Parameters(p): Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
|
||||
@@ -469,11 +269,11 @@ impl MaterialcraftMcp {
|
||||
name = "materialcraft",
|
||||
instructions = "MaterialCraft procedural material designer. A package holds graphs of nodes; each graph's output nodes \
|
||||
(usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \
|
||||
(templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \
|
||||
(templates: empty, pbr, atomics) or package_open, browse nodes with library_list, build with node_add / node_connect \
|
||||
/ node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \
|
||||
view_render (3d, or 2d for one node), then package_save and outputs_export. Undo: command_run edit.undo."
|
||||
view_render (3d, or 2d for one node), then package_save, outputs_export or material_export. Undo: command_run edit.undo."
|
||||
)]
|
||||
impl ServerHandler for MaterialcraftMcp {}
|
||||
impl ServerHandler for MaterialCraftMcp {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -482,7 +282,7 @@ mod tests {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_panic_does_not_wedge_the_session() {
|
||||
let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
|
||||
let mcp = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
|
||||
let Backend::Headless(h) = &*mcp.backend else { panic!("headless") };
|
||||
let h2 = h.clone();
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
@@ -493,6 +293,25 @@ mod tests {
|
||||
assert!(mcp.call("session.inspect", json!({})).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn material_export_tool_writes_through_the_workspace_only() {
|
||||
let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None });
|
||||
|
||||
let denied = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
|
||||
assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true));
|
||||
|
||||
let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap();
|
||||
let mcp = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
|
||||
assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false));
|
||||
assert!(base.join("m.mcmat").is_file());
|
||||
let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None });
|
||||
assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true));
|
||||
assert!(!base.parent().unwrap().join("m.mcmat").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_replies_become_errors() {
|
||||
let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES)));
|
||||
@@ -0,0 +1,6 @@
|
||||
mod backend;
|
||||
mod material_craft_mcp;
|
||||
mod parameter;
|
||||
|
||||
pub use backend::Backend;
|
||||
pub use material_craft_mcp::MaterialCraftMcp;
|
||||
@@ -0,0 +1,9 @@
|
||||
use super::RunParams;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct BatchParams {
|
||||
/// Commands run in order; the batch stops at the first error and reports its index
|
||||
pub steps: Vec<RunParams>,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct BitmapParams {
|
||||
/// Image file relative to the read root (png, jpg, tga, tif, bmp, webp, exr, hdr)
|
||||
pub path: String,
|
||||
/// Resource name (default: the file name)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ConnectParams {
|
||||
/// Source node id
|
||||
pub from: u64,
|
||||
/// Source output port id (default: its first output)
|
||||
#[serde(default, rename = "fromPort", skip_serializing_if = "Option::is_none")]
|
||||
pub from_port: Option<String>,
|
||||
/// Target node id
|
||||
pub to: u64,
|
||||
/// Target input port id (default: its first input)
|
||||
#[serde(default, rename = "toPort", skip_serializing_if = "Option::is_none")]
|
||||
pub to_port: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ExportParams {
|
||||
/// Output folder relative to the write root (created if missing; `.` = the root)
|
||||
pub dir: String,
|
||||
/// png (default), jpg, tga, tif, bmp, webp, exr, hdr
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
/// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pattern: Option<String>,
|
||||
/// 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>,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct FilterParams {
|
||||
/// Only entries whose id or label contains this text (case-insensitive)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub filter: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct InputParams {
|
||||
/// Input events in window points, applied in order on the next frames
|
||||
pub events: Vec<Value>,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct LibraryParams {
|
||||
/// Only nodes whose id or label contains this text
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub filter: Option<String>,
|
||||
/// Library category, such as "Atomic nodes" or "Graph items"
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub category: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct MaterialExportParams {
|
||||
/// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The
|
||||
/// parent folder must exist
|
||||
pub path: String,
|
||||
/// Graph index (default: the open graph)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub graph: Option<u32>,
|
||||
/// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
/// Exposed input values to cook with and embed, by input id (see `session_inspect`)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub values: Option<Value>,
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct MenuParams {
|
||||
/// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `ui.newGraph`, `ui.view.library`
|
||||
pub id: String,
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
mod batch_params;
|
||||
mod bitmap_params;
|
||||
mod connect_params;
|
||||
mod export_params;
|
||||
mod filter_params;
|
||||
mod input_params;
|
||||
mod library_params;
|
||||
mod menu_params;
|
||||
mod new_graph_params;
|
||||
mod node_add_params;
|
||||
mod param_set_params;
|
||||
mod path_params;
|
||||
mod render_params;
|
||||
mod run_params;
|
||||
mod save_params;
|
||||
mod screenshot_params;
|
||||
|
||||
pub use batch_params::BatchParams;
|
||||
pub use bitmap_params::BitmapParams;
|
||||
pub use connect_params::ConnectParams;
|
||||
pub use export_params::ExportParams;
|
||||
pub use filter_params::FilterParams;
|
||||
pub use input_params::InputParams;
|
||||
pub use library_params::LibraryParams;
|
||||
pub use menu_params::MenuParams;
|
||||
pub use new_graph_params::NewGraphParams;
|
||||
pub use node_add_params::NodeAddParams;
|
||||
pub use param_set_params::ParamSetParams;
|
||||
pub use path_params::PathParams;
|
||||
pub use render_params::RenderParams;
|
||||
pub use run_params::RunParams;
|
||||
pub use save_params::SaveParams;
|
||||
pub use screenshot_params::ScreenshotParams;
|
||||
|
||||
mod material_export_params;
|
||||
pub use material_export_params::MaterialExportParams;
|
||||
@@ -0,0 +1,14 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct NewGraphParams {
|
||||
/// Template id: empty, pbr (six material outputs), atomics
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub template: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Graph size in pixels, a power of two from 16 to 8192 (default 1024)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct NodeAddParams {
|
||||
/// Node definition id from `library_list`, e.g. `uniform`, `blend`, `levels`, `normal`, `output`
|
||||
pub def: String,
|
||||
/// Graph position `[x, y]` (default: right of `connectFrom`, else the origin)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub at: Option<[f32; 2]>,
|
||||
/// Parameter values by id (see `library_list`): numbers, `[x, y]`, `"#rrggbb"`, enum indices
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub params: Option<Value>,
|
||||
/// Wire `{node, port?}`'s output into the new node's first input
|
||||
#[serde(default, rename = "connectFrom", skip_serializing_if = "Option::is_none")]
|
||||
pub connect_from: Option<Value>,
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ParamSetParams {
|
||||
/// Node id
|
||||
pub id: u64,
|
||||
/// Parameter id (see `library_list`)
|
||||
pub param: String,
|
||||
/// The value: a number, `[x, y]`, `"#rrggbb"`, an enum index, a curve `[[x, y], …]` or a gradient `[[pos, color], …]`
|
||||
pub value: Value,
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct PathParams {
|
||||
/// Forward-slash path relative to the workspace root
|
||||
pub path: String,
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct RenderParams {
|
||||
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub view: Option<String>,
|
||||
/// Pixels, 16..2048
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub width: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub height: Option<u32>,
|
||||
/// Camera yaw/pitch in degrees for this render only
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub yaw: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pitch: Option<f32>,
|
||||
/// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scene: Option<String>,
|
||||
/// 2D: the node to show (default: the 2D view's node, else the first output)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub node: Option<u64>,
|
||||
/// 2D: the output port index
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub port: Option<u32>,
|
||||
/// Cook at the full graph size instead of the preview size
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub full: Option<bool>,
|
||||
/// 3D: UV repeats of the material on the scene for this render only
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tiling: Option<f32>,
|
||||
/// 3D beauty render: real displacement from the height output, ambient occlusion and a shadowed key light (slower)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hq: Option<bool>,
|
||||
/// With `hq`: displacement depth in scene radii (default 0.04)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub displacement: Option<f32>,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct RunParams {
|
||||
/// Command id from `command_list`, e.g. `graph.node.add`, `graph.connect`, `edit.undo`
|
||||
pub id: String,
|
||||
/// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub params: Option<Value>,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct SaveParams {
|
||||
/// Optional path relative to the write root, with an .sbs extension
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct ScreenshotParams {
|
||||
/// `3d` (default) or `2d`
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub view: Option<String>,
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
//! Capability-based file access for untrusted automation paths (MCP, `serve`).
|
||||
//!
|
||||
//! Roots are trusted launch-time configuration (`--read-root`, `--write-root`); request paths
|
||||
//! are untrusted, forward-slash relative paths resolved by `cap-std` beneath the held directory
|
||||
//! handle, so `..`, absolute paths, drive prefixes and symlink or junction escapes all fail.
|
||||
//! Capability-based file access for untrusted automation paths (MCP, `serve`)
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -14,10 +10,10 @@ use serde_json::Value;
|
||||
|
||||
use crate::{AutomationError, bad};
|
||||
|
||||
/// Largest file read through automation (the mesh importer's own limit).
|
||||
/// Largest file read through automation (the mesh importer's own limit)
|
||||
pub const MAX_READ_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// Separate read and write directory capabilities. A missing authority fails closed.
|
||||
/// Separate read and write directory capabilities. A missing authority fails closed
|
||||
#[derive(Clone, Default)]
|
||||
pub struct AuthorizedWorkspace {
|
||||
read: Option<Arc<Dir>>,
|
||||
@@ -29,7 +25,7 @@ impl AuthorizedWorkspace {
|
||||
Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? })
|
||||
}
|
||||
|
||||
/// Read one regular file below the read root.
|
||||
/// Read one regular file below the read root
|
||||
pub fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
|
||||
let rel = relative_path(path)?;
|
||||
let root = self.read.as_ref().ok_or_else(|| denied("read"))?;
|
||||
@@ -46,8 +42,7 @@ impl AuthorizedWorkspace {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Create or replace one file below the write root: a temporary file beside the target,
|
||||
/// synced and renamed over it. The parent directory must exist.
|
||||
/// Create or replace one file below the write root: a temporary file beside the target, synced and renamed over it. The parent directory must exist
|
||||
pub fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
|
||||
let rel = relative_path(path)?;
|
||||
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
|
||||
@@ -69,7 +64,13 @@ impl AuthorizedWorkspace {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create a directory (and its parents) below the write root.
|
||||
/// Validate the write capability and relative path before cooking
|
||||
pub fn check_write(&self, path: &str) -> Result<(), AutomationError> {
|
||||
relative_path(path)?;
|
||||
self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write"))
|
||||
}
|
||||
|
||||
/// Create a directory and its parents below the write root
|
||||
pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> {
|
||||
let rel = relative_path(path)?;
|
||||
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
|
||||
@@ -87,7 +88,7 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<Arc<Dir>>, A
|
||||
Ok(Some(Arc::new(dir)))
|
||||
}
|
||||
|
||||
/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root).
|
||||
/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root)
|
||||
pub fn relative_path(raw: &str) -> Result<PathBuf, AutomationError> {
|
||||
let reject = |why: &str| bad(format!("path rejected ({why}): `{raw}`; use a forward-slash path relative to the workspace root"));
|
||||
if raw.is_empty() {
|
||||
@@ -127,18 +128,14 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
|
||||
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
|
||||
}
|
||||
|
||||
/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
|
||||
/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
|
||||
/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
|
||||
/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
|
||||
/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
|
||||
/// embedded mesh).
|
||||
/// Route file access through the workspace boundary
|
||||
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
|
||||
let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
|
||||
let ok = match id {
|
||||
"file.new" | "file.newPackage" => !has_path,
|
||||
"file.new" | "file.newPackage" | "file.newAtomicSample" => !has_path,
|
||||
_ => !id.starts_with("file.") && !has_path,
|
||||
};
|
||||
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -234,12 +231,11 @@ mod tests {
|
||||
assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}");
|
||||
assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}");
|
||||
}
|
||||
assert!(authorize_command("file.new", &json!({"template": "bricks"})).is_ok());
|
||||
assert!(authorize_command("file.new", &json!({"template": "atomics"})).is_ok());
|
||||
assert!(authorize_command("graph.node.add", &json!({"def": "blur", "path": null})).is_ok());
|
||||
}
|
||||
|
||||
/// Every registry command documenting a host path must be classified (fails when a new
|
||||
/// path-taking command is added without an automation policy).
|
||||
/// Every registry command documenting a host path must be classified (fails when a new path-taking command is added without an automation policy)
|
||||
#[test]
|
||||
fn registry_path_params_are_classified() {
|
||||
let probe = json!({"path": "/outside/probe", "dir": "/outside", "mesh": "/outside/m.obj"});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
use materialcraft_automation::headless::{Filesystem, Headless, RenderOptions};
|
||||
use materialcraft_engine::{
|
||||
execute,
|
||||
image::{Image, Kind},
|
||||
new_session,
|
||||
nodes::atomic::height_to_normal,
|
||||
};
|
||||
use materialcraft_render::{Lighting, Maps, Scene, Settings, render};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn generated_normal_conventions_produce_the_same_surface_when_matched() {
|
||||
let height = Image::gray(32, 32, |x, y| ((x as f32 * 0.15).sin() + (y as f32 * 0.25).sin()) * 0.25 + 0.5);
|
||||
let gl = height_to_normal(&height, 8.0, false, false, false);
|
||||
let dx = height_to_normal(&height, 8.0, true, false, false);
|
||||
let normal_node = materialcraft_engine::nodes::find("normal").unwrap();
|
||||
assert_eq!(normal_node.param("opengl").unwrap().default.as_bool(), Some(true));
|
||||
let maps = |normal| Maps { normal: Some(normal), base_color: Some(Image::filled(4, 4, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() };
|
||||
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
|
||||
let settings = Settings::default();
|
||||
assert!(!settings.normal_y_flip);
|
||||
let expected = render(&scene, &maps(gl), &light, &settings, 64, 48);
|
||||
let flipped = maps(dx);
|
||||
let matched = render(&scene, &flipped, &light, &Settings { normal_y_flip: true, ..settings }, 64, 48);
|
||||
assert!(expected.iter().zip(&matched).all(|(a, b)| a.abs_diff(*b) <= 1));
|
||||
let wrong = render(&scene, &flipped, &light, &settings, 64, 48);
|
||||
assert!(expected.iter().zip(&wrong).filter(|(a, b)| a.abs_diff(**b) > 2).count() > 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_render_honors_the_normal_y_command() {
|
||||
let mut s = new_session();
|
||||
s.preview_size = Some(64);
|
||||
let node = execute(&mut s, "graph.node.add", &json!({"def": "uniform", "params": {"color": [0.5, 0.75, 1.0, 1.0]}})).unwrap()["id"].as_u64().unwrap();
|
||||
execute(&mut s, "graph.node.add", &json!({"def": "output", "connectFrom": {"node": node}, "params": {"usage": 1}})).unwrap();
|
||||
let mut h = Headless::new(s, Filesystem::Denied);
|
||||
let options = RenderOptions { width: Some(64), height: Some(48), ..RenderOptions::default() };
|
||||
let gl = h.render_png(&options).unwrap().png;
|
||||
execute(&mut h.session, "view.3d", &json!({"normalYFlip": true})).unwrap();
|
||||
let wrong = h.render_png(&options).unwrap().png;
|
||||
assert_ne!(gl, wrong);
|
||||
execute(&mut h.session, "graph.node.param", &json!({"id": node, "param": "color", "value": [0.5, 0.25, 1.0, 1.0]})).unwrap();
|
||||
assert_eq!(gl, h.render_png(&options).unwrap().png);
|
||||
execute(&mut h.session, "view.3d.reset", &json!({})).unwrap();
|
||||
assert_eq!(wrong, h.render_png(&options).unwrap().png);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use materialcraft_automation::headless::{Filesystem, Headless, RenderOptions};
|
||||
use materialcraft_engine::new_session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn rejected_view_command_preserves_the_rendered_scene() {
|
||||
let mut h = Headless::new(new_session(), Filesystem::Denied);
|
||||
let options = RenderOptions { width: Some(64), height: Some(48), ..RenderOptions::default() };
|
||||
h.command_run("view.3d", json!({"scene": "sphere", "environment": "sunset"})).unwrap();
|
||||
let before = h.render_png(&options).unwrap().png;
|
||||
assert!(h.command_run("view.3d", json!({"scene": "cube", "environment": "invalid"})).is_err());
|
||||
assert!(before == h.render_png(&options).unwrap().png, "rejected settings changed the rendered scene");
|
||||
// Confirm that valid settings still change the rendered output rather than returning a stale image.
|
||||
h.command_run("view.3d", json!({"scene": "cube", "environment": "night"})).unwrap();
|
||||
assert_ne!(before, h.render_png(&options).unwrap().png);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Descriptive metadata ("Attributes")
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Attributes {
|
||||
pub category: String,
|
||||
pub description: String,
|
||||
pub author: String,
|
||||
pub tags: String,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{OutputFormat, SizeMode};
|
||||
|
||||
/// Parameters every node has ("Base parameters")
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct BaseParameters {
|
||||
pub size_mode: SizeMode,
|
||||
/// log2 offset per axis (relative modes) or log2 size (absolute)
|
||||
pub size: [i32; 2],
|
||||
pub format: OutputFormat,
|
||||
/// Added to the graph's random seed for this node
|
||||
pub seed: i32,
|
||||
/// Whether sampling wraps at the edges (horizontal, vertical)
|
||||
pub tiling: [bool; 2],
|
||||
}
|
||||
|
||||
impl Default for BaseParameters {
|
||||
fn default() -> Self {
|
||||
BaseParameters { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/// `[r, g, b(, a)]` linear floats, a single gray number, or `"#rrggbb(aa)"` (sRGB, converted to linear)
|
||||
pub fn parse_color(j: &serde_json::Value) -> Option<[f32; 4]> {
|
||||
use serde_json::Value as J;
|
||||
match j {
|
||||
J::Array(a) if a.len() >= 3 => {
|
||||
let v: Vec<f32> = a.iter().take(4).filter_map(|x| x.as_f64().map(|x| x as f32)).filter(|x| x.is_finite()).collect();
|
||||
if v.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
Some([v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)])
|
||||
}
|
||||
J::Number(n) => n.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).map(|v| [v, v, v, 1.0]),
|
||||
J::String(s) => {
|
||||
let s = s.trim_start_matches('#');
|
||||
if s.len() != 6 && s.len() != 8 {
|
||||
return None;
|
||||
}
|
||||
let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0);
|
||||
let a = if s.len() == 8 { c(6)? } else { 1.0 };
|
||||
Some([srgb_to_linear(c(0)?), srgb_to_linear(c(2)?), srgb_to_linear(c(4)?), a])
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB transfer function, encoded → linear
|
||||
pub fn srgb_to_linear(v: f32) -> f32 {
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// sRGB transfer function, linear → encoded
|
||||
pub fn linear_to_srgb(v: f32) -> f32 {
|
||||
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Plain text on the graph canvas
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Comment {
|
||||
pub id: u64,
|
||||
pub text: String,
|
||||
pub pos: [f32; 2],
|
||||
#[serde(default = "comment_size")]
|
||||
pub size: [f32; 2],
|
||||
}
|
||||
|
||||
fn comment_size() -> [f32; 2] {
|
||||
[180.0, 70.0]
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/// Input/output semantics shared by node properties, SBS and texture exports
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ComponentUsage {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
impl ComponentUsage {
|
||||
pub const ANY: Self = Self { id: "any", label: "Any" };
|
||||
pub const ANY_INDEX: u32 = 9;
|
||||
|
||||
// Existing indices are saved in documents; append new entries without reordering
|
||||
pub const ALL: &'static [Self] = &[
|
||||
Self { id: "baseColor", label: "Base color" },
|
||||
Self { id: "normal", label: "Normal" },
|
||||
Self { id: "roughness", label: "Roughness" },
|
||||
Self { id: "metallic", label: "Metallic" },
|
||||
Self { id: "height", label: "Height" },
|
||||
Self { id: "ambientOcclusion", label: "Ambient occlusion" },
|
||||
Self { id: "emissive", label: "Emissive" },
|
||||
Self { id: "opacity", label: "Opacity" },
|
||||
Self { id: "specular", label: "Specular" },
|
||||
Self::ANY,
|
||||
Self { id: "diffuse", label: "Diffuse" },
|
||||
Self { id: "glossiness", label: "Glossiness" },
|
||||
Self { id: "specularLevel", label: "Specular level" },
|
||||
Self { id: "specularEdgeColor", label: "Specular edge color" },
|
||||
Self { id: "anisotropyLevel", label: "Anisotropy level" },
|
||||
Self { id: "anisotropyAngle", label: "Anisotropy angle" },
|
||||
Self { id: "IOR", label: "Index of refraction" },
|
||||
Self { id: "scattering", label: "Scattering" },
|
||||
Self { id: "scatteringColor", label: "Scattering color" },
|
||||
Self { id: "scatteringDistance", label: "Scattering distance" },
|
||||
Self { id: "scatteringDistanceScale", label: "Scattering distance scale" },
|
||||
Self { id: "transmissive", label: "Transmissive" },
|
||||
Self { id: "translucency", label: "Translucency" },
|
||||
Self { id: "absorptionColor", label: "Absorption color" },
|
||||
Self { id: "absorptionDistance", label: "Absorption distance" },
|
||||
Self { id: "coatOpacity", label: "Coat opacity" },
|
||||
Self { id: "coatColor", label: "Coat color" },
|
||||
Self { id: "coatRoughness", label: "Coat roughness" },
|
||||
Self { id: "coatSpecularLevel", label: "Coat specular level" },
|
||||
Self { id: "coatNormal", label: "Coat normal" },
|
||||
Self { id: "coatIOR", label: "Coat index of refraction" },
|
||||
Self { id: "sheenOpacity", label: "Sheen opacity" },
|
||||
Self { id: "sheenColor", label: "Sheen color" },
|
||||
Self { id: "sheenRoughness", label: "Sheen roughness" },
|
||||
Self { id: "reflection", label: "Reflection" },
|
||||
Self { id: "displacement", label: "Displacement" },
|
||||
Self { id: "ambient", label: "Ambient" },
|
||||
Self { id: "mask", label: "Mask" },
|
||||
Self { id: "blendingmask", label: "Blending mask" },
|
||||
Self { id: "bump", label: "Bump" },
|
||||
Self { id: "user0", label: "User 0" },
|
||||
Self { id: "user1", label: "User 1" },
|
||||
Self { id: "user2", label: "User 2" },
|
||||
Self { id: "user3", label: "User 3" },
|
||||
Self { id: "user4", label: "User 4" },
|
||||
Self { id: "user5", label: "User 5" },
|
||||
Self { id: "user6", label: "User 6" },
|
||||
Self { id: "user7", label: "User 7" },
|
||||
];
|
||||
|
||||
pub const LABELS: &'static [&'static str] = &{
|
||||
let mut labels = [""; Self::ALL.len()];
|
||||
let mut index = 0;
|
||||
while index < labels.len() {
|
||||
labels[index] = Self::ALL[index].label;
|
||||
index += 1;
|
||||
}
|
||||
labels
|
||||
};
|
||||
|
||||
pub fn from_index(index: u32) -> Self {
|
||||
Self::ALL.get(index as usize).copied().unwrap_or(Self::ANY)
|
||||
}
|
||||
|
||||
pub fn index(id: &str) -> u32 {
|
||||
Self::ALL.iter().position(|usage| usage.id.eq_ignore_ascii_case(id.trim())).map_or(Self::ANY_INDEX, |index| index as u32)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::NodeId;
|
||||
|
||||
/// A link from an output port to an input port
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Connection {
|
||||
pub from: NodeId,
|
||||
pub from_port: String,
|
||||
pub to: NodeId,
|
||||
pub to_port: String,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CoreError {
|
||||
#[error("no node {0}")]
|
||||
NoNode(u64),
|
||||
#[error("no graph {0}")]
|
||||
NoGraph(usize),
|
||||
#[error("that connection would make a cycle")]
|
||||
Cycle,
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::CurvePoint;
|
||||
|
||||
/// A monotone tone curve through sorted control points (linear when it has two points)
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Curve {
|
||||
pub points: Vec<CurvePoint>,
|
||||
}
|
||||
|
||||
impl Default for Curve {
|
||||
fn default() -> Self {
|
||||
Curve { points: vec![CurvePoint::new(0.0, 0.0), CurvePoint::new(1.0, 1.0)] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
pub fn eval(&self, x: f32) -> f32 {
|
||||
let Some(first) = self.points.first() else { return x };
|
||||
if x <= first.x {
|
||||
return first.y;
|
||||
}
|
||||
let Some(index) = self.points.windows(2).position(|points| x <= points[1].x) else {
|
||||
return self.points.last().map_or(x, |point| point.y);
|
||||
};
|
||||
|
||||
let Some([start, control_left, control_right, end]) = self.segment(index) else { return x };
|
||||
let bezier = |axis: usize, t: f32| {
|
||||
let inverse = 1.0 - t;
|
||||
inverse.powi(3) * start[axis] + 3.0 * inverse.powi(2) * t * control_left[axis] + 3.0 * inverse * t * t * control_right[axis] + t.powi(3) * end[axis]
|
||||
};
|
||||
|
||||
let (mut low, mut high) = (0.0, 1.0);
|
||||
for _ in 0..24 {
|
||||
let middle = (low + high) * 0.5;
|
||||
if bezier(0, middle) < x {
|
||||
low = middle;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
bezier(1, (low + high) * 0.5)
|
||||
}
|
||||
|
||||
pub fn segment(&self, index: usize) -> Option<[[f32; 2]; 4]> {
|
||||
let left = self.points.get(index)?;
|
||||
let right = self.points.get(index.checked_add(1)?)?;
|
||||
let span = (right.x - left.x).max(1e-6);
|
||||
let slope = |index: usize| {
|
||||
let left = self.points.get(index.saturating_sub(1));
|
||||
let right = self.points.get((index + 1).min(self.points.len().saturating_sub(1)));
|
||||
match (left, right) {
|
||||
(Some(left), Some(right)) if (right.x - left.x).abs() > 1e-6 => (right.y - left.y) / (right.x - left.x),
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
|
||||
let secant = (right.y - left.y) / span;
|
||||
let mut slopes = [slope(index), slope(index + 1)];
|
||||
if secant == 0.0 {
|
||||
slopes = [0.0; 2];
|
||||
} else {
|
||||
for slope in &mut slopes {
|
||||
if *slope * secant < 0.0 {
|
||||
*slope = 0.0;
|
||||
}
|
||||
}
|
||||
let length_squared = (slopes[0] / secant).powi(2) + (slopes[1] / secant).powi(2);
|
||||
if length_squared > 9.0 {
|
||||
slopes = slopes.map(|slope| slope * 3.0 / length_squared.sqrt());
|
||||
}
|
||||
}
|
||||
|
||||
let left_handle = left.right.unwrap_or([left.x + span / 3.0, left.y + slopes[0] * span / 3.0]);
|
||||
let right_handle = right.left.unwrap_or([right.x - span / 3.0, right.y - slopes[1] * span / 3.0]);
|
||||
Some([[left.x, left.y], left_handle, right_handle, [right.x, right.y]])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One control point of a [`Curve`]: position and value, both 0..1
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CurvePoint {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub left: Option<[f32; 2]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub right: Option<[f32; 2]>,
|
||||
}
|
||||
|
||||
impl CurvePoint {
|
||||
pub fn new(x: f32, y: f32) -> Self {
|
||||
Self { x, y, left: None, right: None }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Value;
|
||||
|
||||
/// The kind of value an exposed graph input carries
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExposedParameter {
|
||||
/// Identifier, unique in the graph
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub group: String,
|
||||
pub default: Value,
|
||||
#[serde(default)]
|
||||
pub min: f32,
|
||||
#[serde(default = "one")]
|
||||
pub max: f32,
|
||||
/// Labels when the value is an enum
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub options: Vec<String>,
|
||||
}
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A titled, colored rectangle behind a group of nodes
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Frame {
|
||||
pub id: u64,
|
||||
pub title: String,
|
||||
#[serde(default = "default_title_visible")]
|
||||
pub title_visible: bool,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub description: String,
|
||||
/// `[x, y, width, height]` in graph space
|
||||
pub rect: [f32; 4],
|
||||
/// Linear RGBA (alpha is the fill opacity)
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
|
||||
fn default_title_visible() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub fn contains_position(&self, position: [f32; 2]) -> bool {
|
||||
let [x, y, width, height] = self.rect;
|
||||
position[0] >= x && position[1] >= y && position[0] <= x + width && position[1] <= y + height
|
||||
}
|
||||
|
||||
pub fn contains_rect(&self, rect: [f32; 4]) -> bool {
|
||||
self.contains_position([rect[0], rect[1]]) && self.contains_position([rect[0] + rect[2], rect[1] + rect[3]])
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
//! Function graphs: small typed expression graphs evaluated per pixel (pixel processor), once
|
||||
//! per cook (value processor) or to compute a parameter dynamically. The data lives here; the
|
||||
//! evaluator is `materialcraft_nodes::function`.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Value;
|
||||
|
||||
/// A node in a function graph.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FnNode {
|
||||
pub id: u32,
|
||||
/// Operation id, e.g. `const_float`, `add`, `sample_gray`, `get_float2` (see the evaluator's
|
||||
/// catalog for the full list).
|
||||
pub op: String,
|
||||
/// Upstream node per input slot, in the op's slot order.
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Option<u32>>,
|
||||
/// The constant (`const_*`), the variable name (`get_*`) or the input index (`sample_*`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub value: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub pos: [f32; 2],
|
||||
}
|
||||
|
||||
/// A function graph: nodes plus the id of the node whose value is the result.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FnGraph {
|
||||
pub nodes: Vec<FnNode>,
|
||||
#[serde(default)]
|
||||
pub output: Option<u32>,
|
||||
}
|
||||
|
||||
impl FnGraph {
|
||||
pub fn node(&self, id: u32) -> Option<&FnNode> {
|
||||
self.nodes.iter().find(|n| n.id == id)
|
||||
}
|
||||
|
||||
fn next_id(&self) -> u32 {
|
||||
self.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1)
|
||||
}
|
||||
|
||||
/// Append a node and return its id.
|
||||
pub fn add(&mut self, op: &str, inputs: &[u32], value: Option<Value>) -> u32 {
|
||||
let id = self.next_id();
|
||||
let x = self.nodes.len() as f32 * 140.0;
|
||||
self.nodes.push(FnNode { id, op: op.into(), inputs: inputs.iter().map(|i| Some(*i)).collect(), value, pos: [x, 0.0] });
|
||||
id
|
||||
}
|
||||
|
||||
/// A graph returning one constant.
|
||||
pub fn constant(v: Value) -> FnGraph {
|
||||
let op = match &v {
|
||||
Value::Float(_) => "const_float",
|
||||
Value::Float2(_) => "const_float2",
|
||||
Value::Float3(_) => "const_float3",
|
||||
Value::Float4(_) | Value::Color(_) => "const_float4",
|
||||
Value::Int(_) | Value::Enum(_) => "const_int",
|
||||
Value::Bool(_) => "const_bool",
|
||||
_ => "const_float",
|
||||
};
|
||||
let mut g = FnGraph::default();
|
||||
let id = g.add(op, &[], Some(v));
|
||||
g.output = Some(id);
|
||||
g
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Value;
|
||||
|
||||
use crate::FunctionNode;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionGraph {
|
||||
pub nodes: Vec<FunctionNode>,
|
||||
#[serde(default)]
|
||||
pub output: Option<u32>,
|
||||
}
|
||||
|
||||
impl FunctionGraph {
|
||||
pub fn node(&self, id: u32) -> Option<&FunctionNode> {
|
||||
self.nodes.iter().find(|node| node.id == id)
|
||||
}
|
||||
|
||||
pub fn next_id(&self) -> u32 {
|
||||
let maximum = self.nodes.iter().map(|node| node.id).max().unwrap_or(0);
|
||||
if let Some(next) = maximum.checked_add(1) {
|
||||
return next;
|
||||
}
|
||||
|
||||
(1..=u32::MAX).find(|id| self.node(*id).is_none()).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn add(&mut self, operation: &str, inputs: &[u32], value: Option<Value>) -> u32 {
|
||||
let id = self.next_id();
|
||||
let horizontal_position = self.nodes.len() as f32 * 140.0;
|
||||
let node =
|
||||
FunctionNode { id, type_code: 0, op: operation.into(), inputs: inputs.iter().copied().map(Some).collect(), value, pos: [horizontal_position, 0.0] };
|
||||
|
||||
self.nodes.push(node);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn constant(value: Value) -> FunctionGraph {
|
||||
let mut graph = FunctionGraph::default();
|
||||
graph.output = Some(graph.add_constant(value));
|
||||
graph
|
||||
}
|
||||
|
||||
pub fn add_constant(&mut self, value: Value) -> u32 {
|
||||
let operation = match &value {
|
||||
Value::Float(_) => "const_float1",
|
||||
Value::Float2(_) => "const_float2",
|
||||
Value::Float3(_) => "const_float3",
|
||||
Value::Float4(_) | Value::Color(_) => "const_float4",
|
||||
Value::Int(_) | Value::Enum(_) => "const_int1",
|
||||
Value::Int2(_) => "const_int2",
|
||||
Value::Int3(_) => "const_int3",
|
||||
Value::Int4(_) => "const_int4",
|
||||
Value::Text(_) => "const_string",
|
||||
Value::Bool(_) => "const_bool",
|
||||
_ => "const_float1",
|
||||
};
|
||||
|
||||
let value = match value {
|
||||
Value::Color(color) => Value::Float4(color),
|
||||
Value::Enum(index) => Value::Int(index.min(i32::MAX as u32) as i32),
|
||||
value => value,
|
||||
};
|
||||
|
||||
self.add(operation, &[], Some(value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Value;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionNode {
|
||||
pub id: u32,
|
||||
// Zero requests type inference
|
||||
#[serde(default)]
|
||||
pub type_code: u32,
|
||||
pub op: String,
|
||||
// Slots follow the native operation's connector order
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Option<u32>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub value: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub pos: [f32; 2],
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::GradientKey;
|
||||
|
||||
/// A color ramp (gradient map)
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Gradient {
|
||||
pub keys: Vec<GradientKey>,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
fn default() -> Self {
|
||||
Gradient { keys: vec![GradientKey::new(0.0, [0.0, 0.0, 0.0, 1.0]), GradientKey::new(1.0, [1.0, 1.0, 1.0, 1.0])] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
/// Linear interpolation between the sorted keys
|
||||
pub fn eval(&self, t: f32) -> [f32; 4] {
|
||||
let k = &self.keys;
|
||||
let Some(first) = k.first() else { return [t, t, t, 1.0] };
|
||||
if t <= first.pos {
|
||||
return first.color;
|
||||
}
|
||||
for w in k.windows(2) {
|
||||
if t <= w[1].pos {
|
||||
let span = (w[1].pos - w[0].pos).max(1e-6);
|
||||
let midpoint = w[0].midpoint.clamp(0.001, 0.999);
|
||||
let f = ((t - w[0].pos) / span).clamp(0.0, 1.0).powf(0.5_f32.ln() / midpoint.ln());
|
||||
let (a, b) = (w[0].color, w[1].color);
|
||||
return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f];
|
||||
}
|
||||
}
|
||||
k.last().map_or([t, t, t, 1.0], |l| l.color)
|
||||
}
|
||||
|
||||
/// Keys sorted by position (call after editing)
|
||||
pub fn sort(&mut self) {
|
||||
self.keys.sort_by(|a, b| a.pos.total_cmp(&b.pos));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One stop of a [`Gradient`]: position 0..1 and linear RGBA
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GradientKey {
|
||||
pub pos: f32,
|
||||
pub color: [f32; 4],
|
||||
#[serde(default = "midpoint")]
|
||||
pub midpoint: f32,
|
||||
}
|
||||
|
||||
fn midpoint() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
impl GradientKey {
|
||||
pub fn new(pos: f32, color: [f32; 4]) -> Self {
|
||||
Self { pos, color, midpoint: 0.5 }
|
||||
}
|
||||
}
|
||||
+29
-306
@@ -1,254 +1,17 @@
|
||||
//! Graphs: nodes, connections, frames, comments, navigation pins and exposed inputs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{CoreError, Result, Value};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct NodeId(pub u64);
|
||||
|
||||
/// How a node's output size follows its surroundings ("Output size" base parameter).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SizeMode {
|
||||
/// The size of the main (first connected) input; the graph size when none is connected.
|
||||
#[default]
|
||||
RelativeToInput,
|
||||
/// The graph ("parent") size.
|
||||
RelativeToParent,
|
||||
/// `offset` is the absolute log2 size (e.g. 10 = 1024 px).
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// The output bit depth ("Output format").
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum OutputFormat {
|
||||
/// The main input's format; 16 bits for generators.
|
||||
#[default]
|
||||
Inherit,
|
||||
U8,
|
||||
U16,
|
||||
F16,
|
||||
F32,
|
||||
}
|
||||
|
||||
impl OutputFormat {
|
||||
pub const ALL: [OutputFormat; 5] = [OutputFormat::Inherit, OutputFormat::U8, OutputFormat::U16, OutputFormat::F16, OutputFormat::F32];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
OutputFormat::Inherit => "Relative to input",
|
||||
OutputFormat::U8 => "8 bits per channel",
|
||||
OutputFormat::U16 => "16 bits per channel",
|
||||
OutputFormat::F16 => "16 bits per channel float (HDR)",
|
||||
OutputFormat::F32 => "32 bits per channel float (HDR)",
|
||||
}
|
||||
}
|
||||
|
||||
/// The suffix of a node's size label: `8`, `16`, `16F`, `32F`.
|
||||
pub fn bits(self) -> &'static str {
|
||||
match self {
|
||||
OutputFormat::Inherit | OutputFormat::U16 => "16",
|
||||
OutputFormat::U8 => "8",
|
||||
OutputFormat::F16 => "16F",
|
||||
OutputFormat::F32 => "32F",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters every node has ("Base parameters").
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct BaseParams {
|
||||
pub size_mode: SizeMode,
|
||||
/// log2 offset per axis (relative modes) or log2 size (absolute).
|
||||
pub size: [i32; 2],
|
||||
pub format: OutputFormat,
|
||||
/// Added to the graph's random seed for this node.
|
||||
pub seed: i32,
|
||||
/// Whether sampling wraps at the edges (horizontal, vertical).
|
||||
pub tiling: [bool; 2],
|
||||
}
|
||||
|
||||
impl Default for BaseParams {
|
||||
fn default() -> Self {
|
||||
BaseParams { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] }
|
||||
}
|
||||
}
|
||||
|
||||
/// A node instance: a catalog definition (`def`) with parameter overrides.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Node {
|
||||
pub id: NodeId,
|
||||
/// Catalog id, e.g. `blend`, `perlin_noise`, `output`, `input_color`, `graph_instance`.
|
||||
pub def: String,
|
||||
/// User label; empty = the definition's label.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub label: String,
|
||||
/// Graph-space position of the node's top-left corner.
|
||||
pub pos: [f32; 2],
|
||||
/// Values that differ from the catalog defaults.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub params: BTreeMap<String, Value>,
|
||||
/// Parameters driven by a graph input (param id → exposed input id).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub bindings: BTreeMap<String, String>,
|
||||
/// Dynamic parameters: param id → a function graph computing its value from the graph's
|
||||
/// inputs at cook time.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub functions: BTreeMap<String, crate::function::FnGraph>,
|
||||
#[serde(default)]
|
||||
pub base: BaseParams,
|
||||
/// A disabled node passes its first input through.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub disabled: bool,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
pub fn new(id: NodeId, def: &str, pos: [f32; 2]) -> Node {
|
||||
Node {
|
||||
id,
|
||||
def: def.into(),
|
||||
label: String::new(),
|
||||
pos,
|
||||
params: BTreeMap::new(),
|
||||
bindings: BTreeMap::new(),
|
||||
functions: BTreeMap::new(),
|
||||
base: BaseParams::default(),
|
||||
disabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The definition id of a placeholder for a node MaterialCraft does not have (a library node or
|
||||
/// atomic filter named in an SBS file). The node keeps its wires and the data needed to write it
|
||||
/// back; its ports come from [`missing_ports`] and it cooks to a soft error.
|
||||
pub const MISSING_NODE: &str = "missing_node";
|
||||
|
||||
/// The ports of a [`MISSING_NODE`] placeholder: input ids, and output ids with whether each is
|
||||
/// grayscale. They are stored as comma-separated text in its `inputs` and `outputs` parameters
|
||||
/// (`outputs` entries are `id` or `id:gray`).
|
||||
pub fn missing_ports(node: &Node) -> (Vec<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")]
|
||||
pub struct Connection {
|
||||
pub from: NodeId,
|
||||
pub from_port: String,
|
||||
pub to: NodeId,
|
||||
pub to_port: String,
|
||||
}
|
||||
|
||||
/// A titled, colored rectangle behind a group of nodes.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Frame {
|
||||
pub id: u64,
|
||||
pub title: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub description: String,
|
||||
/// `[x, y, width, height]` in graph space.
|
||||
pub rect: [f32; 4],
|
||||
/// Linear RGBA (alpha is the fill opacity).
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
|
||||
/// A sticky note on the canvas.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Comment {
|
||||
pub id: u64,
|
||||
pub text: String,
|
||||
pub pos: [f32; 2],
|
||||
#[serde(default = "comment_size")]
|
||||
pub size: [f32; 2],
|
||||
}
|
||||
|
||||
fn comment_size() -> [f32; 2] {
|
||||
[180.0, 70.0]
|
||||
}
|
||||
|
||||
/// A named bookmark on the canvas (Previous/Next pin).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Pin {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub pos: [f32; 2],
|
||||
}
|
||||
|
||||
/// The kind of value an exposed graph input carries.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExposedParam {
|
||||
/// Identifier, unique in the graph.
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub group: String,
|
||||
pub default: Value,
|
||||
#[serde(default)]
|
||||
pub min: f32,
|
||||
#[serde(default = "one")]
|
||||
pub max: f32,
|
||||
/// Labels when the value is an enum.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub options: Vec<String>,
|
||||
}
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
/// A named set of input values (graph presets).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Preset {
|
||||
pub name: String,
|
||||
pub values: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
/// Descriptive metadata ("Attributes").
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Attributes {
|
||||
pub category: String,
|
||||
pub description: String,
|
||||
pub author: String,
|
||||
pub tags: String,
|
||||
}
|
||||
|
||||
/// Whether a graph makes images or is a function.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GraphKind {
|
||||
#[default]
|
||||
Material,
|
||||
Function,
|
||||
}
|
||||
use crate::{Attributes, Comment, Connection, ExposedParameter, Frame, GraphKind, Node, NodeId, OutputFormat, Pin, Preset};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Graph {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub kind: GraphKind,
|
||||
pub function: Option<crate::FunctionGraph>,
|
||||
pub nodes: Vec<Node>,
|
||||
pub connections: Vec<Connection>,
|
||||
#[serde(default)]
|
||||
@@ -257,31 +20,31 @@ pub struct Graph {
|
||||
pub comments: Vec<Comment>,
|
||||
#[serde(default)]
|
||||
pub pins: Vec<Pin>,
|
||||
/// log2 of the graph ("parent") size per axis.
|
||||
/// log2 of the graph ("parent") size per axis
|
||||
pub size: [u32; 2],
|
||||
#[serde(default)]
|
||||
pub format: OutputFormat,
|
||||
#[serde(default)]
|
||||
pub seed: i32,
|
||||
#[serde(default)]
|
||||
pub exposed: Vec<ExposedParam>,
|
||||
/// Current values of the exposed inputs (missing = default).
|
||||
pub exposed: Vec<ExposedParameter>,
|
||||
/// Current values of the exposed inputs (missing = default)
|
||||
#[serde(default)]
|
||||
pub inputs: BTreeMap<String, Value>,
|
||||
/// Named sets of input values.
|
||||
/// Named sets of input values
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub presets: Vec<Preset>,
|
||||
/// Preview images of the graph's input nodes: identifier → bitmap resource (a mesh map
|
||||
/// baked in TextureCraft, say). Instances feed their inputs from their ports instead.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub input_images: BTreeMap<String, String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub input_images_linear: BTreeSet<String>,
|
||||
#[serde(default)]
|
||||
pub attributes: Attributes,
|
||||
/// The id the next node, frame, comment or pin gets.
|
||||
/// The id the next node, frame, comment or pin gets
|
||||
pub next_id: u64,
|
||||
}
|
||||
|
||||
/// Smallest and largest graph size, as log2 (16 px .. 8192 px).
|
||||
/// Smallest and largest graph size, as log2 (16 px .. 8192 px)
|
||||
pub const MIN_SIZE_LOG2: u32 = 4;
|
||||
pub const MAX_SIZE_LOG2: u32 = 13;
|
||||
|
||||
@@ -289,7 +52,7 @@ impl Graph {
|
||||
pub fn new(name: &str) -> Graph {
|
||||
Graph {
|
||||
name: name.into(),
|
||||
kind: GraphKind::Material,
|
||||
function: None,
|
||||
nodes: Vec::new(),
|
||||
connections: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
@@ -302,11 +65,16 @@ impl Graph {
|
||||
inputs: BTreeMap::new(),
|
||||
presets: Vec::new(),
|
||||
input_images: BTreeMap::new(),
|
||||
input_images_linear: BTreeSet::new(),
|
||||
attributes: Attributes::default(),
|
||||
next_id: 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> GraphKind {
|
||||
if self.function.is_some() { GraphKind::Function } else { GraphKind::Material }
|
||||
}
|
||||
|
||||
pub fn alloc_id(&mut self) -> u64 {
|
||||
let id = self.next_id;
|
||||
self.next_id = self.next_id.saturating_add(1);
|
||||
@@ -321,21 +89,19 @@ impl Graph {
|
||||
self.nodes.iter_mut().find(|n| n.id == id).ok_or(CoreError::NoNode(id.0))
|
||||
}
|
||||
|
||||
/// Add a node of definition `def` at `pos`; returns its id.
|
||||
/// Add a node of definition `def` at `pos`; returns its id
|
||||
pub fn add_node(&mut self, def: &str, pos: [f32; 2]) -> NodeId {
|
||||
let id = NodeId(self.alloc_id());
|
||||
self.nodes.push(Node::new(id, def, pos));
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove nodes and every connection touching them.
|
||||
/// Remove nodes and every connection touching them
|
||||
pub fn remove_nodes(&mut self, ids: &[NodeId]) {
|
||||
self.nodes.retain(|n| !ids.contains(&n.id));
|
||||
self.connections.retain(|c| !ids.contains(&c.from) && !ids.contains(&c.to));
|
||||
}
|
||||
|
||||
/// Connect `from.from_port` → `to.to_port`, replacing whatever fed that input. Refuses
|
||||
/// connections that would make a cycle.
|
||||
pub fn connect(&mut self, from: NodeId, from_port: &str, to: NodeId, to_port: &str) -> Result<()> {
|
||||
self.node(from)?;
|
||||
self.node(to)?;
|
||||
@@ -353,12 +119,12 @@ impl Graph {
|
||||
before != self.connections.len()
|
||||
}
|
||||
|
||||
/// The connection feeding `to.to_port`.
|
||||
/// The connection feeding `to.to_port`
|
||||
pub fn input_of(&self, to: NodeId, to_port: &str) -> Option<&Connection> {
|
||||
self.connections.iter().find(|c| c.to == to && c.to_port == to_port)
|
||||
}
|
||||
|
||||
/// Whether `b` is downstream of (or equal to) `a`.
|
||||
/// Whether `b` is downstream of (or equal to) `a`
|
||||
pub fn reaches(&self, a: NodeId, b: NodeId) -> bool {
|
||||
let mut stack = vec![a];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
@@ -374,69 +140,26 @@ impl Graph {
|
||||
false
|
||||
}
|
||||
|
||||
/// Nodes in dependency order (inputs before the nodes they feed). Nodes on a cycle (only
|
||||
/// possible in a hand-edited file) are left out.
|
||||
pub fn topo_order(&self) -> Vec<NodeId> {
|
||||
let mut indeg: BTreeMap<NodeId, usize> = self.nodes.iter().map(|n| (n.id, 0)).collect();
|
||||
for c in &self.connections {
|
||||
if let Some(d) = indeg.get_mut(&c.to)
|
||||
&& self.nodes.iter().any(|n| n.id == c.from)
|
||||
{
|
||||
*d += 1;
|
||||
}
|
||||
}
|
||||
let mut ready: Vec<NodeId> = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect();
|
||||
let mut out = Vec::with_capacity(self.nodes.len());
|
||||
while let Some(n) = ready.pop() {
|
||||
out.push(n);
|
||||
for c in self.connections.iter().filter(|c| c.from == n) {
|
||||
if let Some(d) = indeg.get_mut(&c.to) {
|
||||
*d = d.saturating_sub(1);
|
||||
if *d == 0 {
|
||||
ready.push(c.to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::GraphIndex::new(self).topo_order()
|
||||
}
|
||||
|
||||
/// Every node upstream of `id` (not including it).
|
||||
/// Every node upstream of `id` (not including it)
|
||||
pub fn upstream(&self, id: NodeId) -> Vec<NodeId> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![id];
|
||||
while let Some(n) = stack.pop() {
|
||||
for c in self.connections.iter().filter(|c| c.to == n) {
|
||||
if !out.contains(&c.from) {
|
||||
out.push(c.from);
|
||||
stack.push(c.from);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::GraphIndex::new(self).upstream(id)
|
||||
}
|
||||
|
||||
/// Every node downstream of `id` (not including it).
|
||||
/// Every node downstream of `id` (not including it)
|
||||
pub fn downstream(&self, id: NodeId) -> Vec<NodeId> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![id];
|
||||
while let Some(n) = stack.pop() {
|
||||
for c in self.connections.iter().filter(|c| c.from == n) {
|
||||
if !out.contains(&c.to) {
|
||||
out.push(c.to);
|
||||
stack.push(c.to);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::GraphIndex::new(self).downstream(id)
|
||||
}
|
||||
|
||||
/// The value of exposed input `id` (its default when unset).
|
||||
/// The value of exposed input `id` (its default when unset)
|
||||
pub fn input_value(&self, id: &str) -> Option<&Value> {
|
||||
self.inputs.get(id).or_else(|| self.exposed.iter().find(|e| e.id == id).map(|e| &e.default))
|
||||
}
|
||||
|
||||
/// Graph size in pixels.
|
||||
/// Graph size in pixels
|
||||
pub fn size_px(&self) -> [u32; 2] {
|
||||
[1 << self.size[0].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), 1 << self.size[1].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)]
|
||||
}
|
||||
@@ -444,7 +167,7 @@ impl Graph {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::*;
|
||||
|
||||
#[test]
|
||||
fn connect_refuses_cycles_and_replaces_inputs() {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::{Connection, Graph, Node, NodeId};
|
||||
|
||||
/// Borrowed lookups for one graph operation, rebuilt when the graph changes
|
||||
pub struct GraphIndex<'a> {
|
||||
nodes: BTreeMap<NodeId, &'a Node>,
|
||||
incoming: BTreeMap<NodeId, Vec<&'a Connection>>,
|
||||
outgoing: BTreeMap<NodeId, Vec<&'a Connection>>,
|
||||
}
|
||||
|
||||
impl<'a> GraphIndex<'a> {
|
||||
pub fn new(graph: &'a Graph) -> Self {
|
||||
let mut nodes = BTreeMap::new();
|
||||
for node in &graph.nodes {
|
||||
nodes.entry(node.id).or_insert(node);
|
||||
}
|
||||
|
||||
let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
let mut outgoing: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for connection in &graph.connections {
|
||||
incoming.entry(connection.to).or_default().push(connection);
|
||||
outgoing.entry(connection.from).or_default().push(connection);
|
||||
}
|
||||
|
||||
Self { nodes, incoming, outgoing }
|
||||
}
|
||||
|
||||
pub fn node(&self, id: NodeId) -> Option<&'a Node> {
|
||||
self.nodes.get(&id).copied()
|
||||
}
|
||||
|
||||
pub fn incoming(&self, id: NodeId) -> &[&'a Connection] {
|
||||
self.incoming.get(&id).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
pub fn input_of(&self, id: NodeId, port: &str) -> Option<&'a Connection> {
|
||||
self.incoming(id).iter().copied().find(|connection| connection.to_port == port)
|
||||
}
|
||||
|
||||
pub fn topo_order(&self) -> Vec<NodeId> {
|
||||
let mut degrees: BTreeMap<_, _> = self.nodes.keys().map(|id| (*id, 0usize)).collect();
|
||||
for (id, connections) in &self.incoming {
|
||||
if let Some(degree) = degrees.get_mut(id) {
|
||||
*degree = connections.iter().filter(|connection| self.nodes.contains_key(&connection.from)).count();
|
||||
}
|
||||
}
|
||||
|
||||
let mut ready: Vec<_> = degrees.iter().filter(|(_, degree)| **degree == 0).map(|(id, _)| *id).collect();
|
||||
let mut ordered = Vec::with_capacity(self.nodes.len());
|
||||
while let Some(id) = ready.pop() {
|
||||
ordered.push(id);
|
||||
for connection in self.outgoing.get(&id).into_iter().flatten() {
|
||||
if let Some(degree) = degrees.get_mut(&connection.to) {
|
||||
*degree = degree.saturating_sub(1);
|
||||
if *degree == 0 {
|
||||
ready.push(connection.to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ordered
|
||||
}
|
||||
|
||||
pub fn upstream(&self, id: NodeId) -> Vec<NodeId> {
|
||||
self.connected(id, true)
|
||||
}
|
||||
|
||||
pub fn downstream(&self, id: NodeId) -> Vec<NodeId> {
|
||||
self.connected(id, false)
|
||||
}
|
||||
|
||||
pub fn required_nodes(&self, roots: &[NodeId]) -> BTreeSet<NodeId> {
|
||||
let mut required: BTreeSet<_> = roots.iter().copied().collect();
|
||||
let mut pending = roots.to_vec();
|
||||
while let Some(id) = pending.pop() {
|
||||
for connection in self.incoming(id) {
|
||||
if required.insert(connection.from) {
|
||||
pending.push(connection.from);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
required
|
||||
}
|
||||
|
||||
fn connected(&self, root: NodeId, upstream: bool) -> Vec<NodeId> {
|
||||
let adjacency = if upstream { &self.incoming } else { &self.outgoing };
|
||||
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut connected = Vec::new();
|
||||
let mut pending = vec![root];
|
||||
while let Some(id) = pending.pop() {
|
||||
for connection in adjacency.get(&id).into_iter().flatten() {
|
||||
let next = if upstream { connection.from } else { connection.to };
|
||||
|
||||
if visited.insert(next) {
|
||||
connected.push(next);
|
||||
pending.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
connected
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn traversal_preserves_document_order_and_dangling_edge_behavior() {
|
||||
let mut graph = Graph::new("Traversal");
|
||||
let first = graph.add_node("uniform", [0.0; 2]);
|
||||
let second = graph.add_node("dot", [0.0; 2]);
|
||||
let third = graph.add_node("blend", [0.0; 2]);
|
||||
let fourth = graph.add_node("dot", [0.0; 2]);
|
||||
for (from, to, port) in [(first, second, "input"), (first, third, "foreground"), (second, third, "background"), (NodeId(99), fourth, "input")] {
|
||||
graph.connections.push(Connection { from, from_port: "output".into(), to, to_port: port.into() });
|
||||
}
|
||||
let index = GraphIndex::new(&graph);
|
||||
assert_eq!(index.topo_order(), [fourth, first, second, third]);
|
||||
assert_eq!(index.upstream(third), [first, second]);
|
||||
assert_eq!(index.downstream(first), [second, third]);
|
||||
assert_eq!(index.required_nodes(&[third, fourth]), BTreeSet::from([first, second, third, fourth, NodeId(99)]));
|
||||
assert_eq!(index.input_of(third, "background").unwrap().from, second);
|
||||
|
||||
graph.connections.push(Connection { from: third, from_port: "output".into(), to: first, to_port: "input".into() });
|
||||
assert_eq!(GraphIndex::new(&graph).topo_order(), [fourth]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Whether a graph makes images or is a function
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GraphKind {
|
||||
#[default]
|
||||
Material,
|
||||
Function,
|
||||
}
|
||||
+71
-27
@@ -1,33 +1,77 @@
|
||||
//! # materialcraft-core
|
||||
//!
|
||||
//! The MaterialCraft document model, L0 (pure data, no I/O): a [`Package`] holds [`Graph`]s and
|
||||
//! [`Resource`]s; a graph holds [`Node`]s (catalog definitions with parameter overrides),
|
||||
//! [`Connection`]s between named ports, frames, comments, navigation pins and exposed inputs.
|
||||
//! Parameter values are [`Value`]s; function graphs ([`function::FnGraph`]) drive pixel and value
|
||||
//! processors.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod function;
|
||||
pub mod graph;
|
||||
pub mod package;
|
||||
pub mod value;
|
||||
mod attributes;
|
||||
mod base_parameters;
|
||||
mod color;
|
||||
mod comment;
|
||||
mod component_usage;
|
||||
mod connection;
|
||||
mod core_error;
|
||||
mod curve;
|
||||
mod curve_point;
|
||||
mod exposed_parameter;
|
||||
mod frame;
|
||||
mod function_graph;
|
||||
mod function_node;
|
||||
mod gradient;
|
||||
mod gradient_key;
|
||||
mod graph;
|
||||
mod graph_index;
|
||||
mod graph_kind;
|
||||
mod material_channel;
|
||||
mod missing_node;
|
||||
mod node;
|
||||
mod node_id;
|
||||
mod output_format;
|
||||
mod package;
|
||||
mod pattern_graph;
|
||||
mod pattern_node;
|
||||
mod pattern_node_kind;
|
||||
mod pin;
|
||||
mod preset;
|
||||
mod resource;
|
||||
mod resource_bytes;
|
||||
mod size_mode;
|
||||
mod value;
|
||||
mod value_type;
|
||||
|
||||
pub use graph::{
|
||||
Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat,
|
||||
Pin, Preset, SizeMode, missing_ports,
|
||||
};
|
||||
pub use package::{PACKAGE_EXT, Package, Resource};
|
||||
pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CoreError {
|
||||
#[error("no node {0}")]
|
||||
NoNode(u64),
|
||||
#[error("no graph {0}")]
|
||||
NoGraph(usize),
|
||||
#[error("that connection would make a cycle")]
|
||||
Cycle,
|
||||
}
|
||||
pub use attributes::Attributes;
|
||||
pub use base_parameters::BaseParameters;
|
||||
pub use color::{linear_to_srgb, parse_color, srgb_to_linear};
|
||||
pub use comment::Comment;
|
||||
pub use component_usage::ComponentUsage;
|
||||
pub use connection::Connection;
|
||||
pub use core_error::CoreError;
|
||||
pub use curve::Curve;
|
||||
pub use curve_point::CurvePoint;
|
||||
pub use exposed_parameter::ExposedParameter;
|
||||
pub use frame::Frame;
|
||||
pub use function_graph::FunctionGraph;
|
||||
pub use function_node::FunctionNode;
|
||||
pub use gradient::Gradient;
|
||||
pub use gradient_key::GradientKey;
|
||||
pub use graph::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2};
|
||||
pub use graph_index::GraphIndex;
|
||||
pub use graph_kind::GraphKind;
|
||||
pub use material_channel::MaterialChannel;
|
||||
pub use missing_node::{MISSING_NODE, missing_ports};
|
||||
pub use node::Node;
|
||||
pub use node_id::NodeId;
|
||||
pub use output_format::OutputFormat;
|
||||
pub use package::{PACKAGE_EXT, Package};
|
||||
pub use pattern_graph::PatternGraph;
|
||||
pub use pattern_node::PatternNode;
|
||||
pub use pattern_node_kind::PatternNodeKind;
|
||||
pub use pin::Pin;
|
||||
pub use preset::Preset;
|
||||
pub use resource::Resource;
|
||||
pub use resource_bytes::ResourceBytes;
|
||||
pub use size_mode::SizeMode;
|
||||
pub use value::Value;
|
||||
pub use value_type::ValueType;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, CoreError>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod value_tests;
|
||||
@@ -0,0 +1,50 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Texture channels supported by the material preview
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MaterialChannel {
|
||||
BaseColor,
|
||||
Normal,
|
||||
Roughness,
|
||||
Metallic,
|
||||
Height,
|
||||
AmbientOcclusion,
|
||||
Emissive,
|
||||
Opacity,
|
||||
}
|
||||
|
||||
impl MaterialChannel {
|
||||
pub const ALL: [Self; 8] =
|
||||
[Self::BaseColor, Self::Normal, Self::Roughness, Self::Metallic, Self::Height, Self::AmbientOcclusion, Self::Emissive, Self::Opacity];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::BaseColor => "baseColor",
|
||||
Self::Normal => "normal",
|
||||
Self::Roughness => "roughness",
|
||||
Self::Metallic => "metallic",
|
||||
Self::Height => "height",
|
||||
Self::AmbientOcclusion => "ambientOcclusion",
|
||||
Self::Emissive => "emissive",
|
||||
Self::Opacity => "opacity",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::BaseColor => "Base color",
|
||||
Self::Normal => "Normal",
|
||||
Self::Roughness => "Roughness",
|
||||
Self::Metallic => "Metallic",
|
||||
Self::Height => "Height",
|
||||
Self::AmbientOcclusion => "Ambient occlusion",
|
||||
Self::Emissive => "Emissive",
|
||||
Self::Opacity => "Opacity",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(id)).or_else(|| id.eq_ignore_ascii_case("diffuse").then_some(Self::BaseColor))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::Node;
|
||||
use crate::Value;
|
||||
|
||||
pub const MISSING_NODE: &str = "missing_node";
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Value;
|
||||
use crate::{BaseParameters, NodeId};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// A node instance: a catalog definition (`def`) with parameter overrides
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Node {
|
||||
pub id: NodeId,
|
||||
/// Catalog id, e.g. `blend`, `pixel_processor`, `output`, `input_color`, `graph_instance`
|
||||
pub def: String,
|
||||
/// User label; empty = the definition's label
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub label: String,
|
||||
/// Graph-space position of the node's top-left corner
|
||||
pub pos: [f32; 2],
|
||||
/// Values that differ from the catalog defaults
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub params: BTreeMap<String, Value>,
|
||||
/// Parameters driven by a graph input (param id → exposed input id)
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub bindings: BTreeMap<String, String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub functions: BTreeMap<String, crate::FunctionGraph>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub input_values: BTreeMap<String, crate::ValueType>,
|
||||
#[serde(default)]
|
||||
pub base: BaseParameters,
|
||||
/// A disabled node passes its first input through
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub disabled: bool,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
pub fn new(id: NodeId, def: &str, pos: [f32; 2]) -> Node {
|
||||
Node {
|
||||
id,
|
||||
def: def.into(),
|
||||
label: String::new(),
|
||||
pos,
|
||||
params: BTreeMap::new(),
|
||||
bindings: BTreeMap::new(),
|
||||
functions: BTreeMap::new(),
|
||||
input_values: BTreeMap::new(),
|
||||
base: BaseParameters::default(),
|
||||
disabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct NodeId(pub u64);
|
||||
@@ -0,0 +1,38 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The output bit depth ("Output format")
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum OutputFormat {
|
||||
/// The main input's format; 16 bits for generators
|
||||
#[default]
|
||||
Inherit,
|
||||
U8,
|
||||
U16,
|
||||
F16,
|
||||
F32,
|
||||
}
|
||||
|
||||
impl OutputFormat {
|
||||
pub const ALL: [OutputFormat; 5] = [OutputFormat::Inherit, OutputFormat::U8, OutputFormat::U16, OutputFormat::F16, OutputFormat::F32];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
OutputFormat::Inherit => "Relative to input",
|
||||
OutputFormat::U8 => "8 bits per channel",
|
||||
OutputFormat::U16 => "16 bits per channel",
|
||||
OutputFormat::F16 => "16 bits per channel float (HDR)",
|
||||
OutputFormat::F32 => "32 bits per channel float (HDR)",
|
||||
}
|
||||
}
|
||||
|
||||
/// The suffix of a node's size label: `8`, `16`, `16F`, `32F`
|
||||
pub fn bits(self) -> &'static str {
|
||||
match self {
|
||||
OutputFormat::Inherit | OutputFormat::U16 => "16",
|
||||
OutputFormat::U8 => "8",
|
||||
OutputFormat::F16 => "16F",
|
||||
OutputFormat::F32 => "32F",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,8 @@
|
||||
//! Packages: the document. A package holds graphs and the resources (bitmaps) they use.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::Resource;
|
||||
use crate::{CoreError, Graph, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{CoreError, Graph, Result};
|
||||
|
||||
/// The native package extension (a zip: `package.json` plus `resources/`).
|
||||
pub const PACKAGE_EXT: &str = "mcraft";
|
||||
|
||||
/// An embedded file: a bitmap a Bitmap node shows, or an SVG.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Resource {
|
||||
/// Unique name, referenced by nodes (`resource` parameter).
|
||||
pub name: String,
|
||||
/// File name inside the package's `resources/` folder.
|
||||
pub file: String,
|
||||
/// The file's bytes (stored in the zip, not in `package.json`).
|
||||
#[serde(skip)]
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
pub const PACKAGE_EXT: &str = "sbs";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Package {
|
||||
@@ -27,7 +10,7 @@ pub struct Package {
|
||||
pub graphs: Vec<Graph>,
|
||||
#[serde(default)]
|
||||
pub resources: Vec<Resource>,
|
||||
/// Format version of `package.json`.
|
||||
/// Format version of `package.json`
|
||||
#[serde(default = "version")]
|
||||
pub version: u32,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::{PatternNode, PatternNodeKind};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PatternGraph {
|
||||
pub nodes: Vec<PatternNode>,
|
||||
pub root: Option<u32>,
|
||||
}
|
||||
|
||||
impl PatternGraph {
|
||||
pub fn with_root(kind: PatternNodeKind) -> Self {
|
||||
Self {
|
||||
root: Some(1),
|
||||
nodes: vec![PatternNode { id: 1, kind, children: vec![None; kind.child_count()], parameters: BTreeMap::new(), position: [0.0; 2] }],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&mut self, kind: PatternNodeKind) -> Result<u32, String> {
|
||||
if self.nodes.len() >= 4096 {
|
||||
return Err("pattern graph exceeds the 4096-node limit".into());
|
||||
}
|
||||
|
||||
let mut occupied = [false; 4097];
|
||||
for node in &self.nodes {
|
||||
if let Some(slot) = occupied.get_mut(node.id.saturating_sub(1) as usize)
|
||||
&& node.id != 0
|
||||
{
|
||||
*slot = true;
|
||||
}
|
||||
}
|
||||
let id = occupied.iter().position(|occupied| !occupied).ok_or("no available pattern node id")? as u32 + 1;
|
||||
self.nodes.push(PatternNode {
|
||||
id,
|
||||
kind,
|
||||
children: vec![None; kind.child_count()],
|
||||
parameters: BTreeMap::new(),
|
||||
position: [self.nodes.len() as f32 * 160.0, 0.0],
|
||||
});
|
||||
self.root.get_or_insert(id);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.nodes.len() > 4096 {
|
||||
return Err("pattern graph exceeds the 4096-node limit".into());
|
||||
}
|
||||
|
||||
let nodes: BTreeMap<_, _> = self.nodes.iter().map(|node| (node.id, node)).collect();
|
||||
if nodes.len() != self.nodes.len() {
|
||||
return Err("duplicate pattern node ids".into());
|
||||
}
|
||||
if self.root.is_some_and(|root| !nodes.contains_key(&root)) {
|
||||
return Err("missing pattern root".into());
|
||||
}
|
||||
|
||||
let mut active = BTreeSet::new();
|
||||
let mut finished = BTreeSet::new();
|
||||
for root in &self.nodes {
|
||||
let mut pending = vec![(root.id, false)];
|
||||
while let Some((id, visited)) = pending.pop() {
|
||||
if finished.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let node = nodes.get(&id).ok_or_else(|| format!("missing pattern node {id}"))?;
|
||||
if node.children.len() != node.kind.child_count() {
|
||||
return Err(format!("{} requires {} child slots", node.kind.label(), node.kind.child_count()));
|
||||
}
|
||||
if visited {
|
||||
active.remove(&id);
|
||||
finished.insert(id);
|
||||
continue;
|
||||
}
|
||||
if !active.insert(id) {
|
||||
return Err(format!("pattern cycle at node {id}"));
|
||||
}
|
||||
|
||||
pending.push((id, true));
|
||||
pending.extend(node.children.iter().rev().flatten().map(|child| (*child, false)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn allocation_reuses_the_lowest_hole_and_ignores_out_of_range_ids() {
|
||||
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
|
||||
let template = graph.nodes[0].clone();
|
||||
graph.nodes = [0, 2, 4097, u32::MAX].map(|id| PatternNode { id, ..template.clone() }).to_vec();
|
||||
assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 1);
|
||||
assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 3);
|
||||
graph.nodes.retain(|node| node.id != 2);
|
||||
assert_eq!(graph.add(PatternNodeKind::Dot).unwrap(), 2);
|
||||
assert_eq!(graph.root, Some(1));
|
||||
|
||||
graph.nodes.resize(4096, template);
|
||||
let before = graph.clone();
|
||||
assert!(graph.add(PatternNodeKind::Dot).is_err());
|
||||
assert_eq!(graph, before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::{PatternNodeKind, Value};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PatternNode {
|
||||
pub id: u32,
|
||||
pub kind: PatternNodeKind,
|
||||
pub children: Vec<Option<u32>>,
|
||||
pub parameters: BTreeMap<String, Value>,
|
||||
pub position: [f32; 2],
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum PatternNodeKind {
|
||||
#[serde(rename = "paramset")]
|
||||
Quadrant,
|
||||
#[serde(rename = "markov2")]
|
||||
Switch,
|
||||
#[serde(rename = "addnode")]
|
||||
Iterate,
|
||||
#[serde(rename = "passthrough")]
|
||||
Dot,
|
||||
}
|
||||
|
||||
impl PatternNodeKind {
|
||||
pub const ALL: [Self; 4] = [Self::Quadrant, Self::Switch, Self::Iterate, Self::Dot];
|
||||
|
||||
pub fn native_id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Quadrant => "paramset",
|
||||
Self::Switch => "markov2",
|
||||
Self::Iterate => "addnode",
|
||||
Self::Dot => "passthrough",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Quadrant => "Quadrant",
|
||||
Self::Switch => "Switch",
|
||||
Self::Iterate => "Iterate",
|
||||
Self::Dot => "Dot",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn child_count(self) -> usize {
|
||||
match self {
|
||||
Self::Quadrant => 4,
|
||||
Self::Switch | Self::Iterate => 2,
|
||||
Self::Dot => 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn child_port(self, slot: usize) -> Option<&'static str> {
|
||||
if self == Self::Dot {
|
||||
return (slot == 0).then_some("output");
|
||||
}
|
||||
["output0", "output1", "output2", "output3"].get(..self.child_count())?.get(slot).copied()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A named bookmark on the canvas (Previous/Next pin)
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Pin {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub pos: [f32; 2],
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// A named set of input values (graph presets)
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Preset {
|
||||
pub name: String,
|
||||
pub values: BTreeMap<String, Value>,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
use crate::ResourceBytes;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// An embedded file: a bitmap a Bitmap node shows, or an SVG
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Resource {
|
||||
/// Unique name, referenced by nodes (`resource` parameter)
|
||||
pub name: String,
|
||||
/// File name inside the package's `resources/` folder
|
||||
pub file: String,
|
||||
/// The file's bytes (stored in the zip, not in `package.json`)
|
||||
#[serde(skip)]
|
||||
pub bytes: ResourceBytes,
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
/// A resource named `name`, stored as `file` in the package
|
||||
pub fn new(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes) -> Resource {
|
||||
Resource { name: name.into(), file: file.into(), bytes }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResourceBytes {
|
||||
bytes: Arc<Vec<u8>>,
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
impl ResourceBytes {
|
||||
/// Take ownership of `bytes` and hash them
|
||||
pub fn new(bytes: Vec<u8>) -> ResourceBytes {
|
||||
let mut h = DefaultHasher::new();
|
||||
bytes.hash(&mut h);
|
||||
ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) }
|
||||
}
|
||||
|
||||
/// The bytes
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
/// Number of bytes
|
||||
pub fn len(&self) -> usize {
|
||||
self.bytes.len()
|
||||
}
|
||||
|
||||
/// Whether there are no bytes
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bytes.is_empty()
|
||||
}
|
||||
|
||||
/// Hash of the whole content
|
||||
pub fn content_hash(&self) -> u64 {
|
||||
self.hash
|
||||
}
|
||||
|
||||
/// Whether both values share one allocation (cheap clones of one file)
|
||||
pub fn ptr_eq(&self, other: &ResourceBytes) -> bool {
|
||||
Arc::ptr_eq(&self.bytes, &other.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ResourceBytes {
|
||||
fn default() -> Self {
|
||||
ResourceBytes::new(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ResourceBytes {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.hash == other.hash && self.bytes == other.bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::*;
|
||||
|
||||
#[test]
|
||||
fn same_length_same_prefix_bytes_hash_differently() {
|
||||
let a = vec![7u8; 200];
|
||||
let mut b = a.clone();
|
||||
b[150] = 8;
|
||||
let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b));
|
||||
assert_eq!(a.len(), b.len());
|
||||
assert_ne!(a.content_hash(), b.content_hash());
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a node's output size follows its surroundings ("Output size" base parameter)
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SizeMode {
|
||||
/// The size of the main (first connected) input; the graph size when none is connected
|
||||
#[default]
|
||||
RelativeToInput,
|
||||
/// The graph ("parent") size
|
||||
RelativeToParent,
|
||||
/// `offset` is the absolute log2 size (e.g. 10 = 1024 px)
|
||||
Absolute,
|
||||
}
|
||||
+45
-208
@@ -1,126 +1,7 @@
|
||||
//! Parameter values: the typed data a node parameter, an exposed graph input or a function-graph
|
||||
//! constant holds.
|
||||
|
||||
use crate::{Curve, CurvePoint, Gradient, GradientKey, parse_color};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One control point of a [`Curve`]: position and value, both 0..1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CurvePoint {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
/// A monotone tone curve through sorted control points (linear when it has two points).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Curve {
|
||||
pub points: Vec<CurvePoint>,
|
||||
}
|
||||
|
||||
impl Default for Curve {
|
||||
fn default() -> Self {
|
||||
Curve { points: vec![CurvePoint { x: 0.0, y: 0.0 }, CurvePoint { x: 1.0, y: 1.0 }] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
/// Value at `x` (0..1): monotone cubic (Fritsch–Carlson) through the points, clamped ends.
|
||||
pub fn eval(&self, x: f32) -> f32 {
|
||||
let p = &self.points;
|
||||
let n = p.len();
|
||||
match n {
|
||||
0 => return x,
|
||||
1 => return p[0].y,
|
||||
_ => {}
|
||||
}
|
||||
if x <= p[0].x {
|
||||
return p[0].y;
|
||||
}
|
||||
if x >= p[n - 1].x {
|
||||
return p[n - 1].y;
|
||||
}
|
||||
let mut i = 0;
|
||||
while i + 2 < n && x > p[i + 1].x {
|
||||
i += 1;
|
||||
}
|
||||
let slope = |a: usize| {
|
||||
let (l, r) = (a.saturating_sub(1), (a + 1).min(n - 1));
|
||||
let dx = p[r].x - p[l].x;
|
||||
if dx.abs() < 1e-6 { 0.0 } else { (p[r].y - p[l].y) / dx }
|
||||
};
|
||||
let (a, b) = (p[i], p[i + 1]);
|
||||
let h = (b.x - a.x).max(1e-6);
|
||||
let d = (b.y - a.y) / h;
|
||||
let (mut m0, mut m1) = (slope(i), slope(i + 1));
|
||||
if d == 0.0 {
|
||||
m0 = 0.0;
|
||||
m1 = 0.0;
|
||||
} else {
|
||||
// Keep the segment monotone.
|
||||
if m0 * d < 0.0 {
|
||||
m0 = 0.0;
|
||||
}
|
||||
if m1 * d < 0.0 {
|
||||
m1 = 0.0;
|
||||
}
|
||||
let (al, be) = (m0 / d, m1 / d);
|
||||
let s = al * al + be * be;
|
||||
if s > 9.0 {
|
||||
let t = 3.0 / s.sqrt();
|
||||
m0 = t * al * d;
|
||||
m1 = t * be * d;
|
||||
}
|
||||
}
|
||||
let t = (x - a.x) / h;
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
(2.0 * t3 - 3.0 * t2 + 1.0) * a.y + (t3 - 2.0 * t2 + t) * h * m0 + (-2.0 * t3 + 3.0 * t2) * b.y + (t3 - t2) * h * m1
|
||||
}
|
||||
}
|
||||
|
||||
/// One stop of a [`Gradient`]: position 0..1 and linear RGBA.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GradientKey {
|
||||
pub pos: f32,
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
|
||||
/// A color ramp (gradient map).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Gradient {
|
||||
pub keys: Vec<GradientKey>,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
fn default() -> Self {
|
||||
Gradient { keys: vec![GradientKey { pos: 0.0, color: [0.0, 0.0, 0.0, 1.0] }, GradientKey { pos: 1.0, color: [1.0, 1.0, 1.0, 1.0] }] }
|
||||
}
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
/// Linear interpolation between the sorted keys.
|
||||
pub fn eval(&self, t: f32) -> [f32; 4] {
|
||||
let k = &self.keys;
|
||||
let Some(first) = k.first() else { return [t, t, t, 1.0] };
|
||||
if t <= first.pos {
|
||||
return first.color;
|
||||
}
|
||||
for w in k.windows(2) {
|
||||
if t <= w[1].pos {
|
||||
let span = (w[1].pos - w[0].pos).max(1e-6);
|
||||
let f = ((t - w[0].pos) / span).clamp(0.0, 1.0);
|
||||
let (a, b) = (w[0].color, w[1].color);
|
||||
return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f];
|
||||
}
|
||||
}
|
||||
k.last().map_or([t, t, t, 1.0], |l| l.color)
|
||||
}
|
||||
|
||||
/// Keys sorted by position (call after editing).
|
||||
pub fn sort(&mut self) {
|
||||
self.keys.sort_by(|a, b| a.pos.total_cmp(&b.pos));
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed parameter value.
|
||||
/// A typed parameter value
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "t", content = "v", rename_all = "camelCase")]
|
||||
pub enum Value {
|
||||
@@ -130,16 +11,19 @@ pub enum Value {
|
||||
Float4([f32; 4]),
|
||||
Int(i32),
|
||||
Int2([i32; 2]),
|
||||
Int3([i32; 3]),
|
||||
Int4([i32; 4]),
|
||||
Bool(bool),
|
||||
/// Linear RGBA, 0..1.
|
||||
/// Linear RGBA, 0..1
|
||||
Color([f32; 4]),
|
||||
/// Index into the parameter's options.
|
||||
/// Index into the parameter's options
|
||||
Enum(u32),
|
||||
Text(String),
|
||||
Curve(Curve),
|
||||
Gradient(Gradient),
|
||||
/// A function graph (pixel/value processors, dynamic parameters).
|
||||
Function(Box<crate::function::FnGraph>),
|
||||
/// A function graph (pixel/value processors, dynamic parameters)
|
||||
Function(Box<crate::FunctionGraph>),
|
||||
PatternGraph(Box<crate::PatternGraph>),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
@@ -163,6 +47,8 @@ impl Value {
|
||||
Value::Float(v) if v.is_finite() => Some(v.round() as i32),
|
||||
Value::Bool(b) => Some(i32::from(*b)),
|
||||
Value::Int2(v) => Some(v[0]),
|
||||
Value::Int3(v) => Some(v[0]),
|
||||
Value::Int4(v) => Some(v[0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -176,7 +62,7 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to four floats (missing ones are 0; a color keeps its alpha).
|
||||
/// Up to four floats (missing ones are 0; a color keeps its alpha)
|
||||
pub fn as_vec4(&self) -> Option<[f32; 4]> {
|
||||
match self {
|
||||
Value::Float(v) => Some([*v, *v, *v, 1.0]),
|
||||
@@ -185,11 +71,13 @@ impl Value {
|
||||
Value::Float4(v) | Value::Color(v) => Some(*v),
|
||||
Value::Int(v) => Some([*v as f32; 4]),
|
||||
Value::Int2(v) => Some([v[0] as f32, v[1] as f32, 0.0, 0.0]),
|
||||
Value::Int3(v) => Some([v[0] as f32, v[1] as f32, v[2] as f32, 0.0]),
|
||||
Value::Int4(v) => Some(v.map(|x| x as f32)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Short type name, for errors and inspect output.
|
||||
/// Short type name, for errors and inspect output
|
||||
pub fn type_name(&self) -> &'static str {
|
||||
match self {
|
||||
Value::Float(_) => "float",
|
||||
@@ -198,6 +86,8 @@ impl Value {
|
||||
Value::Float4(_) => "float4",
|
||||
Value::Int(_) => "int",
|
||||
Value::Int2(_) => "int2",
|
||||
Value::Int3(_) => "int3",
|
||||
Value::Int4(_) => "int4",
|
||||
Value::Bool(_) => "bool",
|
||||
Value::Color(_) => "color",
|
||||
Value::Enum(_) => "enum",
|
||||
@@ -205,10 +95,11 @@ impl Value {
|
||||
Value::Curve(_) => "curve",
|
||||
Value::Gradient(_) => "gradient",
|
||||
Value::Function(_) => "function",
|
||||
Value::PatternGraph(_) => "patternGraph",
|
||||
}
|
||||
}
|
||||
|
||||
/// Coerce a JSON value (from a command or MCP call) into the type of `self`.
|
||||
/// Coerce a JSON value (from a command or MCP call) into the type of `self`
|
||||
pub fn coerce_json(&self, j: &serde_json::Value) -> Option<Value> {
|
||||
use serde_json::Value as J;
|
||||
let f = |v: &J| v.as_f64().map(|x| x as f32).filter(|x| x.is_finite());
|
||||
@@ -219,12 +110,12 @@ impl Value {
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
// A typed value as the API writes it ({"t": .., "v": ..}).
|
||||
// A typed value as the API writes it ({"t": .., "v": ..})
|
||||
if let Ok(v) = serde_json::from_value::<Value>(j.clone()) {
|
||||
if v.type_name() == self.type_name() {
|
||||
return Some(v);
|
||||
}
|
||||
// Another type (a float input bound to an int parameter): coerce its payload.
|
||||
// Another type (a float input bound to an int parameter): coerce its payload
|
||||
return j.get("v").and_then(|p| self.coerce_json(p));
|
||||
}
|
||||
Some(match self {
|
||||
@@ -242,104 +133,50 @@ impl Value {
|
||||
Value::Float4([a[0], a[1], a[2], a[3]])
|
||||
}
|
||||
Value::Color(_) => Value::Color(parse_color(j)?),
|
||||
Value::Int(_) => Value::Int(f(j)?.round() as i32),
|
||||
Value::Int2(_) => {
|
||||
let a = arr(2)?;
|
||||
Value::Int2([a[0].round() as i32, a[1].round() as i32])
|
||||
}
|
||||
Value::Int(_) => Value::Int(match j.as_i64() {
|
||||
Some(value) => i32::try_from(value).ok()?,
|
||||
None => {
|
||||
let value = j.as_f64()?.round();
|
||||
if !value.is_finite() || value < i32::MIN as f64 || value > i32::MAX as f64 {
|
||||
return None;
|
||||
}
|
||||
value as i32
|
||||
}
|
||||
}),
|
||||
Value::Int2(_) => Value::Int2(parse_integers(j)?),
|
||||
Value::Int3(_) => Value::Int3(parse_integers(j)?),
|
||||
Value::Int4(_) => Value::Int4(parse_integers(j)?),
|
||||
Value::Bool(_) => Value::Bool(j.as_bool().or_else(|| f(j).map(|v| v != 0.0))?),
|
||||
Value::Enum(_) => Value::Enum(u32::try_from(j.as_u64()?).ok()?),
|
||||
Value::Text(_) => Value::Text(j.as_str()?.to_string()),
|
||||
Value::Curve(_) => {
|
||||
let pts: Vec<[f32; 2]> = serde_json::from_value(j.clone()).ok()?;
|
||||
let mut points: Vec<CurvePoint> =
|
||||
pts.into_iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| CurvePoint { x: p[0], y: p[1] }).collect();
|
||||
pts.into_iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| CurvePoint::new(p[0], p[1])).collect();
|
||||
points.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
Value::Curve(Curve { points })
|
||||
}
|
||||
Value::Gradient(_) => {
|
||||
let keys: Vec<(f32, serde_json::Value)> = serde_json::from_value(j.clone()).ok()?;
|
||||
let mut g = Gradient { keys: keys.iter().filter_map(|(p, c)| Some(GradientKey { pos: *p, color: parse_color(c)? })).collect() };
|
||||
let mut g = Gradient { keys: keys.iter().filter_map(|(p, c)| Some(GradientKey::new(*p, parse_color(c)?))).collect() };
|
||||
g.sort();
|
||||
Value::Gradient(g)
|
||||
}
|
||||
Value::Function(_) => return None,
|
||||
Value::Function(_) | Value::PatternGraph(_) => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `[r, g, b(, a)]` linear floats, a single gray number, or `"#rrggbb(aa)"` (sRGB, converted to linear).
|
||||
pub fn parse_color(j: &serde_json::Value) -> Option<[f32; 4]> {
|
||||
use serde_json::Value as J;
|
||||
match j {
|
||||
J::Array(a) if a.len() >= 3 => {
|
||||
let v: Vec<f32> = a.iter().take(4).filter_map(|x| x.as_f64().map(|x| x as f32)).filter(|x| x.is_finite()).collect();
|
||||
if v.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
Some([v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)])
|
||||
}
|
||||
J::Number(n) => n.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).map(|v| [v, v, v, 1.0]),
|
||||
J::String(s) => {
|
||||
let s = s.trim_start_matches('#');
|
||||
if s.len() != 6 && s.len() != 8 {
|
||||
return None;
|
||||
}
|
||||
let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0);
|
||||
let a = if s.len() == 8 { c(6)? } else { 1.0 };
|
||||
Some([srgb_to_linear(c(0)?), srgb_to_linear(c(2)?), srgb_to_linear(c(4)?), a])
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB transfer function, encoded → linear.
|
||||
pub fn srgb_to_linear(v: f32) -> f32 {
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// sRGB transfer function, linear → encoded.
|
||||
pub fn linear_to_srgb(v: f32) -> f32 {
|
||||
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curve_identity_and_monotone() {
|
||||
let c = Curve::default();
|
||||
for i in 0..=10 {
|
||||
let x = i as f32 / 10.0;
|
||||
assert!((c.eval(x) - x).abs() < 1e-4);
|
||||
}
|
||||
let s =
|
||||
Curve { points: vec![CurvePoint { x: 0.0, y: 0.0 }, CurvePoint { x: 0.3, y: 0.1 }, CurvePoint { x: 0.7, y: 0.9 }, CurvePoint { x: 1.0, y: 1.0 }] };
|
||||
let mut last = -1.0;
|
||||
for i in 0..=100 {
|
||||
let v = s.eval(i as f32 / 100.0);
|
||||
assert!(v >= last - 1e-5);
|
||||
last = v;
|
||||
}
|
||||
fn parse_integers<const COUNT: usize>(value: &serde_json::Value) -> Option<[i32; COUNT]> {
|
||||
let components = value.as_array()?;
|
||||
if components.len() != COUNT {
|
||||
return None;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coerce_from_json() {
|
||||
assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(0.5)), Some(Value::Float(0.5)));
|
||||
assert_eq!(Value::Color([0.0; 4]).coerce_json(&serde_json::json!("#ffffff")), Some(Value::Color([1.0, 1.0, 1.0, 1.0])));
|
||||
assert_eq!(Value::Float2([0.0; 2]).coerce_json(&serde_json::json!([1, 2])), Some(Value::Float2([1.0, 2.0])));
|
||||
assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!("x")), None);
|
||||
assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(f64::MAX)), None);
|
||||
// A typed value of another type converts through its payload.
|
||||
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "float", "v": 8.6})), Some(Value::Int(9)));
|
||||
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), None);
|
||||
let mut result = [0; COUNT];
|
||||
for (target, component) in result.iter_mut().zip(components) {
|
||||
*target = i32::try_from(component.as_i64()?).ok()?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_interpolates() {
|
||||
let g = Gradient::default();
|
||||
assert_eq!(g.eval(0.5), [0.5, 0.5, 0.5, 1.0]);
|
||||
assert_eq!(Gradient { keys: vec![] }.eval(0.25)[0], 0.25);
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use crate::*;
|
||||
|
||||
#[test]
|
||||
fn curve_identity_and_monotone() {
|
||||
let c = Curve::default();
|
||||
for i in 0..=10 {
|
||||
let x = i as f32 / 10.0;
|
||||
assert!((c.eval(x) - x).abs() < 1e-4);
|
||||
}
|
||||
let s = Curve { points: vec![CurvePoint::new(0.0, 0.0), CurvePoint::new(0.3, 0.1), CurvePoint::new(0.7, 0.9), CurvePoint::new(1.0, 1.0)] };
|
||||
let mut last = -1.0;
|
||||
for i in 0..=100 {
|
||||
let v = s.eval(i as f32 / 100.0);
|
||||
assert!(v >= last - 1e-5);
|
||||
last = v;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coerce_from_json() {
|
||||
assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(0.5)), Some(Value::Float(0.5)));
|
||||
assert_eq!(Value::Color([0.0; 4]).coerce_json(&serde_json::json!("#ffffff")), Some(Value::Color([1.0, 1.0, 1.0, 1.0])));
|
||||
assert_eq!(Value::Float2([0.0; 2]).coerce_json(&serde_json::json!([1, 2])), Some(Value::Float2([1.0, 2.0])));
|
||||
assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!("x")), None);
|
||||
assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(f64::MAX)), None);
|
||||
// A typed value of another type converts through its payload
|
||||
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "float", "v": 8.6})), Some(Value::Int(9)));
|
||||
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_interpolates() {
|
||||
let g = Gradient::default();
|
||||
assert_eq!(g.eval(0.5), [0.5, 0.5, 0.5, 1.0]);
|
||||
assert_eq!(Gradient { keys: vec![] }.eval(0.25)[0], 0.25);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use crate::Value;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[repr(u32)]
|
||||
pub enum ValueType {
|
||||
Boolean = 4,
|
||||
Integer = 16,
|
||||
Integer2 = 32,
|
||||
Integer3 = 64,
|
||||
Integer4 = 128,
|
||||
Float = 256,
|
||||
Float2 = 512,
|
||||
Float3 = 1024,
|
||||
Float4 = 2048,
|
||||
String = 16384,
|
||||
}
|
||||
|
||||
impl ValueType {
|
||||
pub const ALL: [Self; 10] =
|
||||
[Self::Float, Self::Float2, Self::Float3, Self::Float4, Self::Integer, Self::Integer2, Self::Integer3, Self::Integer4, Self::Boolean, Self::String];
|
||||
|
||||
pub fn from_code(code: u32) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|value_type| *value_type as u32 == code)
|
||||
}
|
||||
|
||||
pub fn of(value: &Value) -> Option<Self> {
|
||||
Some(match value {
|
||||
Value::Bool(_) => Self::Boolean,
|
||||
Value::Int(_) | Value::Enum(_) => Self::Integer,
|
||||
Value::Int2(_) => Self::Integer2,
|
||||
Value::Int3(_) => Self::Integer3,
|
||||
Value::Int4(_) => Self::Integer4,
|
||||
Value::Float(_) => Self::Float,
|
||||
Value::Float2(_) => Self::Float2,
|
||||
Value::Float3(_) => Self::Float3,
|
||||
Value::Float4(_) | Value::Color(_) => Self::Float4,
|
||||
Value::Text(_) => Self::String,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Boolean => "Boolean",
|
||||
Self::Integer => "Integer",
|
||||
Self::Integer2 => "Integer2",
|
||||
Self::Integer3 => "Integer3",
|
||||
Self::Integer4 => "Integer4",
|
||||
Self::Float => "Float",
|
||||
Self::Float2 => "Float2",
|
||||
Self::Float3 => "Float3",
|
||||
Self::Float4 => "Float4",
|
||||
Self::String => "String",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_value(self) -> Value {
|
||||
match self {
|
||||
Self::Boolean => Value::Bool(false),
|
||||
Self::Integer => Value::Int(0),
|
||||
Self::Integer2 => Value::Int2([0; 2]),
|
||||
Self::Integer3 => Value::Int3([0; 3]),
|
||||
Self::Integer4 => Value::Int4([0; 4]),
|
||||
Self::Float => Value::Float(0.0),
|
||||
Self::Float2 => Value::Float2([0.0; 2]),
|
||||
Self::Float3 => Value::Float3([0.0; 3]),
|
||||
Self::Float4 => Value::Float4([0.0; 4]),
|
||||
Self::String => Value::Text(String::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let package = materialcraft_engine::atomic_sample()?;
|
||||
let bytes = materialcraft_engine::formats::sbs::write_sbs(&package)?;
|
||||
let path = std::env::args().nth(1).unwrap_or_else(|| "atomic_sample.sbs".into());
|
||||
std::fs::write(path, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
use crate::commands::{CommandSpec, bad, has_graph, strp};
|
||||
use crate::selection_target::SelectionTarget;
|
||||
use crate::{Result, Session, cmd};
|
||||
use materialcraft_core::Value;
|
||||
use serde_json::Value as Json;
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"graph.align",
|
||||
"Align nodes",
|
||||
[],
|
||||
None,
|
||||
"{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?: required for Function/FX-Map, pattern?: owner node id, function?: FunctionGraphTarget, graph?: owning graph index}",
|
||||
has_graph,
|
||||
align
|
||||
)]
|
||||
}
|
||||
|
||||
fn align(session: &mut Session, parameters: &Json) -> Result<Json> {
|
||||
let mode = strp(parameters, "mode").unwrap_or("left");
|
||||
let ids: Vec<u64> = parameters
|
||||
.get("ids")
|
||||
.and_then(Json::as_array)
|
||||
.map(|ids| ids.iter().filter_map(Json::as_u64).collect())
|
||||
.unwrap_or_else(|| session.selection.iter().map(|id| id.0).collect());
|
||||
let target = SelectionTarget::resolve(session, parameters)?;
|
||||
if target.is_some() && parameters.get("ids").and_then(Json::as_array).is_none() {
|
||||
return Err(bad("graph.align", "ids are required for a Function Graph or FX-Map"));
|
||||
}
|
||||
match target {
|
||||
Some(SelectionTarget::Function(target)) => {
|
||||
let mut graph = target.current(session)?.clone();
|
||||
align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.pos)).collect(), &ids, mode)?;
|
||||
crate::graph_validation::function(&graph).map_err(|error| bad("graph.align", error))?;
|
||||
session.edit("Align nodes", |session| target.replace(session, graph))?;
|
||||
}
|
||||
Some(SelectionTarget::Pattern(owner)) => {
|
||||
let mut graph = SelectionTarget::pattern(session, owner)?.clone();
|
||||
align_selected(graph.nodes.iter_mut().map(|node| (u64::from(node.id), &mut node.position)).collect(), &ids, mode)?;
|
||||
crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.align", error))?;
|
||||
session.edit("Align nodes", |session| {
|
||||
session.graph_mut()?.node_mut(owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
None => {
|
||||
session.edit("Align nodes", |session| {
|
||||
align_selected(session.graph_mut()?.nodes.iter_mut().map(|node| (node.id.0, &mut node.pos)).collect(), &ids, mode)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(Json::Null)
|
||||
}
|
||||
|
||||
fn align_selected(mut positions: Vec<(u64, &mut [f32; 2])>, ids: &[u64], mode: &str) -> Result<()> {
|
||||
let present: std::collections::BTreeSet<_> = positions.iter().map(|(id, _)| *id).collect();
|
||||
if let Some(id) = ids.iter().find(|id| !present.contains(id)) {
|
||||
return Err(bad("graph.align", format!("no node {id}")));
|
||||
}
|
||||
let selected: std::collections::BTreeSet<_> = ids.iter().copied().collect();
|
||||
positions.retain(|(id, _)| selected.contains(id));
|
||||
align_positions(positions.into_iter().map(|(_, position)| position).collect(), mode)
|
||||
}
|
||||
|
||||
fn align_positions(mut positions: Vec<&mut [f32; 2]>, mode: &str) -> Result<()> {
|
||||
let axis = match mode {
|
||||
"left" | "right" | "hcenter" | "hdistribute" => 0,
|
||||
"top" | "bottom" | "vcenter" | "vdistribute" => 1,
|
||||
other => return Err(bad("graph.align", format!("unknown mode `{other}`"))),
|
||||
};
|
||||
|
||||
if positions.len() < 2 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let minimum = positions.iter().map(|position| position[axis]).fold(f32::MAX, f32::min);
|
||||
let maximum = positions.iter().map(|position| position[axis]).fold(f32::MIN, f32::max);
|
||||
if mode.ends_with("distribute") {
|
||||
positions.sort_by(|left, right| left[axis].total_cmp(&right[axis]));
|
||||
let step = (maximum - minimum) / (positions.len() - 1) as f32;
|
||||
for (index, position) in positions.iter_mut().enumerate() {
|
||||
position[axis] = minimum + step * index as f32;
|
||||
}
|
||||
} else {
|
||||
let value = match mode {
|
||||
"left" | "top" => minimum,
|
||||
"right" | "bottom" => maximum,
|
||||
_ => (minimum + maximum) * 0.5,
|
||||
};
|
||||
for position in positions {
|
||||
position[axis] = value;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
|
||||
use crate::{AnnotationSelection, Result, Session, cmd};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"graph.annotation.select",
|
||||
"Select annotation",
|
||||
[],
|
||||
None,
|
||||
"{kind?: frame|comment, id?} clears node selection; omit kind to deselect",
|
||||
has_graph,
|
||||
select
|
||||
)]
|
||||
}
|
||||
|
||||
fn select(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let selection = match strp(parameters, "kind") {
|
||||
None => None,
|
||||
Some(kind) => {
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.annotation.select", "`id` is required"))?;
|
||||
let selection = match kind {
|
||||
"frame" => AnnotationSelection::Frame(id),
|
||||
"comment" => AnnotationSelection::Comment(id),
|
||||
_ => return Err(bad("graph.annotation.select", "kind must be frame or comment")),
|
||||
};
|
||||
if !selection.exists(session.graph()?) {
|
||||
return Err(bad("graph.annotation.select", "annotation does not exist"));
|
||||
}
|
||||
|
||||
Some(selection)
|
||||
}
|
||||
};
|
||||
|
||||
session.annotation_selection = selection;
|
||||
if selection.is_some() {
|
||||
session.selection.clear();
|
||||
}
|
||||
|
||||
Ok(json!({"selection": selection}))
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use materialcraft_core::Graph;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", content = "id", rename_all = "camelCase")]
|
||||
pub enum AnnotationSelection {
|
||||
Frame(u64),
|
||||
Comment(u64),
|
||||
}
|
||||
|
||||
impl AnnotationSelection {
|
||||
pub fn exists(self, graph: &Graph) -> bool {
|
||||
match self {
|
||||
Self::Frame(id) => graph.frames.iter().any(|frame| frame.id == id),
|
||||
Self::Comment(id) => graph.comments.iter().any(|comment| comment.id == id),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use crate::{EngineError, Result};
|
||||
use materialcraft_core::{FunctionGraph, Graph, Package, PatternGraph, PatternNodeKind, Value, ValueType};
|
||||
|
||||
pub fn atomic_sample() -> Result<Package> {
|
||||
let mut package = Package::new("Atomic sample");
|
||||
let mut graph = Graph::new("Atomic_sample");
|
||||
graph.size = [8, 8];
|
||||
let input = graph.add_node("input_value", [0.0, 0.0]);
|
||||
graph.node_mut(input)?.params.insert("default".into(), Value::Float(0.35));
|
||||
graph.node_mut(input)?.params.insert("identifier".into(), Value::Text("brightness".into()));
|
||||
|
||||
let value = graph.add_node("value_processor", [200.0, 0.0]);
|
||||
let mut function = FunctionGraph::default();
|
||||
let get = function.add("get_float1", &[], Some(Value::Text("brightness".into())));
|
||||
let two = function.add_constant(Value::Float(2.0));
|
||||
function.output = Some(function.add("mul", &[get, two], None));
|
||||
graph.node_mut(value)?.input_values.insert("brightness".into(), ValueType::Float);
|
||||
graph.node_mut(value)?.params.insert("function".into(), Value::Function(Box::new(function)));
|
||||
graph.connect(input, "output", value, "brightness")?;
|
||||
|
||||
let pixel = graph.add_node("pixel_processor", [400.0, 0.0]);
|
||||
let mut function = FunctionGraph::default();
|
||||
let position = function.add("get_float2", &[], Some(Value::Text("$pos".into())));
|
||||
let horizontal = function.add("swizzle1", &[position], Some(Value::Int(0)));
|
||||
let brightness = function.add("get_float1", &[], Some(Value::Text("brightness".into())));
|
||||
function.output = Some(function.add("mul", &[horizontal, brightness], None));
|
||||
graph.node_mut(pixel)?.params.insert("function".into(), Value::Function(Box::new(function)));
|
||||
graph.node_mut(pixel)?.params.insert("color_mode".into(), Value::Bool(false));
|
||||
graph.node_mut(pixel)?.input_values.insert("brightness".into(), ValueType::Float);
|
||||
graph.connect(value, "output", pixel, "brightness")?;
|
||||
|
||||
let pattern = graph.add_node("fx_map", [400.0, 220.0]);
|
||||
let mut patterns = PatternGraph::default();
|
||||
let iterate = patterns.add(PatternNodeKind::Iterate).map_err(EngineError::Other)?;
|
||||
let switch = patterns.add(PatternNodeKind::Switch).map_err(EngineError::Other)?;
|
||||
let quadrant = patterns.add(PatternNodeKind::Quadrant).map_err(EngineError::Other)?;
|
||||
for node in &mut patterns.nodes {
|
||||
match node.kind {
|
||||
PatternNodeKind::Dot => {}
|
||||
PatternNodeKind::Iterate => {
|
||||
node.position = [160.0, 0.0];
|
||||
node.children = vec![Some(switch), Some(quadrant)];
|
||||
node.parameters.insert("numberadded".into(), Value::Int(8));
|
||||
}
|
||||
PatternNodeKind::Switch => {
|
||||
node.position = [0.0, 192.0];
|
||||
node.children = vec![None, Some(quadrant)];
|
||||
}
|
||||
PatternNodeKind::Quadrant => {
|
||||
node.position = [160.0, 384.0];
|
||||
node.parameters.insert("patterntype".into(), Value::Int(3));
|
||||
node.parameters.insert("patternsize".into(), Value::Float2([0.12; 2]));
|
||||
node.parameters.insert("opacity".into(), Value::Float4([0.5, 0.5, 0.5, 1.0]));
|
||||
let mut function = FunctionGraph::default();
|
||||
let number = function.add("get_float1", &[], Some(Value::Text("$number".into())));
|
||||
let step = function.add_constant(Value::Float(std::f32::consts::TAU / 8.0));
|
||||
let angle = function.add("mul", &[number, step], None);
|
||||
let radius = function.add_constant(Value::Float(0.3));
|
||||
function.output = Some(function.add("cartesian", &[radius, angle], None));
|
||||
node.parameters.insert("frameoffset".into(), Value::Function(Box::new(function)));
|
||||
}
|
||||
}
|
||||
}
|
||||
patterns.root = Some(iterate);
|
||||
graph.node_mut(pattern)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(patterns)));
|
||||
let blend = graph.add_node("blend", [600.0, 0.0]);
|
||||
graph.node_mut(blend)?.params.insert("mode".into(), Value::Enum(1));
|
||||
graph.connect(pattern, "output", blend, "foreground")?;
|
||||
graph.connect(pixel, "output", blend, "background")?;
|
||||
let blur = graph.add_node("blur", [800.0, 0.0]);
|
||||
graph.node_mut(blur)?.params.insert("intensity".into(), Value::Float(1.5));
|
||||
graph.connect(blend, "output", blur, "input")?;
|
||||
let output = graph.add_node("output", [1000.0, 0.0]);
|
||||
graph.node_mut(output)?.params.insert("usage".into(), Value::Enum(4));
|
||||
graph.node_mut(output)?.params.insert("identifier".into(), Value::Text("height".into()));
|
||||
graph.connect(blur, "output", output, "input")?;
|
||||
let output = graph.add_node("output", [400.0, -200.0]);
|
||||
graph.node_mut(output)?.params.insert("identifier".into(), Value::Text("brightness_value".into()));
|
||||
graph.node_mut(output)?.params.insert("usage".into(), Value::Enum(9));
|
||||
graph.connect(value, "output", output, "input")?;
|
||||
package.graphs.push(graph);
|
||||
Ok(package)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::commands::{CommandSpec, always};
|
||||
use crate::{Result, Session, cmd};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!("file.newAtomicSample", "Atomic sample", ["File", "New"], None, "{} opens an original graph made only of native primitives", always, create)]
|
||||
}
|
||||
|
||||
fn create(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
let package = crate::atomic_sample()?;
|
||||
crate::file_cmds::replace_package(session, package, None);
|
||||
Ok(json!({"graph": "Atomic_sample"}))
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use materialcraft_core::{Connection, Node};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Clip {
|
||||
pub nodes: Vec<Node>,
|
||||
pub connections: Vec<Connection>,
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Connection>,
|
||||
#[serde(skip)]
|
||||
pub source_graph: Option<String>,
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//! The command registry. Every user-visible action is a command with a stable id; the menus,
|
||||
//! shortcuts, CLI, control channel and MCP server all dispatch them by id.
|
||||
//! The command registry. Every user-visible action is a command with a stable id; the menus, shortcuts, CLI, control channel and MCP server all dispatch them by id
|
||||
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
@@ -13,11 +12,11 @@ pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
|
||||
pub struct CommandSpec {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
/// Menu placement, e.g. `["Edit"]`. Empty = not in menus.
|
||||
/// Menu placement, e.g. `["Edit"]`. Empty = not in menus
|
||||
pub menu: &'static [&'static str],
|
||||
/// Default shortcut in egui notation (`Ctrl+Shift+E`).
|
||||
/// Default shortcut in egui notation (`Ctrl+Shift+E`)
|
||||
pub shortcut: Option<&'static str>,
|
||||
/// Parameters, for humans and agents.
|
||||
/// Parameters, for humans and agents
|
||||
pub params: &'static str,
|
||||
pub enabled: Enabled,
|
||||
pub run: Run,
|
||||
@@ -49,11 +48,23 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
SPECS.get_or_init(|| {
|
||||
let mut v = Vec::new();
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::atomic_sample_commands::specs());
|
||||
v.extend(crate::material_cmds::specs());
|
||||
v.extend(crate::edit_cmds::specs());
|
||||
v.extend(crate::embedded_edit_commands::specs());
|
||||
v.extend(crate::graph_cmds::specs());
|
||||
v.extend(crate::alignment_commands::specs());
|
||||
v.extend(crate::annotation_commands::specs());
|
||||
v.extend(crate::frame_commands::specs());
|
||||
v.extend(crate::function_commands::specs());
|
||||
v.extend(crate::comment_commands::specs());
|
||||
v.extend(crate::node_cmds::specs());
|
||||
v.extend(crate::node_graph_commands::specs());
|
||||
v.extend(crate::pattern_graph_commands::specs());
|
||||
v.extend(crate::connection_commands::specs());
|
||||
v.extend(crate::value_input_commands::specs());
|
||||
v.extend(crate::view_cmds::specs());
|
||||
v.extend(crate::material_preview_commands::specs());
|
||||
v.extend(crate::wire_cmds::specs());
|
||||
v
|
||||
})
|
||||
@@ -63,21 +74,31 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
/// Run a command by id with JSON params (empty params = defaults, never a dialog).
|
||||
/// Run a command by id with JSON params (empty params = defaults, never a dialog)
|
||||
pub fn execute(s: &mut Session, id: &str, params: &J) -> Result<J> {
|
||||
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
if let Some(result) = crate::selection_commands::execute(s, id, params) {
|
||||
return result;
|
||||
}
|
||||
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
|
||||
(spec.run)(s, params)
|
||||
let result = (spec.run)(s, params)?;
|
||||
if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) {
|
||||
s.annotation_selection = None;
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Every command, as JSON (for `commands` listings and MCP).
|
||||
/// Every command, as JSON (for `commands` listings and MCP)
|
||||
pub fn list(s: &Session, filter: Option<&str>) -> J {
|
||||
let f = filter.map(str::to_ascii_lowercase);
|
||||
J::Array(
|
||||
command_specs()
|
||||
.iter()
|
||||
.filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f)))
|
||||
.map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok()}))
|
||||
.map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": if crate::selection_commands::supports(c.id) {
|
||||
format!("{}; optional function: FunctionGraphTarget or pattern: owner node id, graph: owning graph index; embedded targets use explicit ids; copy returns clip", c.params)
|
||||
} else { c.params.to_string() }, "enabled": crate::selection_commands::enabled(s, c.id, &J::Null).unwrap_or_else(|| (c.enabled)(s).is_ok())}))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
@@ -108,17 +129,18 @@ pub(crate) fn strp<'a>(p: &'a J, key: &str) -> Option<&'a str> {
|
||||
p.get(key).and_then(J::as_str)
|
||||
}
|
||||
|
||||
/// A node id param (`key`), defaulting to the last selected node.
|
||||
/// A node id param (`key`), defaulting to the last selected node
|
||||
pub(crate) fn node_param(s: &Session, cmd: &str, p: &J, key: &str) -> Result<NodeId> {
|
||||
let id = match u64p(p, key) {
|
||||
Some(id) => NodeId(id),
|
||||
None => *s.selection.last().ok_or_else(|| bad(cmd, format!("no node selected and no `{key}` given")))?,
|
||||
};
|
||||
|
||||
s.graph()?.node(id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// A list of node ids (`ids`), defaulting to the selection.
|
||||
/// A list of node ids (`ids`), defaulting to the selection
|
||||
pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result<Vec<NodeId>> {
|
||||
let ids: Vec<NodeId> = match p.get("ids").and_then(J::as_array) {
|
||||
Some(a) => a.iter().filter_map(J::as_u64).map(NodeId).collect(),
|
||||
@@ -127,6 +149,7 @@ pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result<Vec<NodeId>> {
|
||||
None => s.selection.clone(),
|
||||
},
|
||||
};
|
||||
|
||||
let g = s.graph()?;
|
||||
for id in &ids {
|
||||
g.node(*id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?;
|
||||
@@ -134,10 +157,23 @@ pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result<Vec<NodeId>> {
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// A 2D point param (`[x, y]`).
|
||||
/// A 2D point param (`[x, y]`)
|
||||
pub(crate) fn point(p: &J, key: &str) -> Option<[f32; 2]> {
|
||||
let a = p.get(key)?.as_array()?;
|
||||
let x = a.first()?.as_f64()? as f32;
|
||||
let y = a.get(1)?.as_f64()? as f32;
|
||||
(x.is_finite() && y.is_finite()).then_some([x, y])
|
||||
}
|
||||
|
||||
/// Automation requests are separate undo steps unless the caller explicitly groups a gesture
|
||||
pub fn execute_request(session: &mut Session, id: &str, params: &J) -> Result<J> {
|
||||
let merged = params.get("merge").and_then(J::as_bool) == Some(true);
|
||||
if !merged {
|
||||
session.finish_edit();
|
||||
}
|
||||
let result = execute(session, id, params);
|
||||
if !merged {
|
||||
session.finish_edit();
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
|
||||
use crate::graph_cmds::nodes_rect;
|
||||
use crate::{AnnotationSelection, Result, Session, cmd};
|
||||
use materialcraft_core::Comment;
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("graph.comment.add", "Add Comment", [], None, "{text?, at? [x, y]}", has_graph, comment_add),
|
||||
cmd!("graph.comment.edit", "Edit comment", [], None, "{id, text?, at?, size?}", has_graph, comment_edit),
|
||||
cmd!("graph.comment.delete", "Delete comment", [], None, "{id}", has_graph, comment_delete),
|
||||
]
|
||||
}
|
||||
|
||||
fn comment_add(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let at = point(parameters, "at").or_else(|| nodes_rect(session, &session.selection).map(|rect| [rect[0], rect[1] - 90.0])).unwrap_or([0.0, -120.0]);
|
||||
let text = strp(parameters, "text").unwrap_or("Comment").to_string();
|
||||
|
||||
session.edit("Add comment", |session| {
|
||||
let graph = session.graph_mut()?;
|
||||
let id = graph.alloc_id();
|
||||
graph.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] });
|
||||
session.selection.clear();
|
||||
session.annotation_selection = Some(AnnotationSelection::Comment(id));
|
||||
Ok(json!({"id": id}))
|
||||
})
|
||||
}
|
||||
|
||||
fn comment_edit(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.edit", "`id` is required"))?;
|
||||
|
||||
session.edit_merged(&format!("comment{id}"), "Edit comment", |session| {
|
||||
let comment =
|
||||
session.graph_mut()?.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?;
|
||||
if let Some(text) = strp(parameters, "text") {
|
||||
comment.text = text.into();
|
||||
}
|
||||
if let Some(position) = point(parameters, "at") {
|
||||
comment.pos = position;
|
||||
}
|
||||
if let Some(size) = point(parameters, "size") {
|
||||
comment.size = [size[0].max(40.0), size[1].max(24.0)];
|
||||
}
|
||||
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn comment_delete(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.delete", "`id` is required"))?;
|
||||
|
||||
session.edit("Delete comment", |session| {
|
||||
session.graph_mut()?.comments.retain(|comment| comment.id != id);
|
||||
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use materialcraft_core::NodeId;
|
||||
use serde_json::Value as J;
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"graph.connect",
|
||||
"Connect",
|
||||
[],
|
||||
None,
|
||||
"{from, fromPort? (output), to, toPort? (first compatible input), detach? {to, toPort}}",
|
||||
has_graph,
|
||||
connect
|
||||
),
|
||||
cmd!("graph.disconnect", "Disconnect", [], None, "{to, toPort}", has_graph, disconnect),
|
||||
]
|
||||
}
|
||||
|
||||
fn connect(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let from = NodeId(u64p(parameters, "from").ok_or_else(|| bad("graph.connect", "`from` is required"))?);
|
||||
let to = NodeId(u64p(parameters, "to").ok_or_else(|| bad("graph.connect", "`to` is required"))?);
|
||||
let outputs = session.output_ports(from);
|
||||
let from_port = strp(parameters, "fromPort")
|
||||
.map(str::to_string)
|
||||
.or_else(|| outputs.first().cloned())
|
||||
.ok_or_else(|| bad("graph.connect", "the source has no outputs"))?;
|
||||
let to_port = match strp(parameters, "toPort") {
|
||||
Some(port) => port.to_string(),
|
||||
None => connection_input(session, from, &from_port, to)?,
|
||||
};
|
||||
|
||||
let detached = parameters
|
||||
.get("detach")
|
||||
.map(|input| {
|
||||
let node = u64p(input, "to").map(NodeId).ok_or_else(|| bad("graph.connect", "detach needs `to`"))?;
|
||||
let port = strp(input, "toPort").ok_or_else(|| bad("graph.connect", "detach needs `toPort`"))?;
|
||||
let connection = session.graph()?.input_of(node, port).ok_or_else(|| bad("graph.connect", "the detached wire no longer exists"))?;
|
||||
if connection.from != from || connection.from_port != from_port {
|
||||
return Err(bad("graph.connect", "the detached wire has a different source"));
|
||||
}
|
||||
|
||||
Ok((node, port.to_string()))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
validate_connection(session, from, &from_port, to, &to_port)?;
|
||||
|
||||
session.edit("Connect", |session| {
|
||||
if let Some((node, port)) = detached {
|
||||
session.graph_mut()?.disconnect(node, &port);
|
||||
}
|
||||
|
||||
session.graph_mut()?.connect(from, &from_port, to, &to_port)?;
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn connection_input(session: &Session, from: NodeId, from_port: &str, to: NodeId) -> Result<String> {
|
||||
session
|
||||
.input_ports(to)
|
||||
.into_iter()
|
||||
.find(|port| validate_connection(session, from, from_port, to, port).is_ok())
|
||||
.ok_or_else(|| bad("graph.connect", "the target has no compatible input"))
|
||||
}
|
||||
|
||||
fn validate_connection(session: &Session, from: NodeId, from_port: &str, to: NodeId, to_port: &str) -> Result<()> {
|
||||
let outputs = session.output_ports(from);
|
||||
let inputs = session.input_ports(to);
|
||||
if !outputs.iter().any(|port| port == from_port) {
|
||||
return Err(bad("graph.connect", format!("no output `{from_port}` on node {}", from.0)));
|
||||
}
|
||||
if !inputs.iter().any(|port| port == to_port) {
|
||||
return Err(bad("graph.connect", format!("no input `{to_port}` on node {}", to.0)));
|
||||
}
|
||||
|
||||
let graph = session.graph()?;
|
||||
let target = graph.node(to)?;
|
||||
let source_type = materialcraft_nodes::output_value_type(graph, from).map_err(|error| bad("graph.connect", error))?;
|
||||
if let Some(expected) = target.input_values.get(to_port) {
|
||||
if source_type != Some(*expected) {
|
||||
return Err(bad("graph.connect", format!("input `{to_port}` requires {}", expected.label())));
|
||||
}
|
||||
} else if source_type.is_some() && !matches!(target.def.as_str(), "output" | "dot") {
|
||||
return Err(bad("graph.connect", format!("input `{to_port}` requires an image")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn disconnect(s: &mut Session, p: &J) -> Result<J> {
|
||||
let to = NodeId(u64p(p, "to").ok_or_else(|| bad("graph.disconnect", "`to` is required"))?);
|
||||
let port = strp(p, "toPort").ok_or_else(|| bad("graph.disconnect", "`toPort` is required"))?.to_string();
|
||||
s.edit("Disconnect", |s| {
|
||||
if !s.graph_mut()?.disconnect(to, &port) {
|
||||
return Err(bad("graph.disconnect", "nothing is connected there"));
|
||||
}
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Input port ids of node `id` (empty for a missing node)
|
||||
pub fn input_ports(&self, id: NodeId) -> Vec<String> {
|
||||
self.graph()
|
||||
.ok()
|
||||
.and_then(|graph| graph.node(id).ok().map(|node| materialcraft_eval::ports(&self.pkg, graph, node).0.into_iter().map(|port| port.id).collect()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Output port ids of node `id`
|
||||
pub fn output_ports(&self, id: NodeId) -> Vec<String> {
|
||||
self.graph()
|
||||
.ok()
|
||||
.and_then(|graph| graph.node(id).ok().map(|node| materialcraft_eval::ports(&self.pkg, graph, node).1.into_iter().map(|port| port.id).collect()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Edit menu: undo/redo, clipboard, duplicate, delete and selection.
|
||||
//! Edit menu: undo/redo, clipboard, duplicate, delete and selection
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -6,8 +6,8 @@ use serde_json::{Value as J, json};
|
||||
|
||||
use materialcraft_core::{Connection, NodeId};
|
||||
|
||||
use crate::Clip;
|
||||
use crate::commands::{CommandSpec, always, bad, has_graph, has_selection, ids_param, point};
|
||||
use crate::session::Clip;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
fn can_undo(s: &Session) -> std::result::Result<(), String> {
|
||||
@@ -34,14 +34,40 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
duplicate
|
||||
),
|
||||
cmd!("edit.delete", "Delete selection", [], Some("Delete"), "{ids?}", has_selection, delete),
|
||||
cmd!(
|
||||
"edit.pasteWithoutLinks",
|
||||
"Paste without link",
|
||||
[],
|
||||
Some("Ctrl+Shift+V"),
|
||||
"{at?, snapToGrid?} pastes without incoming links",
|
||||
has_clip_or_param,
|
||||
|session, parameters| {
|
||||
let mut parameters = parameters.as_object().cloned().unwrap_or_default();
|
||||
parameters.insert("withoutLinks".into(), J::Bool(true));
|
||||
paste(session, &J::Object(parameters))
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"edit.duplicateWithoutLinks",
|
||||
"Duplicate selection without link",
|
||||
[],
|
||||
Some("Ctrl+Shift+D"),
|
||||
"{ids?, snapToGrid?} duplicates without incoming links",
|
||||
has_selection,
|
||||
|session, parameters| {
|
||||
let mut parameters = parameters.as_object().cloned().unwrap_or_default();
|
||||
parameters.insert("withoutLinks".into(), J::Bool(true));
|
||||
duplicate(session, &J::Object(parameters))
|
||||
}
|
||||
),
|
||||
cmd!("edit.delete", "Delete selection", [], Some("Delete"), "{ids?}", has_deletable_selection, delete),
|
||||
cmd!(
|
||||
"edit.deleteRelink",
|
||||
"Delete and relink",
|
||||
[],
|
||||
Some("Backspace"),
|
||||
"{ids?} deletes nodes and joins what fed their first input to what they fed",
|
||||
has_selection,
|
||||
has_deletable_selection,
|
||||
delete_relink
|
||||
),
|
||||
cmd!("edit.selectAll", "Select all", [], Some("Ctrl+A"), "{}", has_graph, |s, _| {
|
||||
@@ -50,13 +76,14 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
}),
|
||||
cmd!("edit.selectNone", "Deselect", [], None, "{}", always, |s, _| {
|
||||
s.selection.clear();
|
||||
s.annotation_selection = None;
|
||||
Ok(J::Null)
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
fn has_clip_or_param(s: &Session) -> std::result::Result<(), String> {
|
||||
// `clip` may come with the params; the check happens in `paste`.
|
||||
// `clip` may come with the params; the check happens in `paste`
|
||||
has_graph(s)
|
||||
}
|
||||
|
||||
@@ -65,6 +92,8 @@ fn clip_of(s: &Session, ids: &[NodeId]) -> Result<Clip> {
|
||||
Ok(Clip {
|
||||
nodes: g.nodes.iter().filter(|n| ids.contains(&n.id)).cloned().collect(),
|
||||
connections: g.connections.iter().filter(|c| ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect(),
|
||||
inputs: g.connections.iter().filter(|c| !ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect(),
|
||||
source_graph: Some(g.name.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -82,22 +111,22 @@ fn cut(s: &mut Session, p: &J) -> Result<J> {
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Insert a clip's nodes with fresh ids, offset so their top-left lands at `at`; returns the
|
||||
/// new ids. `keep_inputs`: also reconnect wires from outside nodes (duplicate).
|
||||
fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32; 2], outer: &[Connection]) -> Result<Vec<NodeId>> {
|
||||
/// Insert copied nodes and their wires with fresh ids
|
||||
fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32; 2], outer: &[Connection], snap: bool) -> Result<Vec<NodeId>> {
|
||||
let g = s.graph_mut()?;
|
||||
let min = clip.nodes.iter().fold([f32::MAX, f32::MAX], |m, n| [m[0].min(n.pos[0]), m[1].min(n.pos[1])]);
|
||||
let shift = match at {
|
||||
Some(a) if min[0] < f32::MAX => [a[0] - min[0], a[1] - min[1]],
|
||||
_ => offset,
|
||||
};
|
||||
|
||||
let mut map: BTreeMap<NodeId, NodeId> = BTreeMap::new();
|
||||
for n in &clip.nodes {
|
||||
let id = NodeId(g.alloc_id());
|
||||
map.insert(n.id, id);
|
||||
let mut c = n.clone();
|
||||
c.id = id;
|
||||
c.pos = [n.pos[0] + shift[0], n.pos[1] + shift[1]];
|
||||
c.pos = crate::graph_grid::translate(n.pos, shift, snap);
|
||||
g.nodes.push(c);
|
||||
}
|
||||
for c in &clip.connections {
|
||||
@@ -120,12 +149,16 @@ fn paste(s: &mut Session, p: &J) -> Result<J> {
|
||||
Some(c) => serde_json::from_value::<Clip>(c.clone()).map_err(|e| bad("edit.paste", format!("bad clip: {e}")))?,
|
||||
None => s.clipboard.clone().ok_or_else(|| bad("edit.paste", "the clipboard is empty"))?,
|
||||
};
|
||||
|
||||
if clip.nodes.len() > 10_000 {
|
||||
return Err(bad("edit.paste", "too many nodes"));
|
||||
}
|
||||
let at = point(p, "at");
|
||||
let keep_inputs = !crate::commands::boolp(p, "withoutLinks").unwrap_or(false) && clip.source_graph.as_deref() == Some(s.graph()?.name.as_str());
|
||||
let snap = crate::commands::boolp(p, "snapToGrid").unwrap_or(false);
|
||||
|
||||
s.edit("Paste", |s| {
|
||||
let ids = insert_clip(s, &clip, at, [40.0, 40.0], &[])?;
|
||||
let ids = insert_clip(s, &clip, at, [40.0, 40.0], if keep_inputs { &clip.inputs } else { &[] }, snap)?;
|
||||
s.selection = ids.clone();
|
||||
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
})
|
||||
@@ -134,16 +167,38 @@ fn paste(s: &mut Session, p: &J) -> Result<J> {
|
||||
fn duplicate(s: &mut Session, p: &J) -> Result<J> {
|
||||
let ids = ids_param(s, "edit.duplicate", p)?;
|
||||
let clip = clip_of(s, &ids)?;
|
||||
let outer: Vec<Connection> = s.graph()?.connections.iter().filter(|c| ids.contains(&c.to) && !ids.contains(&c.from)).cloned().collect();
|
||||
let keep = !matches!(p.get("withoutLinks"), Some(J::Bool(true)));
|
||||
let snap = crate::commands::boolp(p, "snapToGrid").unwrap_or(false);
|
||||
s.edit("Duplicate", |s| {
|
||||
let new = insert_clip(s, &clip, None, [40.0, 40.0], if keep { &outer } else { &[] })?;
|
||||
let new = insert_clip(s, &clip, None, [40.0, 40.0], if keep { &clip.inputs } else { &[] }, snap)?;
|
||||
s.selection = new.clone();
|
||||
Ok(json!({"ids": new.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
})
|
||||
}
|
||||
|
||||
fn has_deletable_selection(session: &Session) -> std::result::Result<(), String> {
|
||||
if session.annotation_selection.is_some() { has_graph(session) } else { has_selection(session) }
|
||||
}
|
||||
|
||||
fn delete_annotation(session: &mut Session) -> Result<J> {
|
||||
let selection = session.annotation_selection;
|
||||
session.edit("Delete annotation", |session| {
|
||||
let graph = session.graph_mut()?;
|
||||
match selection {
|
||||
Some(crate::AnnotationSelection::Frame(id)) => graph.frames.retain(|frame| frame.id != id),
|
||||
Some(crate::AnnotationSelection::Comment(id)) => graph.comments.retain(|comment| comment.id != id),
|
||||
None => {}
|
||||
}
|
||||
session.annotation_selection = None;
|
||||
Ok(json!({"deleted": 1}))
|
||||
})
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &J) -> Result<J> {
|
||||
if s.annotation_selection.is_some() && p.get("ids").is_none() {
|
||||
return delete_annotation(s);
|
||||
}
|
||||
|
||||
let ids = ids_param(s, "edit.delete", p)?;
|
||||
s.edit("Delete", |s| {
|
||||
s.graph_mut()?.remove_nodes(&ids);
|
||||
@@ -156,11 +211,17 @@ fn delete(s: &mut Session, p: &J) -> Result<J> {
|
||||
}
|
||||
|
||||
fn delete_relink(s: &mut Session, p: &J) -> Result<J> {
|
||||
if s.annotation_selection.is_some() && p.get("ids").is_none() {
|
||||
return delete_annotation(s);
|
||||
}
|
||||
|
||||
let ids = ids_param(s, "edit.deleteRelink", p)?;
|
||||
s.edit("Delete and relink", |s| {
|
||||
let g = s.graph_mut()?;
|
||||
for id in &ids {
|
||||
let src = g.connections.iter().find(|c| c.to == *id).map(|c| (c.from, c.from_port.clone()));
|
||||
// Port order comes from the node definition, not the order its wires were created.
|
||||
let input = s.input_ports(*id).into_iter().next();
|
||||
let g = s.graph_mut()?;
|
||||
let src = input.and_then(|port| g.input_of(*id, &port)).map(|c| (c.from, c.from_port.clone()));
|
||||
let outs: Vec<(NodeId, String)> = g.connections.iter().filter(|c| c.from == *id).map(|c| (c.to, c.to_port.clone())).collect();
|
||||
g.remove_nodes(&[*id]);
|
||||
if let Some((from, port)) = src {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
use materialcraft_core::{FunctionNode, PatternNode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum EmbeddedClipboard {
|
||||
Function { source: String, nodes: Vec<FunctionNode> },
|
||||
Pattern { source: String, nodes: Vec<PatternNode> },
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use crate::{
|
||||
FunctionEdit, FunctionGraphTarget, PatternEdit, Result, Session, cmd,
|
||||
commands::{CommandSpec, bad, has_graph},
|
||||
};
|
||||
|
||||
use materialcraft_core::{NodeId, Value};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"graph.function.edit",
|
||||
"Edit function node",
|
||||
[],
|
||||
None,
|
||||
"{target?: {kind: graph|parameter|dynamic|pattern, node?, owner?, parameter?}, edit: {action: add|move|connect|value|output, ...}, merge?: false}",
|
||||
has_graph,
|
||||
function
|
||||
),
|
||||
cmd!(
|
||||
"graph.pattern.edit",
|
||||
"Edit FX-Map node",
|
||||
[],
|
||||
None,
|
||||
"{id: owner, edit: {action: add|move|connect|disconnect|root|value, ...}, merge?: false}",
|
||||
has_graph,
|
||||
pattern
|
||||
),
|
||||
cmd!("edit.finish", "Finish edit gesture", [], None, "{} ends the current undo group", crate::commands::always, |session, _| {
|
||||
session.finish_edit();
|
||||
Ok(Json::Null)
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
fn commit(session: &mut Session, label: &str, key: Option<String>, run: impl FnOnce(&mut Session) -> Result<Json>) -> Result<Json> {
|
||||
match key {
|
||||
Some(key) => session.edit_merged(&key, label, run),
|
||||
None => session.edit(label, run),
|
||||
}
|
||||
}
|
||||
|
||||
fn function(session: &mut Session, parameters: &Json) -> Result<Json> {
|
||||
let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"})))
|
||||
.map_err(|error| bad("graph.function.edit", error.to_string()))?;
|
||||
let edit: FunctionEdit =
|
||||
serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.edit", error.to_string()))?;
|
||||
let current = target.current(session)?;
|
||||
if let FunctionEdit::Add { operation, .. } = &edit
|
||||
&& !target.available_operations(session).any(|definition| definition.id == operation)
|
||||
{
|
||||
return Err(bad("graph.function.edit", "this operation is not available in the target function graph"));
|
||||
}
|
||||
let mut graph = current.clone();
|
||||
let result = edit.apply(&mut graph).map_err(|error| bad("graph.function.edit", error))?;
|
||||
crate::graph_validation::function(&graph).map_err(|error| bad("graph.function.edit", error))?;
|
||||
let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true))
|
||||
.then(|| edit.merge_key())
|
||||
.flatten()
|
||||
.map(|key| format!("function:{}:{target:?}:{key}", session.graph));
|
||||
commit(session, "Edit Function Graph", key, |session| {
|
||||
target.replace(session, graph)?;
|
||||
Ok(result)
|
||||
})
|
||||
}
|
||||
|
||||
fn pattern(session: &mut Session, parameters: &Json) -> Result<Json> {
|
||||
let id = NodeId(parameters.get("id").and_then(Json::as_u64).ok_or_else(|| bad("graph.pattern.edit", "id is required"))?);
|
||||
let node = session.graph()?.node(id)?;
|
||||
if node.def != "fx_map" {
|
||||
return Err(bad("graph.pattern.edit", "the node is not an FX-Map"));
|
||||
}
|
||||
let value = node.params.get("pattern").or_else(|| materialcraft_nodes::find(&node.def)?.param("pattern").map(|parameter| ¶meter.default));
|
||||
let Some(Value::PatternGraph(graph)) = value else { return Err(bad("graph.pattern.edit", "missing FX-Map graph")) };
|
||||
let mut graph = (**graph).clone();
|
||||
let edit: PatternEdit =
|
||||
serde_json::from_value(parameters.get("edit").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.edit", error.to_string()))?;
|
||||
let result = edit.apply(&mut graph).map_err(|error| bad("graph.pattern.edit", error))?;
|
||||
crate::graph_validation::pattern(&graph).map_err(|error| bad("graph.pattern.edit", error))?;
|
||||
let key = (parameters.get("merge").and_then(Json::as_bool) == Some(true))
|
||||
.then(|| edit.merge_key())
|
||||
.flatten()
|
||||
.map(|key| format!("pattern:{}:{}:{key}", session.graph, id.0));
|
||||
commit(session, "Edit FX-Map graph", key, |session| {
|
||||
session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
|
||||
Ok(result)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("unknown command `{0}`")]
|
||||
UnknownCommand(String),
|
||||
#[error("`{cmd}` is not available: {why}")]
|
||||
Disabled { cmd: String, why: String },
|
||||
#[error("`{cmd}`: {msg}")]
|
||||
BadParams { cmd: String, msg: String },
|
||||
#[error(transparent)]
|
||||
Core(#[from] materialcraft_core::CoreError),
|
||||
#[error(transparent)]
|
||||
Format(#[from] materialcraft_formats::FormatError),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/// One exported file
|
||||
pub struct Exported {
|
||||
pub file: String,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
Loaded 100 of 475 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user