diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000..de64ad3 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 812eeef..2d250fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # AGENTS.md: guide for AI agents and contributors MaterialCraft is an open-source, native **node-based procedural material designer**: a clean-room @@ -13,10 +66,7 @@ TextureCraft) in user-facing text: UI, window titles, About, installers, release Machine names stay lowercase: crates (`materialcraft-*`), binaries, file names, ids (`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, @@ -106,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 @@ -183,6 +233,6 @@ after every arc of work that builds and passes. - `ROADMAP.md`: milestones, parity estimate and remaining effort. - `docs/target-app-parity.md` and `docs/gaps.md`: the assessment and the work list. -- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing. -- `plan/` (local, gitignored): execution plan and notes. +- `docs/releasing.md`: release builds and signing. +- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent. - `log/` (local, gitignored): the dev log. diff --git a/CLAUDE.md b/CLAUDE.md index 911603e..43c994c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1 @@ -# MaterialCraft: instructions for Claude - -Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository -(workspace map, golden rules including the asset and attribution rules, the definition of done). -Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps. +@AGENTS.md diff --git a/Cargo.lock b/Cargo.lock index eaec423..c3134a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2485,7 +2485,6 @@ dependencies = [ "log", "materialcraft-engine", "materialcraft-render", - "rayon", "rfd", "serde", "serde_json", diff --git a/UI_PARITY_NOTES.md b/UI_PARITY_NOTES.md deleted file mode 100644 index 5a14a77..0000000 --- a/UI_PARITY_NOTES.md +++ /dev/null @@ -1,94 +0,0 @@ -# UI parity drop (re-based on main after the primitive rewrite) - -What changed, per area of the reference screenshots. Everything is wired to the engine; no empty settings. - -## Re-port onto main (2026-11-06) -- Built on `origin/main` (1a468e7, PR #125). Everything from the 123-improving-ui drop was re-applied in the new - layout: one type per file, new engine commands in their own module (`engine/src/resource_cmds.rs`, registered by - one line in `commands.rs`), 3D view settings in `engine/src/view3d_settings.rs`, the 3D view split into - `ui-egui/src/view3d/{actions,menus,overlays,settings,side_strip}.rs`, the explorer actions in `explorer/{actions,package_menu}.rs`, - the new-graph dialog in `new_graph_dialog.rs`, graph toolbar tools in `graph/toolbar_tools.rs`, auto conversion in `graph/auto_convert.rs`. -- Upstream features kept as they are: the material-preview assignment (View in 3D view, graph drop onto the 3D view, - `view.3d.outputs`, `view.3d.clear`), the Material assignment list now lives at the bottom of the 3D view's Materials menu; - the function and FX-Map pattern editors; `snapToGrid` from `prefs.snap_to_grid`. -- `.mcraft` is gone upstream, so everything here is SBS only: linked bitmaps are written as `` without `binembedded`, - plugins load `.sbs` packages, the Plugin Manager installs `.sbs` files. -- Library: the reference's generator/filter groups are no longer Rust nodes ("SBS library nodes belong in SBS graphs"), so - the library shows the 26 atomic nodes, graph items, the 85 function ops (added through the function editor), the package's - graphs by kind, and the graphs of loaded plugin packages filed under each graph's `attributes.category` (else "PBR materials ▸ Plugins"). - The remaining reference groups stay listed, greyed, with a 0 count. - -## Menu pass (2026-11-06, late) -- Library: the "SDF functions" group is now "MCF functions"; empty reference groups explain on hover that library - packages (Tools ▸ Plugin Manager) fill them. -- Help menu points at getartcraft.com: Documentation/website → the MaterialCraft app page, Tutorials → /tutorials, - What's new → /news, System requirements → /faq, Support and feedback → /support, Discord; release notes and bug - reports stay on GitHub. Home and About carry the same links. -- Home screen: Samples shows the starter templates and the graphs of loaded library packages (click imports the graph). -- Graph toolbar quick-insert row now has every atomic node (added SVG, Text, Gradient Dynamic, Motion Blur, - Value Processor, Input Color, Input Value). - -## Fixes (2026-11-07) -- Height in the 3D view: the "Material outputs" template now derives its Normal output from the Height (a - `normal` node between them) like the old base material did, so a height wired in shows as relief and shading - right away; with the normal map switched off (Material page ▸ Use maps) the relief shades from its own geometry. -- 3D view ▸ Display ▸ Preview size is a submenu (a combo box inside a menu closed the menu before it applied). -- Navigation pins can be dragged (snap to grid applies), and right-click gives Rename (in place), Go to pin and - Delete; new engine command `graph.pin.edit {id, name?, at?}` in `engine/src/pin_commands.rs`. -- Function graph library: operations grouped by category (collapsible, with an icon and a count), each with a - text badge saying what it is ("F2", "+", "≥", "sin", "if", "(F1)", "$F1"…), its inputs, and a tooltip - describing it; the search also matches the badge. Function node cards show the same badge in their body. - -## Menus (File / Edit / Tools / Windows / Help) -- File: New ▸ Graph / Empty package, Open, Recent, Save, Save as, Save a copy as, Export with dependencies, Import bitmap, Link bitmap, Export outputs, Export material, Send to TextureCraft, Close, Quit. -- Tools: Switch engine (F9: CPU thread count, rayon pool), Cancel rendering, Suspend engine, Clear cache, Reload resources, Plugin Manager. -- Windows: panels, Main toolbar toggle, Dependency Manager, maximize/unmaximize (Shift+Space), reset layout. -- Help: docs, tutorials, release notes, requirements, automation, feedback, bug report, export log, about. No vendor names, no Partners. -- Status bar: "MC Engine: CPU (n threads)". - -## Explorer -- Package context menu: New ▸, Import ▸ (Bitmap, Graph from a package), Link ▸ Bitmap, Reload, Save/Save as/Save a copy as, Export with dependencies, Send to ▸ TextureCraft, Copy/Paste (graphs), Close package, Compute Outputs, Show in Explorer, Dependency Manager. -- Graph context menu: Open (Return), Copy, Paste, Remove (Del), Rename (F2, in place), View Outputs In 3D View, Compute Outputs, Export outputs. -- Resources: Relink, Add a Bitmap node, Remove. Linked bitmaps show a link icon. -- Default graph name is Material_Graph. -- Not done: "Open dependencies" (we have no package-to-package links to open). - -## Library -- Tree: All nodes, Favorites (persisted, right-click a tile), Graph items (Comment, Frame, Pin + inputs/outputs/dot), Atomic nodes, FxMap nodes, Function nodes ▸ (groups), Texture generators ▸, Filters ▸, Material filters ▸ (ours + planned empty groups greyed with 0), Mesh-based generators, Spline & Path tools, SDF functions (planned, greyed), Functions (function graphs of the package), PBR materials ▸ This package / Plugins, Values ▸ Constant. -- Collapsible groups with counts, search, icon/list view, tile size slider. -- Function nodes drop into the open function editor; plugin graphs are copied into the package on drop (file.importGraph). - -## New graph dialog -- Category dropdown, group headings, ⓘ template info, width/height with a link toggle, "Create graph in". - -## Graph toolbar -- Row 1: frame all, 1:1, screenshot (PNG), graph info popup, find node, thumbnails, cook times, straight/curved wires, grid, snap, compute, clean up; right: Stack checkbox + align buttons, Parent size with link and reset. -- Row 2: atomic quick-insert, comment, dot, frame, pin. - -## 3D view -- Menus: Scene (11 scenes incl. Plane hi-res, Cloth, Rounded cylinder, Sphere 2 tiles; Display UVs in 2D View; Load/Save state file; Save as default; Reset), Materials ▸ Default (Edit properties, 9 shaders, reset common/material, create graph), Lights, Camera (Frame F, viewpoints, Save Render Alt+S, Copy Render, Reset Position R), Environment, Display (wireframe, axis, backface culling, bounding box, grid, light gizmos, resolution/stats/FPS overlays), Renderer (Edit settings). -- "Edit properties" pages in the Properties panel: Camera (focal length, projection, background type/colour, render resolution, clip planes), Lights (ambient + 2 point lights with colour strips), Environment (enabled, exposure, rotation dial/turns/degrees, environment preview), Renderer (resolution, scale, samples, AO rays), Material (OpenPBR sections: UVs, Base, Specular, Transmission, Subsurface, Coat, Fuzz, Emission, Thin-film, Geometry, Height; each with the "use map" checkbox, sRGB/Float/HSV colour strips). -- Left tool strip: frame, property pages, display toggles. -- Renderer: point lights with shadows, ambient, env on/off, 9 shading models, common values, wireframe, backface culling, clip planes, background colour/environment, FOV/ortho, tessellation factor. -- Engine: `view.3d` takes nested objects (camera/lights/renderer/display/material), `view.3d.reset {what}`, `view.3d.state`, `view.3d.loadState`. - -## Preferences (Edit ▸ Preferences) -- Tabs General / Projects / Graph / 3D View / Bakers / Library / Shortcuts with OK / Cancel / Apply. -- General: recent count, history size (session.settings), language (English for now), appearance, invert zoom, save/export path mode + fixed folder, temp (backup) folder, image cache budget, cook threads, auto backup interval + versions (rotating files), cooking size limit (caps previews and exports). -- Projects: plugins folder, backups folder, default 3D state (save/clear), default lighting state, library view, preview size, 3D pan limit/speed. -- Graph: Tab menu, drag-create, 3D on open, thumbnails, 2D on open, auto display new node, auto colour/grayscale conversion node, grid/snap/wires/timings. -- 3D View: environment hidden by default, viewport scaling, sample count. -- Bakers: baking threads. Library: rebuild thumbnails, clear cache. Shortcuts: node creation shortcuts (click a field, press keys). -- Skipped on purpose: UDIM, .sbsar publishing. - -## Plugin Manager (Tools ▸ Plugin Manager) -- Filter, Plugins/Loaded table, Browse (opens the plugins folder), Install (copies .sbs files in), Refresh. -- A plugin = a package file or a folder with package files + optional plugin.json {name, version, author, description} in Documents/MaterialCraft/plugins. Loaded plugins' graphs show in the library under PBR materials ▸ Plugins. - -## Engine commands added -file.linkBitmap, file.reloadResources, file.deleteResource, file.importGraph, file.packageGraphs, file.saveCopy, file.exportWithDependencies, graph.add, session.settings, view.3d.reset {what}, view.3d.state, view.3d.loadState; `view.3d` nested objects. Resources can be linked (SBS keeps relative links). - -## Checks run here -cargo fmt --all, cargo check --workspace --all-targets, cargo clippy --workspace --all-targets -- -D warnings, cargo xtask layers, -cargo test --workspace --release --no-fail-fast. `cargo xtask wasm` could not run in this container (the wasm target cannot be -downloaded here); please run it on your side. diff --git a/_to_delete/automation_server.rs b/_to_delete/automation_server.rs deleted file mode 100644 index 4d2dc1f..0000000 --- a/_to_delete/automation_server.rs +++ /dev/null @@ -1,545 +0,0 @@ -//! 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 std::sync::{Arc, Mutex, PoisonError}; - -use base64::Engine as _; -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_json::{Value, json}; - -use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text}; -use crate::headless::batch_reply; -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>), - /// The running desktop app, over its control channel. - Bridge(Arc), -} - -#[derive(Clone)] -pub struct MaterialcraftMcp { - backend: Arc, - tool_router: ToolRouter, -} - -// --------------------------------------------------------------------------------------------- -// 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, -} - -#[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, - /// Only nodes in this library category, e.g. "Noises", "Patterns", "Filters/Blurs". - #[serde(default, skip_serializing_if = "Option::is_none")] - pub category: Option, -} - -#[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, -} - -#[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, -} - -#[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, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub name: Option, - /// 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, -} - -#[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, - /// 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, -} - -#[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, - /// 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, -} - -#[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, -} - -#[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, -} - -#[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, - /// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pattern: Option, - /// 8, 16 or 32 bits (default: the graph's output format). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub depth: Option, - /// 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, - /// Graph index (default: the open graph). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub graph: Option, -} - -#[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, - /// 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, - /// 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, -} - -#[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, - /// Pixels, 16..2048. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub width: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub height: Option, - /// Camera yaw/pitch in degrees for this render only. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub yaw: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pitch: Option, - /// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub scene: Option, - /// 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, - /// 2D: the output port index. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub port: Option, - /// Cook at the full graph size instead of the preview size. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub full: Option, - /// 3D: UV repeats of the material on the scene for this render only. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tiling: Option, - /// 3D beauty render: a finer displaced mesh, ambient occlusion and a shadowed key light (slower). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub hq: Option, - /// With `hq`: displacement depth in scene radii (default: the view's height depth). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub displacement: Option, -} - -#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] -pub struct ScreenshotParams { - /// `3d` (default) or `2d`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub view: Option, -} - -#[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, -} - -// --------------------------------------------------------------------------------------------- -// Results - -fn ok_json(v: &Value) -> CallToolResult { - match json_text(v) { - Ok(text) => CallToolResult::success(vec![Content::text(text)]), - Err(e) => fail(e), - } -} - -fn fail(e: impl std::fmt::Display) -> CallToolResult { - CallToolResult::error(vec![Content::text(e.to_string())]) -} - -fn to_result(r: Result) -> Result { - Ok(match r { - Ok(v) => ok_json(&v), - Err(e) => fail(e), - }) -} - -/// A `{width, height, png: base64}` reply (render or app screenshot) as image content. -fn image_result(r: Result, note: &str, refit: bool) -> Result { - 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()))?; - if !refit { - check_png(b64.len() / 4 * 3)?; - return Ok(b64.to_string()); - } - let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| AutomationError::Other(format!("bad PNG data: {e}")))?; - Ok(base64::engine::general_purpose::STANDARD.encode(fit_png(bytes, MAX_PNG_SIDE)?)) - }); - Ok(match png { - Ok(b64) => CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note.to_string())]), - Err(e) => fail(e), - }) -} - -fn params(p: &T) -> Value { - serde_json::to_value(p).unwrap_or(Value::Null) -} - -impl MaterialcraftMcp { - pub fn headless(h: Headless) -> Self { - Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h)))) - } - - pub fn bridge(client: BridgeClient) -> Self { - Self::with_backend(Backend::Bridge(Arc::new(client))) - } - - pub fn with_backend(backend: Backend) -> Self { - MaterialcraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() } - } - - /// 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()))?; - Ok(()) - } - - fn is_bridge(&self) -> bool { - matches!(*self.backend, Backend::Bridge(_)) - } - - /// One control-channel method on the backend. - async fn call(&self, method: &str, p: Value) -> Result { - 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. - 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}`")))) - } - Backend::Bridge(b) => match method { - "command.run" => { - let id = p.get("id").and_then(Value::as_str).unwrap_or_default(); - authorize_command(id, p.get("params").unwrap_or(&Value::Null))?; - 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" | "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, - }, - } - } - - async fn run(&self, id: &str, p: Value) -> Result { - self.call("command.run", json!({"id": id, "params": p})).await - } - - async fn bridge_only(&self, method: &str, p: Value) -> Result { - if self.is_bridge() { - self.call(method, p).await - } else { - Err(bad(format!( - "`{method}` needs the running app: start `materialcraft --control ` and run `materialcraft-cli mcp --bridge ` (headless renders: view_render)" - ))) - } - } -} - -// --------------------------------------------------------------------------------------------- -// Tools - -#[tool_router] -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 { - to_result(self.call("session.inspect", json!({})).await) - } - - #[tool(description = "List engine commands: id, label, menu path, shortcut, params doc and whether it can run now.")] - async fn command_list(&self, Parameters(p): Parameters) -> Result { - to_result(self.call("command.list", params(&p)).await) - } - - #[tool(description = "Run an engine command by id with JSON params (see command_list). Runs with defaults, never opens a \ - dialog. Commands given host paths are disabled: use package_open, package_save, bitmap_import and outputs_export.")] - async fn command_run(&self, Parameters(p): Parameters) -> Result { - to_result(self.call("command.run", params(&p)).await) - } - - #[tool(description = "Run several commands in order: steps [{id, params}]. Stops at the first error. Returns {completed, \ - results, failed: {index, id, error} | null}; a failed batch is a tool error.")] - async fn command_batch(&self, Parameters(p): Parameters) -> Result { - if p.steps.len() > MAX_BATCH_STEPS { - return Ok(fail(format!("at most {MAX_BATCH_STEPS} steps per batch"))); - } - let reply = if self.is_bridge() { - let mut results = Vec::new(); - let mut failed = None; - for (i, s) in p.steps.iter().enumerate() { - match self.call("command.run", params(s)).await { - Ok(v) => results.push(v), - Err(e) => { - failed = Some((i, s.id.as_str(), e.to_string())); - break; - } - } - } - batch_reply(results, failed) - } else { - match self.call("command.batch", params(&p)).await { - Ok(v) => v, - Err(e) => return Ok(fail(e)), - } - }; - Ok(if reply["failed"].is_null() { ok_json(&reply) } else { fail(json_text(&reply).unwrap_or_else(|e| e.to_string())) }) - } - - #[tool(description = "The node library: every node's id, label, category, input and output ports and parameters (id, \ - default, range, enum options). Filter by text or category.")] - async fn library_list(&self, Parameters(p): Parameters) -> Result { - to_result(self.run("library.list", params(&p)).await) - } - - #[tool(description = "Add a new graph to the package from a template and open it. Returns {graph, name}.")] - async fn graph_new(&self, Parameters(p): Parameters) -> Result { - to_result(self.run("file.new", params(&p)).await) - } - - #[tool(description = "Add a node to the open graph (optionally wired from another node's output). Returns {id}.")] - async fn node_add(&self, Parameters(p): Parameters) -> Result { - to_result(self.run("graph.node.add", params(&p)).await) - } - - #[tool(description = "Wire an output port of one node into an input port of another (replacing what fed that input).")] - async fn node_connect(&self, Parameters(p): Parameters) -> Result { - to_result(self.run("graph.connect", params(&p)).await) - } - - #[tool(description = "Set one parameter of a node.")] - async fn node_param(&self, Parameters(p): Parameters) -> Result { - to_result(self.run("graph.node.param", params(&p)).await) - } - - #[tool( - description = "Open an .sbs or .mcraft package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)." - )] - async fn package_open(&self, Parameters(p): Parameters) -> Result { - 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." - )] - async fn package_save(&self, Parameters(p): Parameters) -> Result { - to_result(self.call("package.save", params(&p)).await) - } - - #[tool(description = "Embed an image (path relative to the read root) as a bitmap resource. Returns its name, for a \ - `bitmap` node's `resource` parameter.")] - async fn bitmap_import(&self, Parameters(p): Parameters) -> Result { - to_result(self.call("bitmap.import", params(&p)).await) - } - - #[tool(description = "Cook a graph at full size and write every output (base color, normal, roughness, …) into a folder \ - relative to the write root. Returns the written files.")] - async fn outputs_export(&self, Parameters(p): Parameters) -> Result { - 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) -> Result { - 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) -> Result { - let note = format!("render {}", params(&p)); - image_result(self.call("render", params(&p)).await, ¬e, false) - } - - #[tool(description = "Bridge mode: PNG of the live app's 3D or 2D view.")] - async fn view_screenshot(&self, Parameters(p): Parameters) -> Result { - image_result(self.bridge_only("view.screenshot", params(&p)).await, "screenshot of an app view", true) - } - - #[tool(description = "Bridge mode: PNG of the whole app window (downscaled to 2048 px a side at most).")] - async fn ui_screenshot(&self) -> Result { - image_result(self.bridge_only("ui.screenshot", json!({})).await, "screenshot of the app window", true) - } - - #[tool(description = "Bridge mode: the app's UI state (panels, windows, graph view camera, node rectangles on screen, toasts).")] - async fn ui_inspect(&self) -> Result { - to_result(self.bridge_only("ui.inspect", json!({})).await) - } - - #[tool(description = "Bridge mode: activate a menu item by id like a click (may open a window). ui.menu.list lists ids.")] - async fn ui_menu_invoke(&self, Parameters(p): Parameters) -> Result { - to_result(self.bridge_only("ui.menu.invoke", params(&p)).await) - } - - #[tool(description = "Bridge mode: synthesize mouse, keyboard and text input in the app window (clicks, drags between \ - node ports, scrolling, shortcuts, typing). Positions are window points (see ui_inspect for node rectangles).")] - async fn ui_input(&self, Parameters(p): Parameters) -> Result { - to_result(self.bridge_only("ui.input", params(&p)).await) - } -} - -#[tool_handler( - router = self.tool_router, - 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 \ - / 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, outputs_export or material_export (.mcmat for TextureCraft). Undo: command_run edit.undo." -)] -impl ServerHandler for MaterialcraftMcp {} - -#[cfg(test)] -mod tests { - use super::*; - use crate::headless::Filesystem; - - #[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 Backend::Headless(h) = &*mcp.backend else { panic!("headless") }; - let h2 = h.clone(); - let _ = tokio::task::spawn_blocking(move || { - let _g = h2.lock().unwrap(); - panic!("boom") - }) - .await; - 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))); - assert_eq!(r.is_error, Some(true)); - } -} diff --git a/_to_delete/core_function.rs b/_to_delete/core_function.rs deleted file mode 100644 index 4e49aaf..0000000 --- a/_to_delete/core_function.rs +++ /dev/null @@ -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>, - /// The constant (`const_*`), the variable name (`get_*`) or the input index (`sample_*`). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub value: Option, - #[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, - #[serde(default)] - pub output: Option, -} - -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) -> 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 - } -} diff --git a/_to_delete/formats_material.rs b/_to_delete/formats_material.rs deleted file mode 100644 index 2b11707..0000000 --- a/_to_delete/formats_material.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! Portable materials (`.mcmat`): a cooked material other apps (TextureCraft) apply without a -//! graph engine, plus the package it came from so an app that can run `materialcraft-cli` -//! re-cooks it with other parameter values, sizes and mesh maps. -//! -//! A zip: `material.json` ([`Manifest`]), `maps/.png` (8-bit sRGB for color usages, -//! 16-bit linear otherwise; normals in the OpenGL convention) and `source.mcraft`. - -use std::collections::BTreeMap; -use std::io::{Cursor, Read, Write}; - -use materialcraft_core::{ExposedParam, Value}; -use serde::{Deserialize, Serialize}; - -use crate::{FormatError, MAX_JSON, MAX_RESOURCE, Result}; - -/// The portable material extension. -pub const MATERIAL_EXT: &str = "mcmat"; -/// `format` of every manifest. -pub const FORMAT: &str = "craft-material"; -/// Newest manifest version this build reads and writes. -pub const VERSION: u32 = 1; -const MANIFEST: &str = "material.json"; -const SOURCE: &str = "source.mcraft"; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Manifest { - pub format: String, - pub version: u32, - pub name: String, - /// The graph of the source package the maps were cooked from. - pub graph: String, - /// Size of the maps in pixels. - pub size: [u32; 2], - pub maps: Vec, - /// Parameters other apps may change (scalar, vector, color, toggle and option inputs). - pub parameters: Vec, - /// Image inputs of the graph, fed from mesh maps by identifier. - pub inputs: Vec, - #[serde(default)] - pub presets: Vec, - pub source: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MapEntry { - /// Usage id: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, - /// `emissive`, `opacity`, `specular`. - pub usage: String, - pub file: String, - /// `srgb` or `linear`. - pub color_space: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Parameter { - #[serde(flatten)] - pub param: ExposedParam, - /// The value the maps were cooked with. - pub value: Value, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImageInput { - pub identifier: String, - /// `gray` or `color`. - pub kind: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct PresetEntry { - pub name: String, - pub values: BTreeMap, -} - -/// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear). -pub fn srgb_usage(usage: &str) -> bool { - matches!(usage, "baseColor" | "emissive" | "specular") -} - -/// Whether other apps can set a value of this type from the manifest. -pub fn portable(v: &Value) -> bool { - matches!( - v, - Value::Float(_) - | Value::Float2(_) - | Value::Float3(_) - | Value::Float4(_) - | Value::Int(_) - | Value::Int2(_) - | Value::Bool(_) - | Value::Color(_) - | Value::Enum(_) - ) -} - -/// Write a portable material: `manifest` (its `source` is set here), the encoded maps named by -/// `manifest.maps[].file`, and the source package bytes. -pub fn write_material(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> Result> { - let io = |e: zip::result::ZipError| FormatError::Io(e.to_string()); - let manifest = Manifest { source: SOURCE.into(), ..manifest.clone() }; - let json = serde_json::to_vec_pretty(&manifest).map_err(|e| FormatError::Io(e.to_string()))?; - let mut buf = Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); - // Maps and the package are already compressed. - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - z.start_file(MANIFEST, deflate).map_err(io)?; - z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?; - for (file, bytes) in maps { - z.start_file(file.as_str(), stored).map_err(io)?; - z.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?; - } - z.start_file(SOURCE, stored).map_err(io)?; - z.write_all(source).map_err(|e| FormatError::Io(e.to_string()))?; - z.finish().map_err(io)?; - } - Ok(buf.into_inner()) -} - -/// Read a portable material's manifest and source package bytes. -pub fn read_material(bytes: &[u8]) -> Result<(Manifest, Vec)> { - let bad = |m: String| FormatError::BadPackage(format!("portable material: {m}")); - let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| bad(e.to_string()))?; - let mut read = |name: &str, cap: u64| -> Result> { - let mut data = Vec::new(); - z.by_name(name).map_err(|_| bad(format!("{name} is missing")))?.take(cap).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?; - Ok(data) - }; - let manifest: Manifest = serde_json::from_slice(&read(MANIFEST, MAX_JSON)?).map_err(|e| bad(e.to_string()))?; - if manifest.format != FORMAT || manifest.version > VERSION { - return Err(bad(format!("unsupported {} version {}", manifest.format, manifest.version))); - } - let source = read(&manifest.source, MAX_RESOURCE)?; - Ok((manifest, source)) -} - -/// Whether `bytes` look like a portable material (a zip with `material.json`). -pub fn is_material(bytes: &[u8]) -> bool { - zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(MANIFEST).is_ok()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn manifest() -> Manifest { - let param = ExposedParam { - id: "rough".into(), - label: "Roughness".into(), - group: String::new(), - default: Value::Float(0.5), - min: 0.0, - max: 1.0, - options: Vec::new(), - }; - Manifest { - format: FORMAT.into(), - version: VERSION, - name: "Bricks".into(), - graph: "Bricks".into(), - size: [64, 64], - maps: vec![MapEntry { usage: "baseColor".into(), file: "maps/baseColor.png".into(), color_space: "srgb".into() }], - parameters: vec![Parameter { param, value: Value::Float(0.25) }], - inputs: vec![ImageInput { identifier: "curvature".into(), kind: "gray".into() }], - presets: Vec::new(), - source: String::new(), - } - } - - #[test] - fn round_trips_and_rejects_newer_versions() { - let m = manifest(); - let bytes = write_material(&m, &[("maps/baseColor.png".into(), vec![1, 2, 3])], b"pkg").unwrap(); - assert!(is_material(&bytes)); - let (back, source) = read_material(&bytes).unwrap(); - assert_eq!(back, Manifest { source: SOURCE.into(), ..m.clone() }, "the writer names the source entry"); - assert_eq!(source, b"pkg"); - // Parameters are flat objects with the value in the API's typed form. - let json = serde_json::to_value(&m).unwrap(); - assert_eq!(json["parameters"][0]["id"], "rough"); - assert_eq!(json["parameters"][0]["value"], serde_json::json!({"t": "float", "v": 0.25})); - - let newer = Manifest { version: VERSION + 1, ..m }; - assert!(read_material(&write_material(&newer, &[], b"").unwrap()).is_err()); - assert!(!is_material(b"not a zip")); - assert!(read_material(b"garbage").is_err()); - } -} diff --git a/_to_delete/formats_sbs.rs b/_to_delete/formats_sbs.rs deleted file mode 100644 index 7fca6c2..0000000 --- a/_to_delete/formats_sbs.rs +++ /dev/null @@ -1,2148 +0,0 @@ -//! SBS packages, MaterialCraft's main project format, read and written with clean-room code built from public documentation and samples. -//! Reading keeps going past unknown nodes: they become [`MISSING_NODE`] placeholders and each gap is in [`SbsRead::warnings`]. -//! Writing embeds bitmaps and adds an exact copy of the package in a trailing comment, used while the `` hash matches. - -use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; -use std::fmt::Write as _; -use std::io::{Read, Write}; - -use base64::Engine as _; -use materialcraft_core::{ - BaseParams, Comment, Connection, ExposedParam, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat, Package, Resource, - ResourceBytes, SizeMode, Value, linear_to_srgb, missing_ports, srgb_to_linear, -}; -use materialcraft_nodes::{PortKind, find}; -use roxmltree::Node as XmlNode; - -use crate::{FormatError, Result}; - -#[path = "sbs_functions.rs"] -mod functions; - -/// The SBS package extension. -pub const SBS_EXT: &str = "sbs"; - -const MAX_SBS_BYTES: usize = 256 << 20; -const MAX_EMBEDDED_BYTES: usize = 256 << 20; -const MAX_XML_NODES: u32 = 8_000_000; -const MAX_GRAPHS: usize = 4096; -const MAX_NODES: usize = 100_000; -const MAX_RESOURCES: usize = 4096; -/// Distinct warning lines kept per read; the rest are counted. -const MAX_WARNINGS: usize = 600; -/// Size of the parsed head [`is_sbs`] sniffs. -const SNIFF_BYTES: usize = 4096; - -/// Marks the exact MaterialCraft copy at the end of a written package. -const EXACT_MARK: &str = "materialcraft-package"; -const EXACT_VERSION: u32 = 1; -/// Dependency file name of MaterialCraft library nodes written as instances. -const LIBRARY_DEPENDENCY: &str = "materialcraft://library.sbs"; -/// The dependency file name a package uses for itself. -const SELF_DEPENDENCY: &str = "?himself"; -const FORMAT_VERSION: &str = "1.1.0.202401"; -/// The first uid the writer hands out (any value works; large ones stay clear of small hand-written uids). -const FIRST_UID: u64 = 1_000_000_000; - -/// Offset between an SBS node position (its center) and MaterialCraft's (its top-left corner), in graph units. -const NODE_HALF_SIZE: [f32; 2] = [50.0, 40.0]; - -/// A read SBS package. -#[derive(Debug)] -pub struct SbsRead { - pub pkg: Package, - /// What could not be read exactly (missing nodes, unsupported parameters, unavailable resources). - pub warnings: Vec, - /// Whether the package came from MaterialCraft's exact copy, so nothing was lost. - pub exact: bool, -} - -/// Whether `bytes` look like an SBS package: XML whose root element is ``. -pub fn is_sbs(bytes: &[u8]) -> bool { - let head = String::from_utf8_lossy(&bytes[..bytes.len().min(SNIFF_BYTES)]); - let mut rest = head.trim_start_matches('\u{feff}'); - - // Skip the XML declaration and comments before the root element - loop { - rest = rest.trim_start(); - let (skip_open, skip_close) = if rest.starts_with("") - } else if rest.starts_with("") - } else { - break; - }; - match rest[skip_open.len()..].find(skip_close) { - Some(end) => rest = &rest[skip_open.len() + end + skip_close.len()..], - None => return false, - } - } - - rest.strip_prefix("' || c == '/' || c.is_whitespace())) -} - -// --------------------------------------------------------------------------------------------- -// Warnings -// --------------------------------------------------------------------------------------------- - -/// Warning lines, deduplicated with counts, in first-seen order. -#[derive(Default)] -struct Warnings { - lines: Vec<(String, usize)>, - line_index: HashMap, -} - -impl Warnings { - fn add(&mut self, message: impl Into) { - let message = message.into(); - if let Some(line) = self.line_index.get(&message).and_then(|&i| self.lines.get_mut(i)) { - line.1 += 1; - return; - } - - self.line_index.insert(message.clone(), self.lines.len()); - self.lines.push((message, 1)); - } - - fn finish(self) -> Vec { - let total = self.lines.len(); - let mut out: Vec = - self.lines.into_iter().take(MAX_WARNINGS).map(|(line, count)| if count > 1 { format!("{line} (×{count})") } else { line }).collect(); - if total > MAX_WARNINGS { - out.push(format!("…and {} more warnings", total - MAX_WARNINGS)); - } - out - } -} - -// --------------------------------------------------------------------------------------------- -// Atomic filters -// --------------------------------------------------------------------------------------------- - -/// How an SBS parameter becomes a MaterialCraft one. -#[derive(Clone, Copy, PartialEq)] -enum ParamConversion { - /// By the MaterialCraft parameter's type. - ByType, - /// An SBS boolean that is `true` for option 0 of a two-option MaterialCraft choice. - TrueIsFirstOption, -} - -use ParamConversion::{ByType, TrueIsFirstOption}; - -/// An SBS atomic filter and the MaterialCraft atomic node it maps to. -struct FilterMap { - sbs: &'static str, - def: &'static str, - /// (SBS input identifier, MaterialCraft input port). - inputs: &'static [(&'static str, &'static str)], - /// (SBS parameter, MaterialCraft parameter, conversion). - params: &'static [(&'static str, &'static str, ParamConversion)], -} - -const FILTERS: &[FilterMap] = &[ - FilterMap { sbs: "uniform", def: "uniform", inputs: &[], params: &[("outputcolor", "color", ByType), ("colorswitch", "mode", TrueIsFirstOption)] }, - FilterMap { - sbs: "blend", - def: "blend", - inputs: &[("source", "foreground"), ("destination", "background"), ("opacity", "mask")], - params: &[("blendingmode", "mode", ByType), ("opacitymult", "opacity", ByType)], - }, - FilterMap { sbs: "blur", def: "blur", inputs: &[("input1", "input")], params: &[("intensity", "intensity", ByType)] }, - FilterMap { - sbs: "shuffle", - def: "channels_shuffle", - inputs: &[("input1", "input1"), ("input2", "input2")], - params: &[("channelred", "red", ByType), ("channelgreen", "green", ByType), ("channelblue", "blue", ByType), ("channelalpha", "alpha", ByType)], - }, - FilterMap { sbs: "curve", def: "curve", inputs: &[("input1", "input")], params: &[] }, - FilterMap { - sbs: "dirmotionblur", - def: "directional_blur", - inputs: &[("input1", "input")], - params: &[("intensity", "intensity", ByType), ("mblurangle", "angle", ByType)], - }, - FilterMap { - sbs: "directionalwarp", - def: "directional_warp", - inputs: &[("input1", "input"), ("inputintensity", "intensity_input")], - params: &[("intensity", "intensity", ByType), ("warpangle", "angle", ByType)], - }, - FilterMap { - sbs: "distance", - def: "distance", - inputs: &[("mask", "mask"), ("source", "source")], - params: &[("distance", "distance", ByType), ("combinedistance", "combine", ByType)], - }, - FilterMap { - sbs: "emboss", - def: "emboss", - inputs: &[("input1", "input"), ("inputgradient", "height")], - params: &[ - ("intensity", "intensity", ByType), - ("lightangle", "light_angle", ByType), - ("highlightcolor", "highlight", ByType), - ("shadowcolor", "shadow", ByType), - ], - }, - FilterMap { - sbs: "dyngradient", - def: "gradient_dynamic", - inputs: &[("input1", "input"), ("input2", "gradient"), ("inputgradient", "gradient")], - params: &[("position", "position", ByType), ("orientation", "orientation", ByType)], - }, - FilterMap { sbs: "gradient", def: "gradient_map", inputs: &[("input1", "input")], params: &[("colorswitch", "mode", TrueIsFirstOption)] }, - FilterMap { sbs: "grayscaleconversion", def: "grayscale_conversion", inputs: &[("input1", "input")], params: &[] }, - FilterMap { - sbs: "hsl", - def: "hsl", - inputs: &[("input1", "input")], - params: &[("hue", "hue", ByType), ("saturation", "saturation", ByType), ("luminance", "lightness", ByType)], - }, - FilterMap { sbs: "bitmap", def: "bitmap", inputs: &[], params: &[] }, - FilterMap { - sbs: "levels", - def: "levels", - inputs: &[("input1", "input")], - params: &[ - ("levelinlow", "in_low", ByType), - ("levelinmid", "in_mid", ByType), - ("levelinhigh", "in_high", ByType), - ("leveloutlow", "out_low", ByType), - ("levelouthigh", "out_high", ByType), - ], - }, - FilterMap { - sbs: "normal", - def: "normal", - inputs: &[("input1", "input")], - params: &[("intensity", "intensity", ByType), ("inversedy", "format", TrueIsFirstOption), ("input2alpha", "height_alpha", ByType)], - }, - FilterMap { - sbs: "pixelprocessor", - def: "pixel_processor", - inputs: &[("input", "input0"), ("input:1", "input1"), ("input:2", "input2"), ("input:3", "input3")], - params: &[], - }, - FilterMap { sbs: "valueprocessor", def: "value_processor", inputs: &[("input", "input0")], params: &[] }, - FilterMap { sbs: "sharpen", def: "sharpen", inputs: &[("input1", "input")], params: &[("intensity", "intensity", ByType)] }, - FilterMap { - sbs: "transformation", - def: "transformation", - inputs: &[("input1", "input")], - params: &[("offset", "offset", ByType), ("mattecolor", "matte", ByType)], - }, - FilterMap { sbs: "warp", def: "warp", inputs: &[("input1", "input"), ("inputgradient", "gradient")], params: &[("intensity", "intensity", ByType)] }, - FilterMap { sbs: "passthrough", def: "dot", inputs: &[("input", "input"), ("input1", "input")], params: &[] }, - FilterMap { sbs: "text", def: "text", inputs: &[], params: &[("text", "text", ByType)] }, - FilterMap { sbs: "svg", def: "svg", inputs: &[], params: &[] }, - FilterMap { sbs: "fxmaps", def: "fx_map", inputs: &[], params: &[] }, -]; - -/// SBS parameters every node has, read as base parameters. -const BASE_PARAMS: &[&str] = &["outputsize", "format", "randomseed", "tiling", "pixelsize", "pixelratio", "quality"]; - -/// Filter parameters handled in code or knowingly ignored, so they raise no warning. -const HANDLED_PARAMS: &[(&str, &str)] = &[ - ("bitmap", "bitmapresourcepath"), - ("bitmap", "colorspace"), - ("grayscaleconversion", "channelsweights"), - ("transformation", "matrix22"), - ("curve", "exposecurve"), -]; - -fn filter_by_sbs_name(name: &str) -> Option<&'static FilterMap> { - FILTERS.iter().find(|f| f.sbs == name) -} - -fn filter_by_def(def: &str) -> Option<&'static FilterMap> { - FILTERS.iter().find(|f| f.def == def) -} - -/// The MaterialCraft usage index of an SBS usage name; unknown names are "any". -fn usage_index(name: &str) -> u32 { - let ids = materialcraft_nodes::atomic::USAGE_IDS; - let name = name.trim(); - let index = ids.iter().position(|u| u.eq_ignore_ascii_case(name)).or_else(|| name.eq_ignore_ascii_case("diffuse").then_some(0)); - index.unwrap_or(ids.len().saturating_sub(1)) as u32 -} - -fn usage_name(index: u32) -> &'static str { - materialcraft_nodes::atomic::USAGE_IDS.get(index as usize).copied().unwrap_or("any") -} - -// --------------------------------------------------------------------------------------------- -// Values -// --------------------------------------------------------------------------------------------- - -/// A constant as SBS stores it. -#[derive(Clone, Debug, PartialEq)] -enum SbsValue { - Floats(Vec), - Ints(Vec), - Bool(bool), - Text(String), -} - -/// Up to 16 whitespace-separated floats; bad or non-finite ones read as 0. -fn parse_floats(text: &str) -> Vec { - text.split_whitespace().take(16).map(|t| t.parse::().ok().filter(|v| v.is_finite()).unwrap_or(0.0)).collect() -} - -/// Up to 16 whitespace-separated integers, saturated to `i32`; bad ones read as 0. -fn parse_ints(text: &str) -> Vec { - let parse = |t: &str| t.parse::().map(|v| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32).or_else(|_| t.parse::().map(|v| v as i32)); - text.split_whitespace().take(16).map(|t| parse(t).unwrap_or(0)).collect() -} - -/// The constant under `holder` (a `paramValue`, `defaultValue` or `constValue` element). -fn sbs_constant(holder: XmlNode) -> Option { - let element = holder.children().find(|c| c.is_element())?; - sbs_constant_element(element) -} - -fn sbs_constant_element(element: XmlNode) -> Option { - let text = element.attribute("v").unwrap_or(""); - let tag = element.tag_name().name(); - - if tag == "constantValueBool" { - Some(SbsValue::Bool(parse_ints(text).first().is_some_and(|b| *b != 0) || text.trim().eq_ignore_ascii_case("true"))) - } else if tag == "constantValueString" { - Some(SbsValue::Text(text.to_string())) - } else if tag.starts_with("constantValueFloat") { - Some(SbsValue::Floats(parse_floats(text))) - } else if tag.starts_with("constantValueInt") { - Some(SbsValue::Ints(parse_ints(text))) - } else { - None - } -} - -impl SbsValue { - /// Component `i` as a float (the first component when there are fewer). - fn float(&self, i: usize) -> f32 { - match self { - SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0), - SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0) as f32, - SbsValue::Bool(b) => f32::from(u8::from(*b)), - SbsValue::Text(_) => 0.0, - } - } - - /// Component `i` as an integer (the first component when there are fewer). - fn int(&self, i: usize) -> i32 { - match self { - SbsValue::Ints(v) => v.get(i).or(v.first()).copied().unwrap_or(0), - SbsValue::Floats(v) => v.get(i).or(v.first()).copied().unwrap_or(0.0).round() as i32, - SbsValue::Bool(b) => i32::from(*b), - SbsValue::Text(_) => 0, - } - } - - fn truthy(&self) -> bool { - match self { - SbsValue::Bool(b) => *b, - SbsValue::Text(s) => s == "1" || s.eq_ignore_ascii_case("true"), - _ => self.float(0) != 0.0, - } - } - - fn component_count(&self) -> usize { - match self { - SbsValue::Floats(v) => v.len(), - SbsValue::Ints(v) => v.len(), - _ => 1, - } - } -} - -/// `value` as the type of `like` (a parameter default); `options` is an enum's option count. -fn to_param_value(like: &Value, value: &SbsValue, options: usize) -> Option { - let f = |i| value.float(i); - - Some(match like { - Value::Float(_) => Value::Float(f(0)), - Value::Float2(_) => Value::Float2([f(0), f(1)]), - Value::Float3(_) => Value::Float3([f(0), f(1), f(2)]), - Value::Float4(_) => Value::Float4([f(0), f(1), f(2), f(3)]), - // SBS colors are stored as displayed (sRGB); MaterialCraft's are linear - Value::Color(_) if value.component_count() >= 3 => { - let alpha = if value.component_count() >= 4 { f(3) } else { 1.0 }; - Value::Color([srgb_to_linear(f(0)), srgb_to_linear(f(1)), srgb_to_linear(f(2)), alpha]) - } - Value::Color(_) => { - let gray = srgb_to_linear(f(0)); - Value::Color([gray, gray, gray, 1.0]) - } - Value::Int(_) => Value::Int(value.int(0)), - Value::Int2(_) => Value::Int2([value.int(0), value.int(1)]), - Value::Bool(_) => Value::Bool(value.truthy()), - Value::Enum(_) => { - let last = options.saturating_sub(1).min(i32::MAX as usize) as i32; - Value::Enum(value.int(0).clamp(0, last) as u32) - } - Value::Text(_) => match value { - SbsValue::Text(s) => Value::Text(s.clone()), - _ => return None, - }, - Value::Curve(_) | Value::Gradient(_) | Value::Function(_) => return None, - }) -} - -/// `value` as the MaterialCraft value of the same shape (for exposed inputs and instance parameters). -fn to_natural_value(value: &SbsValue) -> Value { - let f = |i| value.float(i); - - match value { - SbsValue::Bool(b) => Value::Bool(*b), - SbsValue::Text(s) => Value::Text(s.clone()), - SbsValue::Ints(v) if v.len() <= 1 => Value::Int(value.int(0)), - SbsValue::Ints(_) => Value::Int2([value.int(0), value.int(1)]), - SbsValue::Floats(v) => match v.len() { - 0 | 1 => Value::Float(f(0)), - 2 => Value::Float2([f(0), f(1)]), - 3 => Value::Float3([f(0), f(1), f(2)]), - _ => Value::Float4([f(0), f(1), f(2), f(3)]), - }, - } -} - -/// SBS type codes of exposed graph inputs. -mod type_code { - pub const COLOR_IMAGE: i64 = 1; - pub const GRAY_IMAGE: i64 = 2; - pub const BOOL: i64 = 4; - pub const INT1: i64 = 16; - pub const INT2: i64 = 32; - pub const INT3: i64 = 64; - pub const INT4: i64 = 128; - pub const FLOAT1: i64 = 256; - pub const FLOAT2: i64 = 512; - pub const FLOAT3: i64 = 1024; - pub const FLOAT4: i64 = 2048; - pub const STRING: i64 = 16384; -} - -/// An exposed input's default from its SBS type code. -fn exposed_default(code: i64, value: Option<&SbsValue>) -> Value { - use type_code::*; - - let value = value.cloned().unwrap_or(SbsValue::Floats(vec![0.0])); - let f = |i| value.float(i); - match code { - BOOL => Value::Bool(value.truthy()), - INT1 => Value::Int(value.int(0)), - INT2 | INT3 | INT4 => Value::Int2([value.int(0), value.int(1)]), - FLOAT1 => Value::Float(f(0)), - FLOAT2 => Value::Float2([f(0), f(1)]), - FLOAT3 => Value::Float3([f(0), f(1), f(2)]), - FLOAT4 => Value::Float4([f(0), f(1), f(2), f(3)]), - STRING => match &value { - SbsValue::Text(s) => Value::Text(s.clone()), - _ => Value::Text(String::new()), - }, - _ => to_natural_value(&value), - } -} - -fn exposed_type_code(value: &Value) -> i64 { - use type_code::*; - - match value { - Value::Bool(_) => BOOL, - Value::Int(_) | Value::Enum(_) => INT1, - Value::Int2(_) => INT2, - Value::Float(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) => FLOAT1, - Value::Float2(_) => FLOAT2, - Value::Float3(_) => FLOAT3, - Value::Float4(_) | Value::Color(_) => FLOAT4, - Value::Text(_) => STRING, - } -} - -/// `v` for XML, with non-finite values written as 0. -fn format_float(v: f32) -> String { - if v.is_finite() { format!("{v}") } else { "0".into() } -} - -/// The SBS constant element for `value` (`None` for curves, gradients and functions). -fn constant_xml(value: &Value) -> Option { - let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::>().join(" "); - let (tag, text) = match value { - Value::Float(x) => ("constantValueFloat1", format_float(*x)), - Value::Float2(x) => ("constantValueFloat2", join(x)), - Value::Float3(x) => ("constantValueFloat3", join(x)), - Value::Float4(x) => ("constantValueFloat4", join(x)), - Value::Color(c) => ("constantValueFloat4", join(&[linear_to_srgb(c[0]), linear_to_srgb(c[1]), linear_to_srgb(c[2]), c[3]])), - Value::Int(i) => ("constantValueInt32", i.to_string()), - Value::Int2(i) => ("constantValueInt2", format!("{} {}", i[0], i[1])), - Value::Enum(e) => ("constantValueInt32", e.to_string()), - Value::Bool(b) => ("constantValueBool", u8::from(*b).to_string()), - Value::Text(s) => ("constantValueString", s.clone()), - Value::Curve(_) | Value::Gradient(_) | Value::Function(_) => return None, - }; - - Some(format!("<{tag} v=\"{}\"/>", xml_escape(&text))) -} - -// --------------------------------------------------------------------------------------------- -// XML helpers -// --------------------------------------------------------------------------------------------- - -fn child_element<'a, 'input>(node: XmlNode<'a, 'input>, tag: &str) -> Option> { - node.children().find(|c| c.is_element() && c.tag_name().name() == tag) -} - -fn children_named<'a, 'input: 'a>(node: XmlNode<'a, 'input>, tag: &'a str) -> impl Iterator> + 'a { - node.children().filter(move |c| c.is_element() && c.tag_name().name() == tag) -} - -/// The `v` attribute of child element `tag`, how SBS stores every scalar. -fn child_value<'a>(node: XmlNode<'a, '_>, tag: &str) -> Option<&'a str> { - child_element(node, tag).and_then(|c| c.attribute("v")) -} - -/// `text` escaped for XML attributes and text, without characters XML 1.0 can't hold. -fn xml_escape(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - for c in text.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - '\t' => out.push_str(" "), - '\n' => out.push_str(" "), - '\r' => out.push_str(" "), - c if (c as u32) < 0x20 || c == '\u{fffe}' || c == '\u{ffff}' => {} - c => out.push(c), - } - } - out -} - -/// FNV-1a (64 bits) of the `` an exact copy was written with. -fn content_hash(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, b| (hash ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)) -} - -fn base64_engine() -> base64::engine::GeneralPurpose { - base64::engine::general_purpose::STANDARD -} - -/// Decode embedded data: base64 of a big-endian u32 length followed by zlib-compressed bytes. -fn decode_embedded(strdata: &str) -> std::result::Result, String> { - let raw = base64_engine().decode(strdata.split_whitespace().collect::()).map_err(|e| format!("bad base64: {e}"))?; - let (length, compressed) = raw.split_at_checked(4).ok_or("too short")?; - let length = u32::from_be_bytes([length[0], length[1], length[2], length[3]]) as usize; - if length > MAX_EMBEDDED_BYTES { - return Err(format!("{length} bytes is over the {MAX_EMBEDDED_BYTES}-byte limit")); - } - - let mut out = Vec::with_capacity(length.min(1 << 24)); - let mut decoder = flate2::read::ZlibDecoder::new(compressed).take(MAX_EMBEDDED_BYTES as u64 + 1); - decoder.read_to_end(&mut out).map_err(|e| format!("bad compressed data: {e}"))?; - if out.len() != length { - return Err(format!("{} bytes where {length} were declared", out.len())); - } - Ok(out) -} - -fn encode_embedded(bytes: &[u8]) -> Result { - let length = u32::try_from(bytes.len()).map_err(|_| FormatError::Io("resource too large".into()))?; - let mut encoder = flate2::write::ZlibEncoder::new(length.to_be_bytes().to_vec(), flate2::Compression::default()); - encoder.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?; - let raw = encoder.finish().map_err(|e| FormatError::Io(e.to_string()))?; - Ok(base64_engine().encode(raw)) -} - -// --------------------------------------------------------------------------------------------- -// Reading -// --------------------------------------------------------------------------------------------- - -/// Read an SBS package; `name` is its file name and `linked` loads files it links to by relative path. -pub fn read_sbs(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option>) -> Result { - if bytes.len() > MAX_SBS_BYTES { - return Err(FormatError::BadPackage(format!("the SBS file is over the {} MB limit", MAX_SBS_BYTES >> 20))); - } - - let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?; - let text = text.trim_start_matches('\u{feff}'); - let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES }; - let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?; - let root = doc.root_element(); - if root.tag_name().name() != "package" { - return Err(FormatError::BadPackage("not an SBS package (the root element is not )".into())); - } - - let mut warnings = Warnings::default(); - let file_stem = name.rsplit(['/', '\\']).next().unwrap_or(name); - let file_stem = file_stem.rsplit_once('.').map_or(file_stem, |(stem, _)| stem).trim(); - let package_name = match child_value(root, "identifier").map(str::trim) { - Some(id) if !id.is_empty() && id != "Unsaved Package" => id.to_string(), - _ if !file_stem.is_empty() => file_stem.to_string(), - _ => "Untitled package".to_string(), - }; - let mut reader = Reader { - text, - warnings: &mut warnings, - dependencies: HashMap::new(), - graph_names: HashMap::new(), - resource_names: HashMap::new(), - node_count: 0, - function_variables: BTreeMap::new(), - }; - for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) { - if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) { - reader.dependencies.insert(uid.to_string(), file.to_string()); - } - } - - // Resources first: the exact copy and the SBS graphs both use them - let content = child_element(root, "content"); - let mut pkg = Package::new(&package_name); - let mut graph_elements: Vec<(String, XmlNode)> = Vec::new(); - if let Some(content) = content { - reader.collect_items(content, "", &mut pkg, &mut graph_elements, linked); - } - - if let Some(content) = content - && let Some(mut exact) = read_exact_copy(root, &text[content.range()], reader.warnings) - { - for resource in &mut exact.resources { - match pkg.resources.iter().find(|r| r.name == resource.name) { - Some(found) => resource.bytes = found.bytes.clone(), - None => reader.warnings.add(format!("resource `{}` is missing from the file", resource.name)), - } - } - report_placeholders(&exact, reader.warnings); - return Ok(SbsRead { pkg: exact, warnings: warnings.finish(), exact: true }); - } - - // Name every graph first so instances can refer to graphs defined later in the file - let mut names: Vec = Vec::new(); - for (path, graph) in graph_elements.iter().take(MAX_GRAPHS) { - let identifier = child_value(*graph, "identifier").unwrap_or("").trim(); - let unique = unique_name(&names, if identifier.is_empty() { "Graph" } else { identifier }); - reader.graph_names.insert(path.clone(), unique.clone()); - names.push(unique); - } - if graph_elements.len() > MAX_GRAPHS { - reader.warnings.add(format!("only the first {MAX_GRAPHS} graphs were read")); - } - - for ((_, graph), name) in graph_elements.iter().zip(names) { - let graph = reader.read_graph(*graph, name); - pkg.graphs.push(graph); - } - if pkg.graphs.is_empty() { - reader.warnings.add("the package has no graphs MaterialCraft can open; an empty graph was added"); - pkg.graphs.push(Graph::new("Graph")); - } - - report_placeholders(&pkg, reader.warnings); - Ok(SbsRead { pkg, warnings: warnings.finish(), exact: false }) -} - -/// One warning per missing node kind and graph. -fn report_placeholders(pkg: &Package, warnings: &mut Warnings) { - for graph in &pkg.graphs { - let mut counts: BTreeMap = BTreeMap::new(); - for node in graph.nodes.iter().filter(|n| n.def == MISSING_NODE) { - let name = match node.params.get("sbs_name") { - Some(Value::Text(s)) if !s.is_empty() => s.clone(), - _ => node.label.clone(), - }; - *counts.entry(name).or_default() += 1; - } - - for (name, count) in counts { - let times = if count > 1 { format!(" ×{count}") } else { String::new() }; - warnings.add(format!("graph `{}`: missing node `{name}`{times} is not in MaterialCraft's library yet; kept as a placeholder", graph.name)); - } - } -} - -/// The exact MaterialCraft copy, if present and written for exactly this `content`. -fn read_exact_copy(root: XmlNode, content: &str, warnings: &mut Warnings) -> Option { - let comment = root.children().filter(|c| c.is_comment()).filter_map(|c| c.text()).find(|t| t.trim_start().starts_with(EXACT_MARK))?; - let field = |key: &str| comment.split_whitespace().find_map(|part| part.strip_prefix(key)); - - if field("version=").and_then(|v| v.parse::().ok()) != Some(EXACT_VERSION) { - warnings.add("the MaterialCraft data in this file is from another version; the graphs were read from the SBS data"); - return None; - } - if field("hash=") != Some(format!("{:016x}", content_hash(content.as_bytes())).as_str()) { - warnings.add("this file was changed outside MaterialCraft since it was saved; the graphs were read from the SBS data"); - return None; - } - - let decoded = decode_embedded(field("data=").unwrap_or("")).and_then(|json| serde_json::from_slice::(&json).map_err(|e| e.to_string())); - decoded.map_err(|e| warnings.add(format!("the MaterialCraft data in this file is damaged ({e}); the graphs were read from the SBS data"))).ok() -} - -fn unique_name(taken: &[String], base: &str) -> String { - let free = |name: &str| !taken.iter().any(|t| t == name); - if free(base) { - return base.to_string(); - } - (1..).map(|i| format!("{base}_{i}")).find(|name| free(name)).unwrap_or_else(|| base.to_string()) -} - -struct Reader<'text, 'warnings> { - text: &'text str, - warnings: &'warnings mut Warnings, - /// Dependency uid → file name. - dependencies: HashMap, - /// Package path (`Folder/Graph`) → graph name. - graph_names: HashMap, - /// Package path (`Resources/Bitmap`) → resource name. - resource_names: HashMap, - node_count: usize, - /// Exposed numeric defaults of the graph currently being read. - function_variables: BTreeMap, -} - -/// A node being read, as wires from the SBS data find it. -struct ReadNode { - id: NodeId, - /// Position in `Graph::nodes`. - index: usize, - /// SBS input identifier → MaterialCraft port. - inputs: HashMap, - /// (SBS output uid, MaterialCraft port), in output order. - outputs: Vec<(String, String)>, - /// Placeholders and graph instances take whatever inputs wires arrive at. - open_inputs: bool, -} - -/// Add a node and return it with its position in `graph.nodes`. -fn push_node<'g>(graph: &'g mut Graph, def: &str, pos: [f32; 2]) -> (NodeId, usize, Option<&'g mut Node>) { - let id = graph.add_node(def, pos); - let index = graph.nodes.len() - 1; - (id, index, graph.nodes.last_mut()) -} - -impl<'text> Reader<'text, '_> { - /// Walk `content` and nested groups: queue graphs, load resources, note what is skipped. - fn collect_items<'a>( - &mut self, - content: XmlNode<'a, 'text>, - folder: &str, - pkg: &mut Package, - graphs: &mut Vec<(String, XmlNode<'a, 'text>)>, - linked: &dyn Fn(&str) -> Option>, - ) { - for item in content.children().filter(|c| c.is_element()) { - let identifier = child_value(item, "identifier").unwrap_or("").trim().to_string(); - let path = if folder.is_empty() { identifier.clone() } else { format!("{folder}/{identifier}") }; - - match item.tag_name().name() { - "graph" => graphs.push((path, item)), - "group" => { - if let Some(group_content) = child_element(item, "content") { - self.collect_items(group_content, &path, pkg, graphs, linked); - } - } - "resource" if pkg.resources.len() >= MAX_RESOURCES => self.warnings.add(format!("only the first {MAX_RESOURCES} resources were read")), - "resource" => self.read_resource(item, &identifier, &path, pkg, linked), - "function" => self.warnings.add(format!("function graph `{path}` is not imported yet (SBS function graphs)")), - "mdl_graph" | "mdlGraph" => self.warnings.add(format!("MDL graph `{path}` is not supported")), - other => self.warnings.add(format!("package item <{other}> `{path}` is not supported")), - } - } - } - - fn read_resource(&mut self, item: XmlNode, identifier: &str, path: &str, pkg: &mut Package, linked: &dyn Fn(&str) -> Option>) { - let kind = child_value(item, "type").unwrap_or("bitmap"); - let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase(); - let source = child_element(item, "source"); - let mut bytes: Option> = None; - let mut link: Option = None; - let mut why_missing = String::new(); - - if let Some(embedded) = source.and_then(|s| child_element(s, "binembedded")) { - match decode_embedded(child_value(embedded, "strdata").unwrap_or("")) { - Ok(data) => bytes = Some(data), - Err(e) => why_missing = format!("its embedded data is damaged ({e})"), - } - } - - if bytes.is_none() { - let external_copy = source.and_then(|s| child_element(s, "externalcopy")).and_then(|e| child_value(e, "filename")); - for file in [external_copy, child_value(item, "filepath")].into_iter().flatten().filter(|p| !p.trim().is_empty()) { - if file.contains("://") { - why_missing = format!("it links to `{file}`, which is not available"); - continue; - } - match linked(file) { - Some(data) => { - bytes = Some(data); - link = Some(file.to_string()); - break; - } - None => why_missing = format!("its file `{file}` was not found next to the package"), - } - } - } - - let taken: Vec = pkg.resources.iter().map(|r| r.name.clone()).collect(); - let name = unique_name(&taken, if identifier.is_empty() { "resource" } else { identifier }); - self.resource_names.insert(path.to_string(), name.clone()); - match bytes { - Some(data) => { - let ext = if kind == "svg" { "svg".to_string() } else { format }; - let file = crate::safe_file_name(&format!("{name}.{ext}")); - pkg.resources.push(match link { - Some(l) => Resource::linked(name.clone(), file, ResourceBytes::new(data), l), - None => Resource::new(name.clone(), file, ResourceBytes::new(data)), - }); - } - None => { - let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; - self.warnings.add(format!("resource `{path}` could not be loaded: {why}")); - } - } - } - - /// Split a `pkg:///path?dependency=uid` reference into the path and the dependency's file name. - fn resolve_reference(&self, url: &str) -> (String, Option) { - let url = url.trim(); - let rest = url.strip_prefix("pkg:///").or_else(|| url.strip_prefix("pkg://")).unwrap_or(url); - let (path, query) = rest.split_once('?').unwrap_or((rest, "")); - let dependency = query.split('&').find_map(|kv| kv.strip_prefix("dependency=")).and_then(|uid| self.dependencies.get(uid).cloned()); - (path.trim_matches('/').to_string(), dependency) - } - - fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph { - let mut graph = Graph::new(&name); - - // The default parent size option ("11x11", log2 sizes) - for option in child_element(element, "options").into_iter().flat_map(|o| children_named(o, "option")) { - if child_value(option, "name") == Some("defaultParentSize") - && let Some((width, height)) = child_value(option, "value").and_then(|v| v.split_once('x')) - { - let log2 = |s: &str| s.trim().parse::().unwrap_or(10).clamp(i64::from(MIN_SIZE_LOG2), i64::from(MAX_SIZE_LOG2)) as u32; - graph.size = [log2(width), log2(height)]; - } - } - - if let Some(attributes) = child_element(element, "attributes") { - let text = |tag: &str| child_value(attributes, tag).unwrap_or("").to_string(); - graph.attributes.category = text("category"); - graph.attributes.description = text("description"); - graph.attributes.author = text("author"); - graph.attributes.tags = text("tags"); - } - - let image_inputs = self.read_graph_inputs(element, &mut graph); - self.function_variables = graph.exposed.iter().map(|p| (p.id.clone(), p.default.clone())).collect(); - let outputs = read_graph_outputs(element); - - let mut read_nodes: HashMap = HashMap::new(); - let comp_nodes: Vec = child_element(element, "compNodes").into_iter().flat_map(|c| children_named(c, "compNode")).collect(); - for comp_node in &comp_nodes { - if self.node_count >= MAX_NODES { - self.warnings.add(format!("only the first {MAX_NODES} nodes were read")); - break; - } - - let Some(uid) = child_value(*comp_node, "uid").map(str::to_string) else { continue }; - if read_nodes.contains_key(&uid) { - self.warnings.add(format!("graph `{name}`: duplicate node uid {uid} skipped")); - continue; - } - - self.node_count += 1; - let node = self.read_node(&mut graph, *comp_node, &image_inputs, &outputs); - read_nodes.insert(uid, node); - } - - let wires = self.read_wires(&mut graph, &comp_nodes, &read_nodes); - connect_all(&mut graph, wires, self.warnings); - self.read_canvas_items(element, &mut graph); - graph - } - - /// Exposed value inputs go into `graph`; image inputs are returned as uid → (identifier, gray). - fn read_graph_inputs(&mut self, element: XmlNode, graph: &mut Graph) -> HashMap { - let mut image_inputs = HashMap::new(); - for input in child_element(element, "paraminputs").into_iter().flat_map(|p| children_named(p, "paraminput")) { - let id = child_value(input, "identifier").unwrap_or("input").to_string(); - let code = child_value(input, "type").and_then(|t| t.trim().parse::().ok()).unwrap_or(type_code::FLOAT1); - if code == type_code::COLOR_IMAGE || code == type_code::GRAY_IMAGE { - image_inputs.insert(child_value(input, "uid").unwrap_or("").to_string(), (id, code == type_code::GRAY_IMAGE)); - continue; - } - if graph.exposed.iter().any(|e| e.id == id) { - continue; - } - - let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref()); - let label = child_element(input, "attributes").and_then(|a| child_value(a, "label")).filter(|l| !l.is_empty()).unwrap_or(&id).to_string(); - let (mut min, mut max) = (0.0, 1.0); - let widget_options = child_element(input, "defaultWidget").and_then(|w| child_element(w, "options")); - for option in widget_options.into_iter().flat_map(|o| children_named(o, "option")) { - let value = - child_value(option, "value").and_then(|v| v.split_whitespace().next()).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()); - match (child_value(option, "name"), value) { - (Some("min"), Some(v)) => min = v, - (Some("max"), Some(v)) => max = v, - _ => {} - } - } - - let group = child_value(input, "group").unwrap_or("").to_string(); - graph.exposed.push(ExposedParam { id, label, group, default, min, max, options: Vec::new() }); - } - image_inputs - } - - /// Every wire of the graph, resolved to MaterialCraft nodes and ports, in file order. - fn read_wires(&mut self, graph: &mut Graph, comp_nodes: &[XmlNode], read_nodes: &HashMap) -> Vec { - let name = graph.name.clone(); - let mut wires = Vec::new(); - - for comp_node in comp_nodes { - let Some(to) = child_value(*comp_node, "uid").and_then(|u| read_nodes.get(u)) else { continue }; - for connection in child_element(*comp_node, "connections").into_iter().flat_map(|c| children_named(c, "connection")) { - let sbs_input = child_value(connection, "identifier").unwrap_or(""); - let Some(from) = child_value(connection, "connRef").and_then(|u| read_nodes.get(u)) else { - self.warnings.add(format!("graph `{name}`: a wire from a node that is not in the file was dropped")); - continue; - }; - - let output_uid = child_value(connection, "connRefOutput").unwrap_or(""); - let from_port = from.outputs.iter().find(|(uid, _)| uid == output_uid).or(from.outputs.first()).map(|(_, port)| port.clone()); - let Some(from_port) = from_port else { - self.warnings.add(format!("graph `{name}`: a wire from a node with no outputs was dropped")); - continue; - }; - - let to_port = match to.inputs.get(sbs_input) { - Some(port) => port.clone(), - None if to.open_inputs => { - if let Some(node) = graph.nodes.get_mut(to.index) { - add_placeholder_input(node, sbs_input); - } - sbs_input.to_string() - } - None => { - let def = graph.nodes.get(to.index).map_or("", |n| n.def.as_str()); - self.warnings.add(format!("graph `{name}`: `{def}` has no input `{sbs_input}`; its wire was dropped")); - continue; - } - }; - wires.push(Connection { from: from.id, from_port, to: to.id, to_port }); - } - } - wires - } - - /// Frames and comments. - fn read_canvas_items(&mut self, element: XmlNode, graph: &mut Graph) { - for item in child_element(element, "GUIObjects").into_iter().flat_map(|o| children_named(o, "GUIObject")) { - let layout = child_element(item, "GUILayout"); - let pos = layout.and_then(|l| child_value(l, "gpos")).map(parse_floats).unwrap_or_default(); - let size = layout.and_then(|l| child_value(l, "size")).map(parse_floats).unwrap_or_default(); - let (x, y) = (pos.first().copied().unwrap_or(0.0), pos.get(1).copied().unwrap_or(0.0)); - let width = size.first().copied().unwrap_or(180.0).max(8.0); - let height = size.get(1).copied().unwrap_or(70.0).max(8.0); - let text = child_value(item, "GUIName").unwrap_or("").to_string(); - - match child_value(item, "type") { - Some("COMMENT") if child_value(item, "isFrameVisible") == Some("1") => { - let c = child_value(item, "frameColor").map(parse_floats).unwrap_or_default(); - let color = if c.len() >= 4 { [srgb_to_linear(c[0]), srgb_to_linear(c[1]), srgb_to_linear(c[2]), c[3]] } else { [0.2, 0.4, 0.8, 0.25] }; - let id = graph.alloc_id(); - let title = child_value(item, "title").unwrap_or("").to_string(); - graph.frames.push(Frame { id, title, description: text, rect: [x, y, width, height], color }); - } - Some("COMMENT") => { - let id = graph.alloc_id(); - graph.comments.push(Comment { id, text, pos: [x, y], size: [width, height] }); - } - Some(other) => self.warnings.add(format!("graph `{}`: canvas item `{other}` is not supported", graph.name)), - None => {} - } - } - } - - /// Read one `compNode` into `graph`. - fn read_node( - &mut self, - graph: &mut Graph, - comp_node: XmlNode<'_, 'text>, - image_inputs: &HashMap, - outputs: &HashMap, - ) -> ReadNode { - let gpos = child_element(comp_node, "GUILayout").and_then(|l| child_value(l, "gpos")).map(parse_floats).unwrap_or_default(); - let pos = [gpos.first().copied().unwrap_or(0.0) - NODE_HALF_SIZE[0], gpos.get(1).copied().unwrap_or(0.0) - NODE_HALF_SIZE[1]]; - let output_uids: Vec<(String, bool)> = child_element(comp_node, "compOutputs") - .into_iter() - .flat_map(|o| children_named(o, "compOutput")) - .map(|o| (child_value(o, "uid").unwrap_or("").to_string(), child_value(o, "comptype") == Some("2"))) - .collect(); - let all_outputs_to = |port: &str| output_uids.iter().map(|(uid, _)| (uid.clone(), port.to_string())).collect::>(); - let text = self.text; - - let Some(implementation) = child_element(comp_node, "compImplementation").and_then(|i| i.children().find(|c| c.is_element())) else { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - fill_placeholder(node, "other", "empty node", "", None, &output_uids, None); - } - return ReadNode { id, index, inputs: HashMap::new(), outputs: Vec::new(), open_inputs: true }; - }; - - let params = child_element(implementation, "parameters"); - match implementation.tag_name().name() { - "compInputBridge" => { - let entry = child_value(implementation, "entry").unwrap_or(""); - let fallback = || ("input".to_string(), output_uids.first().is_some_and(|(_, gray)| *gray)); - let (identifier, gray) = image_inputs.get(entry).cloned().unwrap_or_else(fallback); - let (id, index, node) = push_node(graph, if gray { "input_grayscale" } else { "input_color" }, pos); - if let Some(node) = node { - node.params.insert("identifier".into(), Value::Text(identifier)); - node.base = read_base_params(params); - } - ReadNode { id, index, inputs: HashMap::new(), outputs: all_outputs_to("output"), open_inputs: false } - } - "compOutputBridge" => { - let output = child_value(implementation, "output").unwrap_or(""); - let (identifier, usage) = outputs.get(output).cloned().unwrap_or_else(|| ("output".into(), usage_index("any"))); - let (id, index, node) = push_node(graph, "output", pos); - if let Some(node) = node { - node.params.insert("identifier".into(), Value::Text(identifier)); - node.params.insert("usage".into(), Value::Enum(usage)); - } - let inputs = HashMap::from([("inputNodeOutput".to_string(), "input".to_string())]); - ReadNode { id, index, inputs, outputs: Vec::new(), open_inputs: false } - } - "compFilter" => { - let filter_name = child_value(implementation, "filter").unwrap_or(""); - let graph_name = graph.name.clone(); - match filter_by_sbs_name(filter_name).filter(|f| find(f.def).is_some()) { - Some(filter) => { - let (id, index, node) = push_node(graph, filter.def, pos); - if let Some(node) = node { - self.read_filter_params(node, filter, params, &graph_name); - node.base = read_base_params(params); - } - let inputs = filter.inputs.iter().map(|(sbs, port)| (sbs.to_string(), port.to_string())).collect(); - ReadNode { id, index, inputs, outputs: all_outputs_to("output"), open_inputs: false } - } - None => { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - fill_placeholder(node, "filter", filter_name, "", params.map(|p| &text[p.range()]), &output_uids, None); - } - ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(&output_uids, None), open_inputs: true } - } - } - } - "compInstance" => self.read_instance(graph, implementation, pos, &output_uids), - other => { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - fill_placeholder(node, "other", other, "", None, &output_uids, None); - } - ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(&output_uids, None), open_inputs: true } - } - } - } - - /// An instance: of a graph in this package, of a library node MaterialCraft has, or a placeholder. - fn read_instance(&mut self, graph: &mut Graph, implementation: XmlNode<'_, 'text>, pos: [f32; 2], output_uids: &[(String, bool)]) -> ReadNode { - let graph_name = graph.name.clone(); - let (path, dependency) = self.resolve_reference(child_value(implementation, "path").unwrap_or("")); - let params = child_element(implementation, "parameters"); - let bridgings: Vec<(String, String)> = child_element(implementation, "outputBridgings") - .into_iter() - .flat_map(|b| children_named(b, "outputBridging")) - .map(|b| (child_value(b, "uid").unwrap_or("").to_string(), child_value(b, "identifier").unwrap_or("output").to_string())) - .collect(); - let instance_params = - || params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))); - - let own_graph = dependency.as_deref().is_none_or(|d| d == SELF_DEPENDENCY).then(|| self.graph_names.get(&path).cloned()).flatten(); - if let Some(sub_graph) = own_graph { - let (id, index, node) = push_node(graph, "graph_instance", pos); - if let Some(node) = node { - node.params.insert("graph".into(), Value::Text(sub_graph)); - for param in instance_params() { - if let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) { - node.params.insert(child_value(param, "name").unwrap_or("").to_string(), to_natural_value(&value)); - } - } - node.base = read_base_params(params); - } - return ReadNode { id, index, inputs: HashMap::new(), outputs: bridgings, open_inputs: true }; - } - - let short_name = path.rsplit('/').next().unwrap_or(&path).to_string(); - let library_def = find(&short_name).filter(|d| d.id != "graph_instance" && d.id != "output" && !d.id.starts_with("input_")); - let Some(def) = library_def else { - let (id, index, node) = push_node(graph, MISSING_NODE, pos); - if let Some(node) = node { - let raw_params = params.map(|p| &self.text[p.range()]); - fill_placeholder(node, "instance", &short_name, dependency.as_deref().unwrap_or(""), raw_params, output_uids, Some(&bridgings)); - node.params.insert("sbs_path".into(), Value::Text(path)); - } - return ReadNode { id, index, inputs: HashMap::new(), outputs: placeholder_outputs(output_uids, Some(&bridgings)), open_inputs: true }; - }; - - let (id, index, node) = push_node(graph, def.id, pos); - if let Some(node) = node { - for param in instance_params() { - let param_name = child_value(param, "name").unwrap_or(""); - let id = match (def.id, param_name) { - ("histogram_scan", "Position") => "position", - ("histogram_scan", "Contrast") => "contrast", - _ => param_name, - }; - match def.param(id) { - Some(param_def) => self.set_param(node, id, ¶m_def.default, param_def.options.len(), param, &graph_name), - None => self.warnings.add(format!("`{}`: parameter `{param_name}` has no MaterialCraft equivalent and was ignored", def.id)), - } - } - node.base = read_base_params(params); - } - - let first_output = def.outputs.first().map_or("output", |o| o.id).to_string(); - let port_for = |identifier: &str| if def.output_index(identifier).is_some() { identifier.to_string() } else { first_output.clone() }; - let unbridged = output_uids.iter().filter(|(uid, _)| !bridgings.iter().any(|(b, _)| b == uid)).map(|(uid, _)| (uid.clone(), first_output.clone())); - let outputs = bridgings.iter().map(|(uid, identifier)| (uid.clone(), port_for(identifier))).chain(unbridged).collect(); - let mut inputs: HashMap<_, _> = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect(); - let input_aliases: &[(&str, &str)] = match def.id { - "histogram_scan" => &[("Input_1", "input")], - "auto_levels" => &[("Input", "input")], - "flood_fill" => &[("mask", "input")], - "height_blend" => &[("height_top", "top"), ("height_bottom", "bottom")], - _ => &[], - }; - inputs.extend(input_aliases.iter().map(|&(alias, port)| (alias.to_string(), port.to_string()))); - ReadNode { id, index, inputs, outputs, open_inputs: false } - } - - /// Set MaterialCraft parameter `id` (default `like`) from the SBS `` element `param`. - fn set_param(&mut self, node: &mut Node, id: &str, like: &Value, options: usize, param: XmlNode, graph_name: &str) { - let Some(param_value) = child_element(param, "paramValue") else { return }; - - if let Some(value) = sbs_constant(param_value) { - match to_param_value(like, &value, options) { - Some(value) => { - node.params.insert(id.to_string(), value); - } - None => self.warnings.add(format!("`{}`: parameter `{id}` has a value type MaterialCraft can't read yet; kept the default", node.def)), - } - return; - } - - // A parameter linked to a graph input is a function of one `get_*` node naming it - let Some(dynamic) = child_element(param_value, "dynamicValue") else { return }; - let function_nodes: Vec = - child_element(dynamic, "paramNodes").into_iter().flat_map(|p| children_named(p, "paramNode")).take(functions::MAX_NODES + 1).collect(); - if let [only] = function_nodes.as_slice() - && child_value(*only, "function").is_some_and(|f| f.starts_with("get_")) - && let Some(input) = only.descendants().find(|c| c.tag_name().name() == "constantValueString").and_then(|c| c.attribute("v")) - { - node.bindings.insert(id.to_string(), input.to_string()); - return; - } - match functions::read(dynamic, &self.function_variables, like) { - Ok(function) => { - node.functions.insert(id.to_string(), function); - } - Err(reason) => { - self.warnings.add(format!("graph `{graph_name}`: `{}` parameter `{id}` is driven by a function; imported its default ({reason})", node.def)) - } - } - } - - fn read_filter_params(&mut self, node: &mut Node, filter: &FilterMap, params: Option, graph_name: &str) { - let Some(def) = find(filter.def) else { return }; - - let filter_params: Vec = - params.into_iter().flat_map(|p| children_named(p, "parameter")).filter(|p| !BASE_PARAMS.contains(&child_value(*p, "name").unwrap_or(""))).collect(); - for param in &filter_params { - let param_name = child_value(*param, "name").unwrap_or(""); - let value = child_element(*param, "paramValue").and_then(sbs_constant); - - if let Some(&(_, mc_name, conversion)) = filter.params.iter().find(|(sbs, _, _)| *sbs == param_name) { - let Some(param_def) = def.param(mc_name) else { continue }; - - match (conversion, value) { - (TrueIsFirstOption, Some(v)) => { - node.params.insert(mc_name.into(), Value::Enum(if v.truthy() { 0 } else { 1 })); - } - (TrueIsFirstOption, None) => {} - (ByType, _) => self.set_param(node, mc_name, ¶m_def.default, param_def.options.len(), *param, graph_name), - } - continue; - } - - match (filter.sbs, param_name, value) { - ("bitmap", "bitmapresourcepath", Some(SbsValue::Text(url))) => { - let (path, _) = self.resolve_reference(&url); - match self.resource_names.get(&path) { - Some(name) => { - node.params.insert("resource".into(), Value::Text(name.clone())); - } - None => self.warnings.add(format!("graph `{graph_name}`: Bitmap uses resource `{path}`, which is not in the package")), - } - } - ("grayscaleconversion", "channelsweights", Some(weights)) => { - for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() { - node.params.insert(channel.into(), Value::Float(weights.float(i))); - } - } - ("transformation", "matrix22", Some(matrix)) => { - let (a, b, c, d) = (matrix.float(0), matrix.float(1), matrix.float(2), matrix.float(3)); - let (scale_x, scale_y) = ((a * a + c * c).sqrt(), (b * b + d * d).sqrt()); - if scale_x > 1e-6 && scale_y > 1e-6 { - node.params.insert("scale".into(), Value::Float2([scale_x, scale_y])); - node.params.insert("rotation".into(), Value::Float(c.atan2(a) / std::f32::consts::TAU)); - } - } - _ if HANDLED_PARAMS.contains(&(filter.sbs, param_name)) => {} - _ => self.warnings.add(format!("`{}`: SBS parameter `{param_name}` is not supported yet and was ignored", filter.def)), - } - } - - let not_imported = match filter.sbs { - "curve" => Some("curve points"), - "gradient" => Some("gradient keys"), - "pixelprocessor" | "valueprocessor" => Some("function graph"), - "svg" => Some("vector shapes"), - "fxmaps" => Some("pattern settings"), - _ => None, - }; - if let Some(what) = not_imported - && !filter_params.is_empty() - { - self.warnings.add(format!("graph `{graph_name}`: the {what} of `{}` nodes are not imported yet; they use MaterialCraft's defaults", filter.def)); - } - } -} - -/// Graph outputs as uid → (identifier, usage index). -fn read_graph_outputs(element: XmlNode) -> HashMap { - let mut outputs = HashMap::new(); - for output in child_element(element, "graphOutputs").into_iter().flat_map(|o| children_named(o, "graphoutput")) { - let identifier = child_value(output, "identifier").unwrap_or("output").to_string(); - let usage = child_element(output, "usages") - .and_then(|u| child_element(u, "usage")) - .and_then(|u| child_value(u, "name")) - .map_or(usage_index("any"), usage_index); - outputs.insert(child_value(output, "uid").unwrap_or("").to_string(), (identifier, usage)); - } - outputs -} - -/// Output size, format and random seed. -fn read_base_params(params: Option) -> BaseParams { - let mut base = BaseParams::default(); - for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) { - let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::().ok()).unwrap_or(1); - let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue }; - - match child_value(param, "name") { - Some("outputsize") => { - base.size_mode = match relative_to { - 0 => SizeMode::Absolute, - 2 => SizeMode::RelativeToParent, - _ => SizeMode::RelativeToInput, - }; - let limit = |log2: i32| log2.clamp(-(MAX_SIZE_LOG2 as i32), MAX_SIZE_LOG2 as i32); - base.size = [limit(value.int(0)), limit(value.int(1))]; - } - Some("format") if relative_to == 0 => { - base.format = match value.int(0) { - 0 => OutputFormat::U8, - 1 => OutputFormat::U16, - 2 => OutputFormat::F16, - 3 => OutputFormat::F32, - _ => OutputFormat::Inherit, - } - } - Some("randomseed") if relative_to == 0 => base.seed = value.int(0), - _ => {} - } - } - base -} - -/// Connect `wires` in one pass: the last wire into an input wins, and wires that would close a cycle are dropped. -fn connect_all(graph: &mut Graph, wires: Vec, warnings: &mut Warnings) { - let graph_name = graph.name.clone(); - let cycle_warning = || format!("graph `{graph_name}`: a wire that would make a cycle was dropped"); - - let mut last_into_input: HashMap<(NodeId, String), usize> = HashMap::new(); - let mut kept: Vec> = Vec::with_capacity(wires.len()); - for wire in wires { - if wire.from == wire.to { - warnings.add(cycle_warning()); - continue; - } - if let Some(previous) = last_into_input.insert((wire.to, wire.to_port.clone()), kept.len()) - && let Some(slot) = kept.get_mut(previous) - { - *slot = None; - } - kept.push(Some(wire)); - } - let wires: Vec = kept.into_iter().flatten().collect(); - - // Kahn's algorithm: nodes it can't order lie on or after a cycle - let mut in_degree: HashMap = HashMap::new(); - let mut downstream: HashMap> = HashMap::new(); - for wire in &wires { - *in_degree.entry(wire.to).or_default() += 1; - downstream.entry(wire.from).or_default().push(wire.to); - } - let mut ready: VecDeque = graph.nodes.iter().map(|n| n.id).filter(|id| !in_degree.contains_key(id)).collect(); - let mut ordered: HashSet = HashSet::new(); - while let Some(id) = ready.pop_front() { - ordered.insert(id); - for next in downstream.get(&id).into_iter().flatten() { - if let Some(degree) = in_degree.get_mut(next) { - *degree -= 1; - if *degree == 0 { - ready.push_back(*next); - } - } - } - } - - // Wires among unordered nodes go through the cycle-checked path, one at a time - let (safe, risky): (Vec, Vec) = wires.into_iter().partition(|w| ordered.contains(&w.from) || ordered.contains(&w.to)); - graph.connections = safe; - for wire in risky { - if graph.connect(wire.from, &wire.from_port, wire.to, &wire.to_port).is_err() { - warnings.add(cycle_warning()); - } - } -} - -/// Fill in a [`MISSING_NODE`] placeholder with what writing it back needs. -fn fill_placeholder( - node: &mut Node, - kind: &str, - name: &str, - package: &str, - raw_params: Option<&str>, - output_uids: &[(String, bool)], - bridgings: Option<&[(String, String)]>, -) { - node.label = name.to_string(); - node.params.insert("sbs_kind".into(), Value::Text(kind.into())); - node.params.insert("sbs_name".into(), Value::Text(name.into())); - if !package.is_empty() { - node.params.insert("sbs_package".into(), Value::Text(package.into())); - } - if let Some(raw) = raw_params { - node.params.insert("sbs_parameters".into(), Value::Text(raw.into())); - } - - let mut seen = BTreeSet::new(); - let outputs: Vec = placeholder_outputs(output_uids, bridgings) - .into_iter() - .filter(|(_, port)| seen.insert(port.clone())) - .map(|(uid, port)| if output_uids.iter().any(|(u, gray)| *u == uid && *gray) { format!("{port}:gray") } else { port }) - .collect(); - node.params.insert("outputs".into(), Value::Text(outputs.join(","))); - node.params.insert("inputs".into(), Value::Text(String::new())); -} - -/// (Output uid, port) of a placeholder in output order: the instance's bridgings, else `output`, `output_2`… -fn placeholder_outputs(output_uids: &[(String, bool)], bridgings: Option<&[(String, String)]>) -> Vec<(String, String)> { - let bridged = |uid: &str| bridgings.and_then(|b| b.iter().find(|(u, _)| u == uid)).map(|(_, identifier)| identifier.clone()); - let mut outputs: Vec<(String, String)> = output_uids - .iter() - .enumerate() - .map(|(i, (uid, _))| (uid.clone(), bridged(uid).unwrap_or_else(|| if i == 0 { "output".to_string() } else { format!("output_{}", i + 1) }))) - .collect(); - - for (uid, identifier) in bridgings.unwrap_or_default() { - if !outputs.iter().any(|(u, _)| u == uid) { - outputs.push((uid.clone(), identifier.clone())); - } - } - outputs -} - -/// Record a wire arriving at placeholder input `port`. -fn add_placeholder_input(node: &mut Node, port: &str) { - if port.is_empty() || port.contains(',') { - return; - } - - let (mut inputs, _) = missing_ports(node); - if !inputs.iter().any(|p| p == port) { - inputs.push(port.to_string()); - node.params.insert("inputs".into(), Value::Text(inputs.join(","))); - } -} - -// --------------------------------------------------------------------------------------------- -// Writing -// --------------------------------------------------------------------------------------------- - -/// Write `pkg` as an SBS package (UTF-8 XML) with bitmaps embedded and MaterialCraft's exact copy at the end. -pub fn write_sbs(pkg: &Package) -> Result> { - let mut writer = SbsWriter { last_uid: FIRST_UID, external_packages: BTreeMap::new() }; - let self_uid = writer.next_uid(); - let library_uid = writer.next_uid(); - - let mut content = String::from(""); - for graph in &pkg.graphs { - writer.write_graph(&mut content, pkg, graph, self_uid, library_uid); - } - if !pkg.resources.is_empty() { - let _ = write!(content, "", writer.next_uid()); - for resource in &pkg.resources { - let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); - let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); - // A resource linked to a file next to the package stays a link; one linked from - // elsewhere (or opened without a folder) is embedded, so the file is whole. - let relative = resource.link.as_deref().filter(|l| !l.contains(':') && !l.starts_with('/') && !l.starts_with('\\')); - match relative { - Some(path) => { - let _ = write!( - content, - "", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - xml_escape(path) - ); - } - None => { - let _ = write!( - content, - "", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - resource.bytes.len(), - encode_embedded(resource.bytes.as_slice())? - ); - } - } - } - content.push_str(""); - } - content.push_str(""); - - let mut out = String::with_capacity(content.len() + 4096); - let _ = write!( - out, - "", - xml_escape(&pkg.name) - ); - let write_dependency = |out: &mut String, file: &str, uid: u64| { - let _ = write!( - out, - "", - xml_escape(file) - ); - }; - write_dependency(&mut out, SELF_DEPENDENCY, self_uid); - write_dependency(&mut out, LIBRARY_DEPENDENCY, library_uid); - for (file, uid) in &writer.external_packages { - write_dependency(&mut out, file, *uid); - } - out.push_str(""); - out.push_str(&content); - - // The exact copy; resource bytes live in the resources above - let json = serde_json::to_vec(pkg).map_err(|e| FormatError::Io(e.to_string()))?; - let hash = content_hash(content.as_bytes()); - let _ = write!(out, "", encode_embedded(&json)?); - out.push_str("\n"); - Ok(out.into_bytes()) -} - -struct SbsWriter { - last_uid: u64, - /// Packages placeholders come from: file name → dependency uid. - external_packages: BTreeMap, -} - -/// An output port's SBS type: 1 color, 2 grayscale. -fn sbs_output_type(kind: PortKind) -> u8 { - if kind == PortKind::Gray { 2 } else { 1 } -} - -/// Text parameter `key` of `node`, or `default` when unset or empty. -fn text_param(node: &Node, key: &str, default: &str) -> String { - match node.params.get(key) { - Some(Value::Text(s)) if !s.is_empty() => s.clone(), - _ => default.to_string(), - } -} - -/// A node's output ports as (port, SBS type, uid). -type WrittenOutputs = Vec<(String, u8, u64)>; - -impl SbsWriter { - fn next_uid(&mut self) -> u64 { - self.last_uid = self.last_uid.saturating_add(1); - self.last_uid - } - - fn external_package_uid(&mut self, file: &str) -> u64 { - if let Some(uid) = self.external_packages.get(file) { - return *uid; - } - - let uid = self.next_uid(); - self.external_packages.insert(file.to_string(), uid); - uid - } - - /// The output ports of `node` as (port, SBS type). - fn output_ports(pkg: &Package, node: &Node) -> Vec<(String, u8)> { - match node.def.as_str() { - "output" => Vec::new(), - "graph_instance" => { - let sub_graph = match node.params.get("graph") { - Some(Value::Text(name)) => pkg.graph_by_name(name).map(|(_, g)| g), - _ => None, - }; - let outputs = sub_graph.into_iter().flat_map(|g| g.nodes.iter().filter(|o| o.def == "output")); - outputs.map(|o| (text_param(o, "identifier", "output"), 1)).collect() - } - def if def == MISSING_NODE => missing_ports(node).1.into_iter().map(|(id, gray)| (id, if gray { 2 } else { 1 })).collect(), - def => match find(def) { - Some(def) => def.outputs.iter().map(|o| (o.id.to_string(), sbs_output_type(o.kind))).collect(), - None => vec![("output".into(), 1)], - }, - } - } - - fn write_graph(&mut self, out: &mut String, pkg: &Package, graph: &Graph, self_uid: u64, library_uid: u64) { - let _ = write!(out, "", xml_escape(&graph.name), self.next_uid()); - let attributes = &graph.attributes; - if !(attributes.category.is_empty() && attributes.description.is_empty() && attributes.author.is_empty() && attributes.tags.is_empty()) { - let _ = write!( - out, - "", - xml_escape(&attributes.category), - xml_escape(&attributes.description), - xml_escape(&attributes.author), - xml_escape(&attributes.tags) - ); - } - - let mut node_uids: HashMap = HashMap::new(); - let mut node_outputs: HashMap = HashMap::new(); - for node in &graph.nodes { - node_uids.insert(node.id, self.next_uid()); - let outputs = Self::output_ports(pkg, node).into_iter().map(|(port, kind)| (port, kind, self.next_uid())).collect(); - node_outputs.insert(node.id, outputs); - } - - let input_entries = self.write_graph_inputs(out, graph); - let output_uids = self.write_graph_outputs(out, graph); - - let mut wires_into: HashMap> = HashMap::new(); - for wire in &graph.connections { - wires_into.entry(wire.to).or_default().push(wire); - } - out.push_str(""); - for node in &graph.nodes { - let uid = node_uids.get(&node.id).copied().unwrap_or(0); - let (x, y) = (node.pos[0] + NODE_HALF_SIZE[0], node.pos[1] + NODE_HALF_SIZE[1]); - let _ = write!(out, "", format_float(x), format_float(y)); - - let outputs = node_outputs.get(&node.id).map_or(&[][..], Vec::as_slice); - if !outputs.is_empty() { - out.push_str(""); - for (_, kind, output_uid) in outputs { - let _ = write!(out, ""); - } - out.push_str(""); - } - - let filter = filter_by_def(&node.def); - let wires = wires_into.get(&node.id).map_or(&[][..], Vec::as_slice); - if !wires.is_empty() { - out.push_str(""); - for wire in wires { - let Some(from_uid) = node_uids.get(&wire.from) else { continue }; - let Some((_, _, output_uid)) = node_outputs.get(&wire.from).and_then(|o| o.iter().find(|(port, _, _)| *port == wire.from_port)) else { - continue; - }; - - let identifier = if node.def == "output" { - "inputNodeOutput".to_string() - } else { - let mapped = filter.and_then(|f| f.inputs.iter().find(|(_, port)| *port == wire.to_port)); - mapped.map_or(wire.to_port.clone(), |(sbs, _)| sbs.to_string()) - }; - let _ = write!( - out, - "", - xml_escape(&identifier) - ); - } - out.push_str(""); - } - - out.push_str(""); - let ids = NodeUids { input_entry: input_entries.get(&node.id).copied(), graph_output: output_uids.get(&node.id).copied(), self_uid, library_uid }; - self.write_implementation(out, node, outputs, ids); - out.push_str(""); - } - out.push_str(""); - - write_canvas_items(out, graph, self); - let [width, height] = graph.size.map(|s| s.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)); - let _ = write!(out, ""); - for uid in graph.nodes.iter().filter_map(|n| output_uids.get(&n.id)) { - let _ = write!(out, ""); - } - out.push_str(""); - } - - /// Image inputs (input nodes) and exposed values; returns input node → paraminput uid. - fn write_graph_inputs(&mut self, out: &mut String, graph: &Graph) -> HashMap { - let mut entries = HashMap::new(); - out.push_str(""); - - for node in graph.nodes.iter().filter(|n| n.def == "input_color" || n.def == "input_grayscale") { - let uid = self.next_uid(); - entries.insert(node.id, uid); - let default = match node.params.get("default") { - Some(color @ Value::Color(_)) => constant_xml(color).unwrap_or_default(), - _ => "".into(), - }; - let code = if node.def == "input_grayscale" { type_code::GRAY_IMAGE } else { type_code::COLOR_IMAGE }; - let _ = write!( - out, - "{default}", - xml_escape(&text_param(node, "identifier", "input")) - ); - } - - for exposed in &graph.exposed { - let default = constant_xml(&exposed.default).unwrap_or_else(|| "".into()); - let group = if exposed.group.is_empty() { String::new() } else { format!("", xml_escape(&exposed.group)) }; - let _ = write!( - out, - "{default}{group}", - xml_escape(&exposed.id), - self.next_uid(), - xml_escape(&exposed.label), - exposed_type_code(&exposed.default), - format_float(exposed.min), - format_float(exposed.max) - ); - } - - out.push_str(""); - entries - } - - /// Graph outputs (output nodes); returns output node → graphoutput uid. - fn write_graph_outputs(&mut self, out: &mut String, graph: &Graph) -> HashMap { - let mut output_uids = HashMap::new(); - out.push_str(""); - - for node in graph.nodes.iter().filter(|n| n.def == "output") { - let uid = self.next_uid(); - output_uids.insert(node.id, uid); - let usage = node.params.get("usage").and_then(Value::as_i32).unwrap_or(0).max(0) as u32; - let identifier = text_param(node, "identifier", "output"); - let label = if node.label.is_empty() { identifier.clone() } else { node.label.clone() }; - let _ = write!( - out, - "", - xml_escape(&identifier), - xml_escape(&label), - usage_name(usage) - ); - } - - out.push_str(""); - output_uids - } - - /// The `compImplementation` body of `node`. - fn write_implementation(&mut self, out: &mut String, node: &Node, outputs: &[(String, u8, u64)], ids: NodeUids) { - let base = base_params_xml(&node.base); - - match node.def.as_str() { - "output" => { - let _ = write!(out, "", ids.graph_output.unwrap_or(0)); - } - "input_color" | "input_grayscale" => { - let _ = write!(out, "{base}", ids.input_entry.unwrap_or(0)); - } - "graph_instance" => { - let sub_graph = text_param(node, "graph", ""); - let params: String = node.params.iter().filter(|(k, _)| *k != "graph").filter_map(|(k, v)| param_xml(k, v)).collect(); - let _ = write!( - out, - "{base}{params}", - xml_escape(&sub_graph), - ids.self_uid - ); - write_bridgings(out, outputs); - out.push_str(""); - } - def if def == MISSING_NODE => { - let name = text_param(node, "sbs_name", &node.label); - let raw_params = match node.params.get("sbs_parameters") { - Some(Value::Text(s)) if is_parameters_element(s) => s.clone(), - _ => "".into(), - }; - if text_param(node, "sbs_kind", "instance") == "filter" { - let _ = write!(out, "{raw_params}", xml_escape(&name)); - return; - } - - let package = text_param(node, "sbs_package", ""); - let dependency = if package.is_empty() { ids.library_uid } else { self.external_package_uid(&package) }; - let path = text_param(node, "sbs_path", &name); - let _ = write!(out, "{raw_params}", xml_escape(&path)); - write_bridgings(out, outputs); - out.push_str(""); - } - def => match (filter_by_def(def), find(def)) { - (Some(filter), Some(catalog_def)) => { - let _ = write!(out, "{base}", filter.sbs); - let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default)); - for (sbs_name, mc_name, conversion) in filter.params { - let Some(value) = value_of(mc_name) else { continue }; - let value = if *conversion == TrueIsFirstOption { Value::Bool(value.as_i32() == Some(0)) } else { value.clone() }; - out.push_str(¶m_xml(sbs_name, &value).unwrap_or_default()); - } - out.push_str(&special_filter_params_xml(filter.sbs, &value_of, ids.self_uid)); - out.push_str(""); - } - _ => { - let params: String = node.params.iter().filter_map(|(k, v)| param_xml(k, v)).collect(); - let _ = write!( - out, - "{base}{params}", - xml_escape(def), - ids.library_uid - ); - write_bridgings(out, outputs); - out.push_str(""); - } - }, - } - } -} - -/// The uids a node's implementation refers to. -#[derive(Clone, Copy)] -struct NodeUids { - input_entry: Option, - graph_output: Option, - self_uid: u64, - library_uid: u64, -} - -/// Filter parameters that don't map one to one: the bitmap path, grayscale weights, the 2×2 matrix. -fn special_filter_params_xml<'a>(filter: &str, value_of: &dyn Fn(&str) -> Option<&'a Value>, self_uid: u64) -> String { - match filter { - "bitmap" => match value_of("resource") { - Some(Value::Text(name)) if !name.is_empty() => { - param_xml("bitmapresourcepath", &Value::Text(format!("pkg:///Resources/{name}?dependency={self_uid}"))).unwrap_or_default() - } - _ => String::new(), - }, - "grayscaleconversion" => { - let weight = |channel: &str| value_of(channel).and_then(Value::as_f32).unwrap_or(0.0); - param_xml("channelsweights", &Value::Float4([weight("red"), weight("green"), weight("blue"), weight("alpha")])).unwrap_or_default() - } - "transformation" => { - let scale = match value_of("scale") { - Some(Value::Float2(s)) => *s, - _ => [1.0, 1.0], - }; - let (sin, cos) = (value_of("rotation").and_then(Value::as_f32).unwrap_or(0.0) * std::f32::consts::TAU).sin_cos(); - param_xml("matrix22", &Value::Float4([scale[0] * cos, -scale[1] * sin, scale[0] * sin, scale[1] * cos])).unwrap_or_default() - } - _ => String::new(), - } -} - -/// Frames (framed comments) and comments. -fn write_canvas_items(out: &mut String, graph: &Graph, writer: &mut SbsWriter) { - out.push_str(""); - - for frame in &graph.frames { - let [x, y, width, height] = frame.rect.map(format_float); - let [r, g, b] = [0, 1, 2].map(|i| format_float(linear_to_srgb(frame.color[i]))); - let _ = write!( - out, - "<frameColor v=\"{r} {g} {b} {}\"/><isTitleVisible v=\"1\"/><isFrameVisible v=\"1\"/></GUIObject>", - xml_escape(&frame.description), - writer.next_uid(), - xml_escape(&frame.title), - format_float(frame.color[3]) - ); - } - - for comment in &graph.comments { - let [x, y] = comment.pos.map(format_float); - let [width, height] = comment.size.map(format_float); - let _ = write!( - out, - "<GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"{x} {y} 0\"/><size v=\"{width} {height}\"/></GUILayout><GUIName v=\"{}\"/><uid v=\"{}\"/><isFrameVisible v=\"0\"/></GUIObject>", - xml_escape(&comment.text), - writer.next_uid() - ); - } - - out.push_str("</GUIObjects>"); -} - -fn write_bridgings(out: &mut String, outputs: &[(String, u8, u64)]) { - out.push_str("<outputBridgings>"); - for (port, _, uid) in outputs { - let _ = write!(out, "<outputBridging><uid v=\"{uid}\"/><identifier v=\"{}\"/></outputBridging>", xml_escape(port)); - } - out.push_str("</outputBridgings>"); -} - -/// One `<parameter>` element (`None` for values SBS constants can't hold). -fn param_xml(name: &str, value: &Value) -> Option<String> { - Some(format!("<parameter><name v=\"{}\"/><relativeTo v=\"0\"/><paramValue>{}</paramValue></parameter>", xml_escape(name), constant_xml(value)?)) -} - -fn base_params_xml(base: &BaseParams) -> String { - let mut out = String::new(); - - if base.size_mode != SizeMode::RelativeToInput || base.size != [0, 0] { - let relative_to = match base.size_mode { - SizeMode::Absolute => 0, - SizeMode::RelativeToInput => 1, - SizeMode::RelativeToParent => 2, - }; - let [width, height] = base.size; - let _ = write!( - out, - "<parameter><name v=\"outputsize\"/><relativeTo v=\"{relative_to}\"/><paramValue><constantValueInt2 v=\"{width} {height}\"/></paramValue></parameter>" - ); - } - - let format = match base.format { - OutputFormat::Inherit => None, - OutputFormat::U8 => Some(0), - OutputFormat::U16 => Some(1), - OutputFormat::F16 => Some(2), - OutputFormat::F32 => Some(3), - }; - if let Some(format) = format { - let _ = write!(out, "<parameter><name v=\"format\"/><relativeTo v=\"0\"/><paramValue><constantValueInt1 v=\"{format}\"/></paramValue></parameter>"); - } - - if base.seed != 0 { - let _ = write!( - out, - "<parameter><name v=\"randomseed\"/><relativeTo v=\"0\"/><paramValue><constantValueInt1 v=\"{}\"/></paramValue></parameter>", - base.seed - ); - } - out -} - -/// Whether `xml` is one well-formed `<parameters>` element, the raw SBS a placeholder keeps. -fn is_parameters_element(xml: &str) -> bool { - let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1_000_000 }; - xml.len() < (16 << 20) && roxmltree::Document::parse_with_options(xml, options).is_ok_and(|d| d.root_element().tag_name().name() == "parameters") -} - -#[cfg(test)] -mod tests { - use super::*; - use materialcraft_core::Graph; - - fn no_linked_files(_: &str) -> Option<Vec<u8>> { - None - } - - /// The SBS data of a written package without the exact copy, as another program would leave it. - fn without_exact_copy(bytes: &[u8]) -> String { - let text = String::from_utf8(bytes.to_vec()).unwrap(); - format!("{}</package>", &text[..text.find("<!--").unwrap()]) - } - - fn sample_package() -> Package { - let mut pkg = Package::new("Bricks"); - let mut graph = Graph::new("Wall"); - graph.size = [9, 9]; - - let bricks = graph.add_node("brick_generator", [0.0, 0.0]); - let blur = graph.add_node("blur", [150.0, 0.0]); - let uniform = graph.add_node("uniform", [0.0, 150.0]); - let blend = graph.add_node("blend", [300.0, 0.0]); - let output = graph.add_node("output", [450.0, 0.0]); - graph.connect(bricks, "output", blur, "input").unwrap(); - graph.connect(blur, "output", blend, "foreground").unwrap(); - graph.connect(uniform, "output", blend, "background").unwrap(); - graph.connect(blend, "output", output, "input").unwrap(); - - let blur_node = graph.node_mut(blur).unwrap(); - blur_node.params.insert("intensity".into(), Value::Float(4.5)); - blur_node.base.size_mode = SizeMode::Absolute; - blur_node.base.size = [8, 8]; - graph.node_mut(uniform).unwrap().params.insert("color".into(), Value::Color([0.25, 0.5, 0.75, 1.0])); - graph.node_mut(blend).unwrap().params.insert("mode".into(), Value::Enum(3)); - let output_node = graph.node_mut(output).unwrap(); - output_node.params.insert("usage".into(), Value::Enum(4)); - output_node.params.insert("identifier".into(), Value::Text("height".into())); - // Only the exact copy can carry a curve - graph.node_mut(bricks).unwrap().params.insert("curvy".into(), Value::Curve(materialcraft_core::Curve::default())); - graph.frames.push(Frame { - id: 90, - title: "Frame & <title>".into(), - description: "note".into(), - rect: [-10.0, -10.0, 300.0, 200.0], - color: [0.1, 0.2, 0.3, 0.4], - }); - pkg.graphs.push(graph); - - let orange = materialcraft_image::Image::filled(4, 4, materialcraft_image::Kind::Color, [1.0, 0.5, 0.0, 1.0]); - let png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap(); - pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png))); - pkg - } - - #[test] - fn sniffs_sbs() { - assert!(is_sbs(b"<?xml version=\"1.0\"?>\n<package><content/></package>")); - assert!(is_sbs(b"\xef\xbb\xbf<package>")); - assert!(is_sbs(b"<!-- hi --><package >")); - assert!(!is_sbs(b"<packages>")); - assert!(!is_sbs(b"PK\x03\x04zip")); - assert!(!is_sbs(b"<?xml")); - assert!(!is_sbs(b"")); - } - - #[test] - fn exact_round_trip() { - let pkg = sample_package(); - let bytes = write_sbs(&pkg).unwrap(); - assert!(is_sbs(&bytes)); - - let read = read_sbs(&bytes, "Bricks.sbs", &no_linked_files).unwrap(); - assert!(read.exact, "{:?}", read.warnings); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_eq!(read.pkg.graphs, pkg.graphs); - assert_eq!(read.pkg.resources[0].bytes, pkg.resources[0].bytes); - assert_eq!(read.pkg.name, "Bricks"); - } - - /// The SBS data alone carries the graph. - #[test] - fn structural_round_trip() { - let pkg = sample_package(); - let plain = without_exact_copy(&write_sbs(&pkg).unwrap()); - let read = read_sbs(plain.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - assert!(!read.exact); - - let (original, back) = (&pkg.graphs[0], &read.pkg.graphs[0]); - assert_eq!(back.name, "Wall"); - assert_eq!(back.size, [9, 9]); - assert_eq!(back.nodes.len(), original.nodes.len()); - assert_eq!(back.connections.len(), original.connections.len()); - for (a, b) in original.nodes.iter().zip(&back.nodes) { - assert_eq!(a.def, b.def); - assert!((a.pos[0] - b.pos[0]).abs() < 1e-3 && (a.pos[1] - b.pos[1]).abs() < 1e-3); - assert_eq!(a.base, b.base); - } - - assert_eq!(back.nodes[1].params.get("intensity"), Some(&Value::Float(4.5))); - let Some(Value::Color(color)) = back.nodes[2].params.get("color") else { panic!("uniform color") }; - assert!((color[0] - 0.25).abs() < 1e-3 && (color[2] - 0.75).abs() < 1e-3); - assert_eq!(back.nodes[3].params.get("mode"), Some(&Value::Enum(3))); - assert_eq!(back.nodes[4].params.get("usage"), Some(&Value::Enum(4))); - assert_eq!(back.nodes[4].params.get("identifier"), Some(&Value::Text("height".into()))); - assert_eq!(back.frames[0].title, "Frame & <title>"); - assert_eq!(read.pkg.resources[0].bytes, pkg.resources[0].bytes); - - let blend = back.nodes[3].id; - assert_eq!(back.input_of(blend, "foreground").map(|c| c.from), Some(back.nodes[1].id)); - assert_eq!(back.input_of(blend, "background").map(|c| c.from), Some(back.nodes[2].id)); - } - - #[test] - fn edited_file_falls_back_to_sbs_data() { - let text = String::from_utf8(write_sbs(&sample_package()).unwrap()).unwrap().replace("<identifier v=\"Wall\"/>", "<identifier v=\"Wall2\"/>"); - let read = read_sbs(text.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - - assert!(!read.exact); - assert_eq!(read.pkg.graphs[0].name, "Wall2"); - assert!(read.warnings.iter().any(|w| w.contains("changed outside")), "{:?}", read.warnings); - } - - #[test] - fn damaged_exact_copy_falls_back_with_a_warning() { - let text = String::from_utf8(write_sbs(&sample_package()).unwrap()).unwrap(); - let data_start = text.find("data=").unwrap() + "data=".len(); - let data_end = data_start + text[data_start..].find(' ').unwrap(); - let damaged = format!("{}AAAAAAAAAAAA{}", &text[..data_start], &text[data_end..]); - let read = read_sbs(damaged.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - - assert!(!read.exact); - assert_eq!(read.pkg.graphs[0].nodes.len(), 5); - assert!(read.warnings.iter().any(|w| w.contains("damaged")), "{:?}", read.warnings); - } - - #[test] - fn missing_nodes_are_placeholders_that_survive_saving() { - let xml = r#"<?xml version="1.0"?><package><identifier v="P"/><dependencies><dependency><filename v="sbs://noise_fancy.sbs"/><uid v="7"/></dependency></dependencies><content><graph><identifier v="G"/> - <compNodes> - <compNode><uid v="1"/><GUILayout><gpos v="0 0 0"/></GUILayout><compOutputs><compOutput><uid v="11"/><comptype v="2"/></compOutput></compOutputs> - <compImplementation><compInstance><path v="pkg:///fancy_noise?dependency=7"/><parameters><parameter><name v="scale"/><paramValue><constantValueFloat1 v="3"/></paramValue></parameter></parameters> - <outputBridgings><outputBridging><uid v="11"/><identifier v="noise"/></outputBridging></outputBridgings></compInstance></compImplementation></compNode> - <compNode><uid v="2"/><GUILayout><gpos v="200 0 0"/></GUILayout><compOutputs><compOutput><uid v="21"/><comptype v="1"/></compOutput></compOutputs> - <connections><connection><identifier v="input1"/><connRef v="1"/><connRefOutput v="11"/></connection></connections> - <compImplementation><compFilter><filter v="blur"/><parameters><parameter><name v="intensity"/><paramValue><constantValueFloat1 v="6"/></paramValue></parameter><parameter><name v="bogus"/><paramValue><constantValueFloat1 v="6"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode> - <compNode><uid v="3"/><GUILayout><gpos v="400 0 0"/></GUILayout><compOutputs><compOutput><uid v="31"/><comptype v="1"/></compOutput></compOutputs> - <connections><connection><identifier v="weird_in"/><connRef v="2"/><connRefOutput v="21"/></connection></connections> - <compImplementation><compFilter><filter v="futurefilter"/><parameters/></compFilter></compImplementation></compNode> - </compNodes></graph></content></package>"#; - let read = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); - let graph = &read.pkg.graphs[0]; - assert_eq!(graph.nodes.len(), 3); - assert_eq!(graph.connections.len(), 2); - - let fancy = &graph.nodes[0]; - assert_eq!(fancy.def, MISSING_NODE); - assert_eq!(fancy.label, "fancy_noise"); - assert_eq!(missing_ports(fancy).1, vec![("noise".to_string(), true)]); - assert_eq!(graph.nodes[1].params.get("intensity"), Some(&Value::Float(6.0))); - assert_eq!(graph.input_of(graph.nodes[1].id, "input").map(|c| c.from_port.as_str()), Some("noise")); - assert_eq!(missing_ports(&graph.nodes[2]).0, vec!["weird_in".to_string()]); - for expected in ["missing node `fancy_noise`", "missing node `futurefilter`", "bogus"] { - assert!(read.warnings.iter().any(|w| w.contains(expected)), "{expected}: {:?}", read.warnings); - } - - // Saved and read back from the SBS data alone, the placeholders are written as they came - let text = String::from_utf8(write_sbs(&read.pkg).unwrap()).unwrap(); - assert!(text.contains("sbs://noise_fancy.sbs")); - assert!(text.contains("pkg:///fancy_noise?dependency=")); - assert!(text.contains("<filter v=\"futurefilter\"/>")); - let back = read_sbs(without_exact_copy(text.as_bytes()).as_bytes(), "p.sbs", &no_linked_files).unwrap(); - let back_graph = &back.pkg.graphs[0]; - assert_eq!(back_graph.nodes[0].def, MISSING_NODE); - assert_eq!(back_graph.nodes[0].params.get("sbs_parameters"), fancy.params.get("sbs_parameters")); - assert_eq!(back_graph.connections.len(), 2); - } - - /// Wires are connected in one pass: the last wire into an input wins and a cycle loses one wire. - #[test] - fn wires_keep_the_last_per_input_and_drop_cycles() { - let node = |uid: u32, wires: &str| { - format!( - "<compNode><uid v=\"{uid}\"/><compOutputs><compOutput><uid v=\"{}\"/></compOutput></compOutputs><connections>{wires}</connections><compImplementation><compFilter><filter v=\"blend\"/></compFilter></compImplementation></compNode>", - uid + 100 - ) - }; - let wire = |input: &str, from: u32| { - format!("<connection><identifier v=\"{input}\"/><connRef v=\"{from}\"/><connRefOutput v=\"{}\"/></connection>", from + 100) - }; - let xml = format!( - "<package><content><graph><identifier v=\"G\"/><compNodes>{}{}{}{}</compNodes></graph></content></package>", - node(1, ""), - node(2, &format!("{}{}", wire("source", 1), wire("source", 4))), - node(3, &wire("source", 2)), - node(4, &wire("source", 3)) - ); - let read = read_sbs(xml.as_bytes(), "x.sbs", &no_linked_files).unwrap(); - let graph = &read.pkg.graphs[0]; - - // 2 takes 4 (the last wire), which closes 2 → 3 → 4 → 2, so one wire of that loop is dropped - assert_eq!(graph.connections.len(), 2); - assert!(graph.input_of(graph.nodes[1].id, "foreground").is_none_or(|c| c.from == graph.nodes[3].id)); - assert_eq!(graph.topo_order().len(), 4); - assert!(read.warnings.iter().any(|w| w.contains("cycle")), "{:?}", read.warnings); - } - - #[test] - fn hostile_input_is_an_error_or_a_warning_never_a_panic() { - let cases: &[&str] = &[ - "", - "<package", - "<notpackage/>", - "<!DOCTYPE package [<!ENTITY x \"y\">]><package/>", - "<package><content><graph/></content></package>", - "<package><content><graph><compNodes><compNode/><compNode><uid v=\"1\"/><compImplementation><compInstance/></compImplementation></compNode><compNode><uid v=\"1\"/></compNode></compNodes></graph></content></package>", - "<package><content><graph><options><option><name v=\"defaultParentSize\"/><value v=\"99999x-4\"/></option></options><compNodes><compNode><uid v=\"1\"/><connections><connection><identifier v=\"input1\"/><connRef v=\"1\"/><connRefOutput v=\"9\"/></connection></connections><compImplementation><compFilter><filter v=\"blur\"/><parameters><parameter><name v=\"outputsize\"/><relativeTo v=\"0\"/><paramValue><constantValueInt2 v=\"99999999999 nan\"/></paramValue></parameter><parameter><name v=\"intensity\"/><paramValue><constantValueFloat1 v=\"inf\"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph></content></package>", - "<package><content><resource><identifier v=\"r\"/><source><binembedded><strdata v=\"////\"/></binembedded></source></resource><resource><identifier v=\"s\"/><source><binembedded><strdata v=\"f////w==\"/></binembedded></source></resource><resource><identifier v=\"t\"/><filepath v=\"../../etc/passwd\"/></resource></content></package>", - "<package><content/><!-- materialcraft-package version=1 hash=0 data=AAAA --></package>", - "<package><content><group><content><group><content><graph><identifier v=\"Deep\"/></graph></content></group></content></group><function><identifier v=\"f\"/></function><weird/></content></package>", - ]; - for case in cases { - if let Ok(read) = read_sbs(case.as_bytes(), "x.sbs", &no_linked_files) { - assert!(!read.pkg.graphs.is_empty(), "{case}"); - } - } - assert!(read_sbs(b"\xff\xfe", "x.sbs", &no_linked_files).is_err()); - - let nested = read_sbs(cases[9].as_bytes(), "x.sbs", &no_linked_files).unwrap(); - assert_eq!(nested.pkg.graphs[0].name, "Deep"); - let clamped = read_sbs(cases[6].as_bytes(), "x.sbs", &no_linked_files).unwrap(); - assert_eq!(clamped.pkg.graphs[0].size, [MAX_SIZE_LOG2, MIN_SIZE_LOG2]); - assert!(clamped.pkg.graphs[0].connections.is_empty(), "a self-wire is a cycle"); - } - - #[test] - fn linked_resources_load_through_the_callback() { - let xml = "<package><content><resource><identifier v=\"img\"/><type v=\"bitmap\"/><format v=\"png\"/><source><externalcopy><filename v=\"p.resources/img.png\"/></externalcopy></source></resource></content></package>"; - - let found = read_sbs(xml.as_bytes(), "p.sbs", &|path| (path == "p.resources/img.png").then(|| vec![1, 2, 3])).unwrap(); - assert_eq!(found.pkg.resources[0].bytes.as_slice(), &[1, 2, 3]); - - let not_found = read_sbs(xml.as_bytes(), "p.sbs", &no_linked_files).unwrap(); - assert!(not_found.pkg.resources.is_empty()); - assert!(not_found.warnings.iter().any(|w| w.contains("img")), "{:?}", not_found.warnings); - } - - #[test] - fn embedded_data_round_trips_and_checks_its_length() { - let data: Vec<u8> = (0..5000u32).map(|i| (i * 7 % 251) as u8).collect(); - let encoded = encode_embedded(&data).unwrap(); - assert_eq!(decode_embedded(&encoded).unwrap(), data); - - let mut raw = base64_engine().decode(&encoded).unwrap(); - raw[3] ^= 1; - assert!(decode_embedded(&base64_engine().encode(raw)).unwrap_err().contains("declared")); - } - - /// The sample with every node of the reference library loads softly and round-trips exactly. - #[test] - fn the_all_nodes_sample_loads_with_warnings() { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs"); - let bytes = std::fs::read(dir.join("all_nodes.sbs")).unwrap(); - assert!(is_sbs(&bytes)); - - let read = read_sbs(&bytes, "all_nodes.sbs", &|path| std::fs::read(dir.join(path)).ok()).unwrap(); - let graph = &read.pkg.graphs[0]; - let placeholders = graph.nodes.iter().filter(|n| n.def == MISSING_NODE).count(); - assert_eq!(graph.nodes.len(), 536); - assert!(graph.nodes.len() - placeholders >= 100, "{placeholders} placeholders"); - assert!(placeholders > 300, "{placeholders} placeholders"); - assert!(read.warnings.iter().any(|w| w.contains("missing node `3D_perlin_noise`")), "{:?}", &read.warnings[..5]); - assert!(read.pkg.resources.iter().any(|r| r.name == "Untitled_Bitmap" && !r.bytes.is_empty())); - let svg = read.pkg.resources.iter().find(|r| r.name == "Untitled_Vector_Graphics").unwrap(); - assert!(String::from_utf8_lossy(svg.bytes.as_slice()).contains("<svg")); - assert_eq!(graph.frames.len(), 26); - assert_eq!(graph.size, [11, 11]); - - let back = read_sbs(&write_sbs(&read.pkg).unwrap(), "x.sbs", &no_linked_files).unwrap(); - assert!(back.exact); - assert_eq!(back.pkg.graphs, read.pkg.graphs); - } -} diff --git a/_to_delete/formats_sbs_functions.rs b/_to_delete/formats_sbs_functions.rs deleted file mode 100644 index b76645f..0000000 --- a/_to_delete/formats_sbs_functions.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! Clean-room import of a bounded subset of numeric SBS parameter expressions. -//! Unsupported operations retain the reader's warning-and-default behavior. - -use materialcraft_core::{ - Value, - function::{FnGraph, FnNode}, -}; -use std::collections::{BTreeMap, HashMap}; - -use super::{XmlNode, child_element, child_value, children_named, sbs_constant, sbs_constant_element, to_natural_value}; - -pub(super) const MAX_NODES: usize = 4096; - -fn float_dims(value: &Value) -> Option<usize> { - match value { - Value::Float(_) => Some(1), - Value::Float2(_) => Some(2), - Value::Float3(_) => Some(3), - Value::Float4(_) => Some(4), - _ => None, - } -} - -pub(super) fn read(dynamic: XmlNode, variables: &BTreeMap<String, Value>, target: &Value) -> Result<FnGraph, String> { - let expected = float_dims(target).ok_or("only float parameter expressions are supported")?; - let elements: Vec<_> = child_element(dynamic, "paramNodes").into_iter().flat_map(|p| children_named(p, "paramNode")).take(MAX_NODES + 1).collect(); - if elements.is_empty() || elements.len() > MAX_NODES { - return Err(format!("expected 1..{MAX_NODES} function nodes")); - } - let mut ids = HashMap::new(); - for (index, node) in elements.iter().enumerate() { - let uid = child_value(*node, "uid").filter(|s| !s.is_empty()).ok_or("function node has no uid")?; - if ids.insert(uid, index as u32 + 1).is_some() { - return Err(format!("duplicate function uid `{uid}`")); - } - } - let output = child_value(dynamic, "rootnode").and_then(|uid| ids.get(uid)).copied().ok_or("function rootnode is missing or unknown")?; - let mut graph = FnGraph { nodes: Vec::with_capacity(elements.len()), output: Some(output) }; - for (index, node) in elements.iter().enumerate() { - if child_value(*node, "disabled").is_some_and(|v| v != "0") { - return Err("disabled function nodes are not supported".into()); - } - let name = child_value(*node, "function").ok_or("function node has no operation")?; - if child_value(*node, "type").is_some_and(|t| !matches!(t, "256" | "512" | "1024" | "2048")) { - return Err(format!("`{name}` has an unsupported result type")); - } - let (op, ports): (&str, &[&str]) = match name { - "const_float1" => ("const_float", &[]), - "const_float2" | "const_float3" | "const_float4" => (name, &[]), - "get_float1" | "get_float2" | "get_float3" | "get_float4" => ("get_var", &[]), - "add" | "sub" | "mul" | "div" => (name, &["a", "b"]), - "neg" | "abs" | "floor" | "ceil" | "cos" | "sin" | "sqrt" | "log" | "exp" => (name, &["a"]), - _ => return Err(format!("unsupported function operation `{name}`")), - }; - let value = if ports.is_empty() { - let data = child_element(*node, "funcDatas") - .into_iter() - .flat_map(|p| children_named(p, "funcData")) - .find(|p| child_value(*p, "name") == Some(name)) - .ok_or_else(|| format!("`{name}` has no function data"))?; - let value = data - .children() - .filter(|n| n.is_element()) - .find_map(|n| sbs_constant_element(n).or_else(|| sbs_constant(n))) - .ok_or_else(|| format!("`{name}` has no constant value"))?; - let value = to_natural_value(&value); - let dims = name.chars().last().and_then(|c| c.to_digit(10)).unwrap_or(0) as usize; - if op == "get_var" { - let Value::Text(variable) = &value else { return Err(format!("`{name}` needs a variable name")) }; - if variables.get(variable).and_then(float_dims) != Some(dims) { - return Err(format!("`{name}` references an unknown or differently typed input `{variable}`")); - } - } else if float_dims(&value) != Some(dims) { - return Err(format!("`{name}` has the wrong constant type")); - } - Some(value) - } else { - None - }; - let mut inputs = vec![None; ports.len()]; - for connection in child_element(*node, "connections").into_iter().flat_map(|p| children_named(p, "connection")) { - let port = child_value(connection, "identifier").unwrap_or(""); - let slot = ports.iter().position(|p| *p == port).and_then(|i| inputs.get_mut(i)).ok_or_else(|| format!("`{name}` has no input `{port}`"))?; - if slot.is_some() { - return Err(format!("duplicate function input `{port}`")); - } - *slot = Some(child_value(connection, "connRef").and_then(|uid| ids.get(uid)).copied().ok_or("function connection references an unknown node")?); - } - if inputs.iter().any(Option::is_none) { - return Err(format!("`{name}` has an unconnected input")); - } - graph.nodes.push(FnNode { id: index as u32 + 1, op: op.into(), inputs, value, pos: [index as f32 * 140.0, 0.0] }); - } - let program = materialcraft_nodes::function::compile(&graph, variables, 0)?; - if program.dims() != expected { - return Err("function result type does not match the parameter".into()); - } - Ok(graph) -} diff --git a/_to_delete/formats_tests_sbs_functions.rs b/_to_delete/formats_tests_sbs_functions.rs deleted file mode 100644 index 3058e35..0000000 --- a/_to_delete/formats_tests_sbs_functions.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! Original synthetic XML fixtures exercise structural SBS import without a native payload. -use materialcraft_core::Value; -use materialcraft_formats::sbs::{SbsRead, read_sbs, write_sbs}; -use std::collections::BTreeMap; - -fn node(uid: &str, op: &str, value: &str, connections: &str) -> String { - let data = if value.is_empty() { String::new() } else { format!("<funcDatas><funcData><name v=\"{op}\"/>{value}</funcData></funcDatas>") }; - format!("<paramNode><uid v=\"{uid}\"/><function v=\"{op}\"/>{data}<connections>{connections}</connections></paramNode>") -} -fn wire(port: &str, uid: &str) -> String { - format!("<connection><identifier v=\"{port}\"/><connRef v=\"{uid}\"/></connection>") -} -fn xml(nodes: &str, root: &str, filter: &str, parameter: &str) -> String { - format!( - r#"<package><content><graph><identifier v="Math"/><paraminputs><paraminput><identifier v="amount"/><uid v="90"/><type v="256"/><defaultValue><constantValueFloat1 v="0.75"/></defaultValue></paraminput></paraminputs><compNodes><compNode><uid v="10"/><compImplementation><compFilter><filter v="{filter}"/><parameters><parameter><name v="{parameter}"/><paramValue><dynamicValue><rootnode v="{root}"/><paramNodes>{nodes}</paramNodes></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph></content></package>"# - ) -} -fn read(text: &str) -> SbsRead { - let report = read_sbs(text.as_bytes(), "math.sbs", &|_| None).unwrap(); - assert!(!report.exact); - report -} -fn expression() -> String { - // XML order and connection order deliberately differ from dependency/operand order. - [ - node("99999999999", "sub", "", &(wire("b", "2") + &wire("a", "1"))), - node("2", "const_float1", r#"<constantValue><constantValueFloat1 v="0.25"/></constantValue>"#, ""), - node("1", "get_float1", r#"<constantValueString v="amount"/>"#, ""), - ] - .concat() -} -#[test] -fn imports_arithmetic_and_keeps_exposed_inputs_live() { - let report = read(&xml(&expression(), "99999999999", "blur", "intensity")); - assert!(report.warnings.is_empty(), "{:?}", report.warnings); - let f = &report.pkg.graphs[0].nodes[0].functions["intensity"]; - assert_eq!(f.nodes.len(), 3); - let mut vars = BTreeMap::new(); - for (input, expected) in [(0.75, 0.5), (0.5, 0.25)] { - vars.insert("amount".into(), Value::Float(input)); - let program = materialcraft_nodes::function::compile(f, &vars, 0).unwrap(); - assert_eq!(program.eval([0.0; 2], [1.0; 2], &[], true, &mut Vec::new()), [expected; 4]); - } - let saved = write_sbs(&report.pkg).unwrap(); - assert_eq!(read_sbs(&saved, "saved.sbs", &|_| None).unwrap().pkg, report.pkg); -} -#[test] -fn imports_vector_constants_and_unary_operations() { - let nodes = node("1", "const_float2", r#"<constValue><constantValueFloat2 v="-0.25 0.75"/></constValue>"#, "") + &node("2", "abs", "", &wire("a", "1")); - let report = read(&xml(&nodes, "2", "transformation", "offset")); - assert!(report.warnings.is_empty(), "{:?}", report.warnings); - let p = materialcraft_nodes::function::compile(&report.pkg.graphs[0].nodes[0].functions["offset"], &BTreeMap::new(), 0).unwrap(); - assert_eq!(p.dims(), 2); - assert_eq!(&p.eval([0.0; 2], [1.0; 2], &[], true, &mut Vec::new())[..2], &[0.25, 0.75]); -} -#[test] -fn invalid_or_unsupported_expressions_warn_and_keep_defaults() { - let valid = xml(&expression(), "99999999999", "blur", "intensity"); - for (case, text) in [ - valid.replace("rootnode v=\"99999999999\"", "rootnode v=\"missing\""), - valid.replace("function v=\"sub\"", "function v=\"while\""), - valid.replace("connRef v=\"2\"", "connRef v=\"missing\""), - valid.replace("connRef v=\"2\"", "connRef v=\"99999999999\""), - valid.replace("identifier v=\"b\"", "identifier v=\"a\""), - valid.replace("identifier v=\"b\"", "identifier v=\"unknown\""), - valid.replace("uid v=\"2\"", "uid v=\"1\""), - valid.replace("constantValueString v=\"amount\"", "constantValueString v=\"unknown\""), - valid.replace("get_float1", "get_float2"), - valid.replace("function v=\"sub\"", "function v=\"sub\"/><disabled v=\"1\""), - valid.replace("function v=\"sub\"", "function v=\"sub\"/><type v=\"16\""), - valid.replace(&wire("b", "2"), ""), - xml(&node("1", "const_float2", r#"<constantValueFloat2 v="1 2"/>"#, ""), "1", "blur", "intensity"), - ] - .into_iter() - .enumerate() - { - let report = read(&text); - assert!(report.pkg.graphs[0].nodes[0].functions.is_empty(), "case {case}: unsupported expression was imported"); - assert!(report.warnings.iter().any(|w| w.contains("imported its default")), "{:?}", report.warnings); - } -} -#[test] -fn oversized_functions_are_rejected_and_simple_bindings_still_work() { - let constant = node("1", "const_float1", r#"<constantValueFloat1 v="1"/>"#, ""); - let report = read(&xml(&constant.repeat(4097), "1", "blur", "intensity")); - assert!(report.pkg.graphs[0].nodes[0].functions.is_empty()); - assert!(report.warnings.iter().any(|w| w.contains("4096"))); - let getter = node("1", "get_float1", r#"<constantValueString v="amount"/>"#, ""); - let report = read(&xml(&getter, "1", "blur", "intensity")); - assert_eq!(report.pkg.graphs[0].nodes[0].bindings["intensity"], "amount"); - assert!(report.warnings.is_empty()); -} diff --git a/_to_delete/formats_tests_sbs_library_aliases.rs b/_to_delete/formats_tests_sbs_library_aliases.rs deleted file mode 100644 index deb0b64..0000000 --- a/_to_delete/formats_tests_sbs_library_aliases.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! The reported library-node aliases must preserve imported settings and connections. -use materialcraft_core::{Graph, Package, Value}; -use materialcraft_formats::sbs::{read_sbs, write_sbs}; - -fn plain_xml(bytes: &[u8]) -> String { - let text = String::from_utf8(bytes.to_vec()).unwrap(); - // Exercise XML import rather than the writer's embedded exact native-package copy. - format!("{}</package>", text.split("<!--").next().unwrap()) -} -const DEFS: [&str; 4] = ["histogram_scan", "auto_levels", "flood_fill", "height_blend"]; - -fn fixture(def: &str) -> String { - let mut pkg = Package::new("Import check"); - let mut graph = Graph::new("G"); - let source = graph.add_node("uniform", [0.0, 0.0]); - let second = (def == "height_blend").then(|| graph.add_node("uniform", [0.0, 150.0])); - let filter = graph.add_node(def, [150.0, 0.0]); - graph.connect(source, "output", filter, if def == "height_blend" { "top" } else { "input" }).unwrap(); - if let Some(second) = second { - graph.connect(second, "output", filter, "bottom").unwrap(); - } - if def == "histogram_scan" { - let n = graph.node_mut(filter).unwrap(); - n.params.insert("position".into(), Value::Float(0.25)); - n.params.insert("contrast".into(), Value::Float(0.75)); - } - pkg.graphs.push(graph); - plain_xml(&write_sbs(&pkg).unwrap()) -} -fn aliased_fixture(def: &str) -> String { - let xml = fixture(def); - match def { - "histogram_scan" => xml - .replace("<name v=\"position\"/>", "<name v=\"Position\"/>") - .replace("<name v=\"contrast\"/>", "<name v=\"Contrast\"/>") - .replace("<identifier v=\"input\"/>", "<identifier v=\"Input_1\"/>"), - "auto_levels" => xml.replace("<identifier v=\"input\"/>", "<identifier v=\"Input\"/>"), - "flood_fill" => xml.replace("<identifier v=\"input\"/>", "<identifier v=\"mask\"/>"), - "height_blend" => { - xml.replace("<identifier v=\"top\"/>", "<identifier v=\"height_top\"/>").replace("<identifier v=\"bottom\"/>", "<identifier v=\"height_bottom\"/>") - } - _ => panic!("unknown fixture node {def}"), - } -} -fn assert_wires(pkg: &Package, def: &str) { - let g = &pkg.graphs[0]; - let sources: Vec<_> = g.nodes.iter().filter(|n| n.def == "uniform").collect(); - let filter = g.nodes.iter().find(|n| n.def == def).unwrap(); - let ports: &[&str] = if def == "height_blend" { &["top", "bottom"] } else { &["input"] }; - assert_eq!(sources.len(), ports.len()); - assert_eq!(g.connections.len(), ports.len()); - for (source, port) in sources.iter().zip(ports) { - let wire = g.input_of(filter.id, port).unwrap(); - assert_eq!((wire.from, wire.from_port.as_str(), wire.to, wire.to_port.as_str()), (source.id, "output", filter.id, *port)); - } -} - -fn assert_scan_values(pkg: &Package) { - let n = pkg.graphs[0].nodes.iter().find(|n| n.def == "histogram_scan").unwrap(); - assert_eq!(n.params.get("position"), Some(&Value::Float(0.25))); - assert_eq!(n.params.get("contrast"), Some(&Value::Float(0.75))); - assert!(!n.params.contains_key("Position") && !n.params.contains_key("Contrast")); -} - -#[test] -fn canonical_names_keep_parameters_and_wires() { - for def in DEFS { - let read = read_sbs(fixture(def).as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(!read.exact); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_wires(&read.pkg, def); - if def == "histogram_scan" { - assert_scan_values(&read.pkg); - } - } -} -#[test] -fn histogram_scan_keeps_reported_parameter_spellings() { - let xml = fixture("histogram_scan").replace("<name v=\"position\"/>", "<name v=\"Position\"/>").replace("<name v=\"contrast\"/>", "<name v=\"Contrast\"/>"); - let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_scan_values(&read.pkg); -} -#[test] -fn histogram_scan_keeps_reported_input_connection() { - let xml = fixture("histogram_scan").replace("<identifier v=\"input\"/>", "<identifier v=\"Input_1\"/>"); - let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_wires(&read.pkg, "histogram_scan"); -} -#[test] -fn auto_levels_keeps_reported_input_connection() { - let xml = fixture("auto_levels").replace("<identifier v=\"input\"/>", "<identifier v=\"Input\"/>"); - let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_wires(&read.pkg, "auto_levels"); -} -#[test] -fn flood_fill_keeps_reported_mask_connection() { - let read = read_sbs(aliased_fixture("flood_fill").as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_wires(&read.pkg, "flood_fill"); -} -#[test] -fn height_blend_keeps_reported_connections_without_swapping_sources() { - let read = read_sbs(aliased_fixture("height_blend").as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - assert_wires(&read.pkg, "height_blend"); -} -#[test] -fn aliased_imports_survive_a_structural_save_and_reload() { - for def in DEFS { - let read = read_sbs(aliased_fixture(def).as_bytes(), "check.sbs", &|_| None).unwrap(); - assert!(read.warnings.is_empty(), "{:?}", read.warnings); - let xml = plain_xml(&write_sbs(&read.pkg).unwrap()); - let back = read_sbs(xml.as_bytes(), "saved.sbs", &|_| None).unwrap(); - assert!(!back.exact); - assert!(back.warnings.is_empty(), "{:?}", back.warnings); - assert_wires(&back.pkg, def); - if def == "histogram_scan" { - assert_scan_values(&back.pkg); - } - } -} -#[test] -fn unknown_parameters_still_warn() { - let xml = fixture("histogram_scan").replace("<name v=\"contrast\"/>", "<name v=\"UnexpectedContrast\"/>"); - let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap(); - assert_eq!(read.warnings.len(), 1); - assert!(read.warnings[0].contains("UnexpectedContrast")); - let n = read.pkg.graphs[0].nodes.iter().find(|n| n.def == "histogram_scan").unwrap(); - assert_eq!(n.params.get("position"), Some(&Value::Float(0.25))); - assert!(!n.params.contains_key("contrast") && !n.params.contains_key("UnexpectedContrast")); -} -#[test] -fn unknown_inputs_still_warn_and_drop_the_wire() { - for def in DEFS { - let original = if def == "height_blend" { "top" } else { "input" }; - let xml = fixture(def).replace(&format!("<identifier v=\"{original}\"/>"), "<identifier v=\"UnexpectedInput\"/>"); - let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap(); - assert_eq!(read.warnings.len(), 1); - assert!(read.warnings[0].contains("UnexpectedInput")); - let g = &read.pkg.graphs[0]; - if def == "height_blend" { - assert_eq!(g.connections.len(), 1); - assert_eq!(g.connections[0].to_port, "bottom"); - assert_eq!(g.connections[0].from, g.nodes[1].id); - assert_eq!(g.nodes.len(), 3); - } else { - assert!(g.connections.is_empty()); - assert_eq!(g.nodes.len(), 2); - } - } -} diff --git a/_to_delete/nodes_atomic.rs b/_to_delete/nodes_atomic.rs deleted file mode 100644 index 96593f2..0000000 --- a/_to_delete/nodes_atomic.rs +++ /dev/null @@ -1,549 +0,0 @@ -//! The atomic nodes: the built-in operations every graph is made of (blend, blur, levels, -//! curve, HSL, warp, transform, normal, distance, …) plus the graph's own input, output and -//! dot nodes. - -use materialcraft_core::Gradient; -use materialcraft_image::{Image, Kind, luminance}; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::ops::{self, BLEND_MODES}; - -pub const ATOMIC: &str = "Atomic nodes"; -pub const GRAPH_ITEMS: &str = "Graph items"; - -/// Output usages (the material channel an output feeds). -pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"]; - -/// Machine ids of [`USAGES`], used in exports and inspect output. -pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("bitmap", "Bitmap", ATOMIC) - .desc("A bitmap resource of the package, resampled to the node size.") - .atomic() - .generator() - .resource("resource", "Bitmap resource") - .choice("colour_space", "Color space", &["sRGB", "Linear (data)"], 0) - .color_out() - .cook(bitmap), - node("blend", "Blend", ATOMIC) - .desc("Blends a foreground over a background with a blending mode, weighted by opacity and an optional mask.") - .atomic() - .any_in("foreground", "Foreground") - .any_in("background", "Background") - .gray_in("mask", "Opacity") - .float("opacity", "Opacity", 1.0, 0.0, 1.0) - .choice("mode", "Blending mode", BLEND_MODES, 0) - .choice("alpha", "Alpha blending", &["Use source alpha", "Ignore alpha"], 0) - .cook(blend), - node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).cook(blur), - node("channels_shuffle", "Channels Shuffle", ATOMIC) - .desc("Builds a color image from any channels of two inputs.") - .atomic() - .any_in("input1", "Input 1") - .any_in("input2", "Input 2") - .choice("red", "Red", CHANNEL_SOURCES, 0) - .choice("green", "Green", CHANNEL_SOURCES, 1) - .choice("blue", "Blue", CHANNEL_SOURCES, 2) - .choice("alpha", "Alpha", CHANNEL_SOURCES, 3) - .color_out() - .cook(channels_shuffle), - node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").cook(curve), - node("directional_blur", "Directional Blur", ATOMIC) - .desc("Blurs along one direction.") - .atomic() - .any_in("input", "Input") - .float("intensity", "Intensity", 10.0, 0.0, 64.0) - .angle("angle", "Angle", 0.0) - .cook(directional_blur), - node("directional_warp", "Directional Warp", ATOMIC) - .desc("Offsets the input along a direction, by an intensity map.") - .atomic() - .any_in("input", "Input") - .gray_in("intensity_input", "Intensity input") - .float("intensity", "Intensity", 10.0, 0.0, 64.0) - .angle("angle", "Warp angle", 0.0) - .cook(directional_warp), - node("distance", "Distance", ATOMIC) - .desc("Grows white areas of a mask into a distance gradient; with a source, spreads its colors outward.") - .atomic() - .gray_in("mask", "Mask") - .any_in("source", "Source") - .float("distance", "Maximum distance", 10.0, 0.0, 256.0) - .boolean("combine", "Combine distance with source", false) - .cook(distance), - node("emboss", "Emboss", ATOMIC) - .desc("Lights the input with the relief of a height map.") - .atomic() - .any_in("input", "Input") - .gray_in("height", "Height") - .float("intensity", "Intensity", 5.0, 0.0, 32.0) - .angle("light_angle", "Light angle", 0.375) - .color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0]) - .color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0]) - .cook(emboss), - node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) - .desc("Maps a grayscale input through the colors of a row of a gradient image.") - .atomic() - .gray_in("input", "Input") - .color_in("gradient", "Gradient") - .float("position", "Position", 0.5, 0.0, 1.0) - .choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0) - .color_out() - .cook(gradient_dynamic), - node("gradient_map", "Gradient Map", ATOMIC) - .desc("Maps grayscale values to colors along a gradient.") - .atomic() - .gray_in("input", "Input") - .gradient("gradient", "Gradient", Gradient::default()) - .choice("mode", "Color mode", &["Color", "Grayscale"], 0) - .cook(gradient_map), - node("grayscale_conversion", "Grayscale Conversion", ATOMIC) - .desc("Weighted sum of the RGBA channels.") - .atomic() - .color_in("input", "Input") - .float("red", "Red weight", 0.333, 0.0, 1.0) - .float("green", "Green weight", 0.333, 0.0, 1.0) - .float("blue", "Blue weight", 0.333, 0.0, 1.0) - .float("alpha", "Alpha weight", 0.0, 0.0, 1.0) - .boolean("flatten_alpha", "Flatten alpha", false) - .gray_out() - .cook(grayscale_conversion), - node("hsl", "HSL", ATOMIC) - .desc("Hue, saturation and lightness adjustments (0.5 = unchanged).") - .atomic() - .color_in("input", "Input") - .float("hue", "Hue", 0.5, 0.0, 1.0) - .float("saturation", "Saturation", 0.5, 0.0, 1.0) - .float("lightness", "Lightness", 0.5, 0.0, 1.0) - .color_out() - .cook(hsl), - node("levels", "Levels", ATOMIC) - .desc("Remaps the input range, midtones and output range.") - .atomic() - .any_in("input", "Input") - .float("in_low", "Level in low", 0.0, 0.0, 1.0) - .float("in_mid", "Level in mid", 0.5, 0.0, 1.0) - .float("in_high", "Level in high", 1.0, 0.0, 1.0) - .float("out_low", "Level out low", 0.0, 0.0, 1.0) - .float("out_high", "Level out high", 1.0, 0.0, 1.0) - .cook(levels), - node("normal", "Normal", ATOMIC) - .desc("Converts a height map to a tangent-space normal map.") - .atomic() - .gray_in("input", "Input") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) - .boolean("height_alpha", "Height in alpha", false) - .color_out() - .cook(normal), - node("pixel_processor", "Pixel Processor", ATOMIC) - .desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).") - .atomic() - .any_in("input0", "Input 0") - .any_in("input1", "Input 1") - .any_in("input2", "Input 2") - .any_in("input3", "Input 3") - .function("function", "Per pixel function", crate::function::default_pixel_function()) - .choice("output", "Output", &["Color", "Grayscale"], 0) - .cook(crate::function::pixel_processor), - node("value_processor", "Value Processor", ATOMIC) - .desc("Computes one value with a function graph and outputs it as a uniform image.") - .atomic() - .any_in("input0", "Input 0") - .function("function", "Function", materialcraft_core::function::FnGraph::constant(materialcraft_core::Value::Float(0.5))) - .cook(crate::function::value_processor), - node("sharpen", "Sharpen", ATOMIC) - .desc("Unsharp mask.") - .atomic() - .any_in("input", "Input") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .cook(sharpen), - node("transformation", "Transformation 2D", ATOMIC) - .desc("Offsets, scales and rotates the input.") - .atomic() - .any_in("input", "Input") - .float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0) - .float2("scale", "Scale", [1.0, 1.0], 0.01, 10.0) - .angle("rotation", "Rotation", 0.0) - .choice("filtering", "Filtering", &["Bilinear", "Nearest"], 0) - .color("matte", "Matte color", [0.0, 0.0, 0.0, 0.0]) - .cook(transformation), - node("uniform", "Uniform Color", ATOMIC) - .desc("A single color or gray value.") - .atomic() - .generator() - .color("color", "Color", [0.5, 0.5, 0.5, 1.0]) - .choice("mode", "Output", &["Color", "Grayscale"], 0) - .cook(uniform), - node("warp", "Warp", ATOMIC) - .desc("Distorts the input along the slopes of a gradient map.") - .atomic() - .any_in("input", "Input") - .gray_in("gradient", "Gradient") - .float("intensity", "Intensity", 1.0, 0.0, 32.0) - .cook(warp), - node("input_color", "Input Color", GRAPH_ITEMS) - .desc("A color image input of the graph.") - .atomic() - .generator() - .text("identifier", "Identifier", "input") - .color("default", "Default color", [0.5, 0.5, 0.5, 1.0]) - .color_out() - .cook(input_color_default), - node("input_grayscale", "Input Grayscale", GRAPH_ITEMS) - .desc("A grayscale image input of the graph.") - .atomic() - .generator() - .text("identifier", "Identifier", "input") - .color("default", "Default value", [0.5, 0.5, 0.5, 1.0]) - .gray_out() - .cook(input_gray_default), - node("output", "Output", GRAPH_ITEMS) - .desc("An output of the graph: a material channel (usage) or any image.") - .atomic() - .any_in("input", "Input") - .text("identifier", "Identifier", "output") - .choice("usage", "Usage", USAGES, 0) - .cook(passthrough), - node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").cook(passthrough), - node("graph_instance", "Graph Instance", GRAPH_ITEMS) - .desc("Another graph of the package, used as a node.") - .atomic() - .text("graph", "Graph", "") - .cook(crate::catalog::no_cook), - ] -} - -const CHANNEL_SOURCES: &[&str] = - &["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"]; - -fn bitmap(ctx: &Ctx) -> CookResult { - let name = ctx.text("resource"); - // "Linear (data)" keeps the file's values as stored (normal maps, masks); sRGB decodes color. - let key = materialcraft_image::resource_key(name, ctx.i("colour_space") == 1); - match (ctx.resource)(&key) { - Some(img) => Ok(vec![img.resize(ctx.w, ctx.h, ctx.tile)]), - None if name.is_empty() => Ok(vec![ctx.gen_color(|u, v| { - let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 }; - [c, c, c, 1.0] - })]), - None => Err(format!("no bitmap resource `{name}`")), - } -} - -fn blend(ctx: &Ctx) -> CookResult { - let (fg, bg) = (ctx.sized(0), ctx.sized(1)); - let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; - let fg = fg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 0.0])); - let bg = bg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 1.0])); - let mask = ctx.sized(2).map(|m| m.to_gray()); - let (mode, op) = (ctx.i("mode"), ctx.f("opacity")); - let use_alpha = ctx.i("alpha") == 0 && !fg.is_gray(); - Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| { - let (x, y) = (x as i64, y as i64); - let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); - ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, use_alpha, true) - })]) -} - -fn blur(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let sigma = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0 * 0.5; - Ok(vec![ops::gaussian(&img, sigma, ctx.tile)]) -} - -fn channels_shuffle(ctx: &Ctx) -> CookResult { - let a = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let b = ctx.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let src = [ctx.i("red"), ctx.i("green"), ctx.i("blue"), ctx.i("alpha")]; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - src.map(|s| match s { - 0..=3 => pa[s as usize], - 4..=7 => pb[(s - 4) as usize], - 9 => 1.0, - _ => 0.0, - }) - })]) -} - -fn curve(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let c = ctx.curve("curve"); - // A 1024-entry table: the curve is smooth, so linear lookups are exact enough. - let lut: Vec<f32> = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect(); - let f = |v: f32| { - let t = v.clamp(0.0, 1.0) * 1024.0; - let i = t as usize; - let a = lut.get(i).copied().unwrap_or(0.0); - let b = lut.get(i + 1).copied().unwrap_or(a); - a + (b - a) * (t - i as f32) - }; - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) -} - -fn dir_vec(turns: f32) -> (f32, f32) { - let a = turns * std::f32::consts::TAU; - (a.cos(), -a.sin()) -} - -fn directional_blur(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let len = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0; - if len < 0.5 { - return Ok(vec![img]); - } - let (dx, dy) = dir_vec(ctx.f("angle")); - let n = (len.ceil() as i32).clamp(1, 512); - let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let mut acc = [0.0; 4]; - for i in -n..=n { - let t = i as f32 / n as f32 * len * 0.5; - let p = img.sample(u + dx * t * iw, v + dy * t * ih, ctx.tile); - for k in 0..4 { - acc[k] += p[k]; - } - } - acc.map(|a| a / (2 * n + 1) as f32) - })]) -} - -fn directional_warp(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let map = ctx.gray_or(1, 0.0); - let (dx, dy) = dir_vec(ctx.f("angle")); - let k = ctx.f("intensity") / 256.0; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let m = map.sample_gray(u, v, ctx.tile) * k; - img.sample(u + dx * m, v + dy * m, ctx.tile) - })]) -} - -fn distance(ctx: &Ctx) -> CookResult { - let mask = ctx.gray_or(0, 0.0); - let maxd = (ctx.f("distance").max(0.0) * ctx.w as f32 / 256.0).max(1e-3); - let data = mask.data.clone(); - let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5; - let Some(src) = ctx.sized(1) else { - let d2 = ops::distance_sq(ctx.w, ctx.h, inside, ctx.tile); - return Ok(vec![ops::gray_from(ctx.w, ctx.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); - }; - // Propagate the exact nearest mask pixel. Gradient walks can stall at stationary points or - // stop before reaching the mask, leaving background-colored gaps inside the distance range. - let (d2, sites) = ops::distance_sq_with_sites(ctx.w, ctx.h, inside, ctx.tile); - let combine = ctx.b("combine"); - Ok(vec![Image::generate(ctx.w, ctx.h, src.kind, |x, y| { - let i = y as usize * ctx.w as usize + x as usize; - let site = sites.get(i).copied().unwrap_or(usize::MAX); - let mut c = if site == usize::MAX { - [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }] - } else { - src.get((site % ctx.w as usize) as i64, (site / ctx.w as usize) as i64, false) - }; - let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt(); - if d > maxd { - c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]; - } else if combine { - let f = (1.0 - d / maxd).clamp(0.0, 1.0); - c = [c[0] * f, c[1] * f, c[2] * f, c[3]]; - } - c - })]) -} - -fn emboss(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]); - let hmap = ctx.gray_or(1, 0.0); - let (lx, ly) = dir_vec(ctx.f("light_angle")); - let k = ctx.f("intensity") * ctx.w as f32 / 64.0; - let (hi, sh) = (ctx.v4("highlight"), ctx.v4("shadow")); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, ctx.tile); - let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0); - let p = img.get(x as i64, y as i64, false); - let tint = if l >= 0.0 { hi } else { sh }; - let t = l.abs(); - [p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]] - })]) -} - -fn gradient_dynamic(ctx: &Ctx) -> CookResult { - let input = ctx.gray_or(0, 0.0); - let grad = ctx.input(1).map(|g| g.to_color()).unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Color, |u, _| [u, u, u, 1.0])); - let pos = ctx.f("position"); - let vertical = ctx.i("orientation") == 1; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let t = input.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0); - if vertical { grad.sample(pos, t, false) } else { grad.sample(t, pos, false) } - })]) -} - -fn gradient_map(ctx: &Ctx) -> CookResult { - let input = ctx.gray_or(0, 0.0); - let g = ctx.gradient("gradient"); - let lut: Vec<[f32; 4]> = (0..=512).map(|i| g.eval(i as f32 / 512.0)).collect(); - let gray = ctx.i("mode") == 1; - let look = |v: f32| lut.get((v.clamp(0.0, 1.0) * 512.0).round() as usize).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]); - Ok(vec![if gray { input.map(Kind::Gray, |p| [luminance(look(p[0])), 0.0, 0.0, 0.0]) } else { input.map(Kind::Color, |p| look(p[0])) }]) -} - -fn grayscale_conversion(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let w = [ctx.f("red"), ctx.f("green"), ctx.f("blue"), ctx.f("alpha")]; - let flatten = ctx.b("flatten_alpha"); - Ok(vec![img.map(Kind::Gray, |p| { - let mut v = p[0] * w[0] + p[1] * w[1] + p[2] * w[2] + p[3] * w[3]; - if flatten { - v *= p[3]; - } - [v, 0.0, 0.0, 0.0] - })]) -} - -fn hsl(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let (dh, sat, lig) = (ctx.f("hue") - 0.5, ctx.f("saturation"), ctx.f("lightness")); - Ok(vec![img.map(Kind::Color, |p| { - let [h, s, l] = ops::rgb_to_hsl(p); - let s = if sat <= 0.5 { s * sat * 2.0 } else { s + (1.0 - s) * (sat - 0.5) * 2.0 }; - let l = if lig <= 0.5 { l * lig * 2.0 } else { l + (1.0 - l) * (lig - 0.5) * 2.0 }; - let c = ops::hsl_to_rgb(h + dh, s.clamp(0.0, 1.0), l.clamp(0.0, 1.0)); - [c[0], c[1], c[2], p[3]] - })]) -} - -/// The Levels mapping for one value. -pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 { - let span = in_high - in_low; - let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) }; - // NaN (from an input or a hostile parameter) would otherwise spread through the graph. - let t = if t.is_finite() { t } else { 0.0 }; - let mid = in_mid.clamp(0.001, 0.999); - let g = 0.5f32.ln() / mid.ln(); - out_low + t.powf(g) * (out_high - out_low) -} - -fn levels(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let p = [ctx.f("in_low"), ctx.f("in_mid"), ctx.f("in_high"), ctx.f("out_low"), ctx.f("out_high")]; - let f = |v: f32| levels_fn(v, p[0], p[1], p[2], p[3], p[4]); - Ok(vec![img.map(img.kind, |c| [f(c[0]), f(c[1]), f(c[2]), c[3]])]) -} - -/// Tangent-space normal from a height map; `k` scales the slopes. -pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { - Image::generate(h.w, h.h, Kind::Color, |x, y| { - let (dx, dy) = ops::slope(h, x as i64, y as i64, tile); - let (nx, ny, nz) = (-dx * k, dy * k, 1.0); - let l = (nx * nx + ny * ny + nz * nz).sqrt(); - let ny = if directx { -ny } else { ny }; - let a = if alpha_height { h.get_gray(x as i64, y as i64, tile) } else { 1.0 }; - [nx / l * 0.5 + 0.5, ny / l * 0.5 + 0.5, nz / l * 0.5 + 0.5, a] - }) -} - -fn normal(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let k = ctx.f("intensity") * ctx.w as f32 / 32.0; - Ok(vec![height_to_normal(&h, k, ctx.i("format") == 1, ctx.tile, ctx.b("height_alpha"))]) -} - -fn sharpen(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let soft = ops::gaussian(&img, 1.0, ctx.tile); - let k = ctx.f("intensity"); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false)); - [a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]] - })]) -} - -/// Sample `img` through the inverse of offset → rotate → scale about the center. -pub fn transform_sample(img: &Image, u: f32, v: f32, offset: [f32; 2], scale: [f32; 2], rot_turns: f32, nearest: bool, tile: bool) -> Option<[f32; 4]> { - let (s, c) = (rot_turns * std::f32::consts::TAU).sin_cos(); - let (x, y) = (u - 0.5 - offset[0], v - 0.5 - offset[1]); - let (x, y) = (x * c - y * s, x * s + y * c); - let (sx, sy) = (if scale[0].abs() < 1e-4 { 1e-4 } else { scale[0] }, if scale[1].abs() < 1e-4 { 1e-4 } else { scale[1] }); - let (su, sv) = (x / sx + 0.5, y / sy + 0.5); - if !tile && (!(0.0..1.0).contains(&su) || !(0.0..1.0).contains(&sv)) { - return None; - } - Some(if nearest { img.sample_nearest(su, sv, tile) } else { img.sample(su, sv, tile) }) -} - -fn transformation(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let (off, sc, rot) = (ctx.v2("offset"), ctx.v2("scale"), ctx.f("rotation")); - let nearest = ctx.i("filtering") == 1; - let matte = ctx.v4("matte"); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, off, sc, rot, nearest, ctx.tile).unwrap_or(matte))]) -} - -fn uniform(ctx: &Ctx) -> CookResult { - let c = ctx.v4("color"); - Ok(vec![if ctx.i("mode") == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [luminance(c); 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, c) }]) -} - -fn warp(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let grad = ctx.gray_or(1, 0.0); - let k = ctx.f("intensity"); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = ((u * ctx.w as f32) as i64, (v * ctx.h as f32) as i64); - let (dx, dy) = ops::slope(&grad, x, y, ctx.tile); - img.sample(u + dx * k, v + dy * k, ctx.tile) - })]) -} - -fn input_color_default(ctx: &Ctx) -> CookResult { - Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, ctx.v4("default"))]) -} - -fn input_gray_default(ctx: &Ctx) -> CookResult { - Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Gray, [ctx.v4("default")[0]; 4])]) -} - -pub(crate) fn passthrough(ctx: &Ctx) -> CookResult { - Ok(vec![ctx.sized(0).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))]) -} - -/// The kind an output port produces given the node's inputs. -pub fn output_kind(def: &NodeDef, port: usize, inputs: &[Option<Image>]) -> Kind { - match def.outputs.get(port).map(|p| p.kind) { - Some(PortKind::Gray) => Kind::Gray, - Some(PortKind::Color) => Kind::Color, - _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind), - } -} - -#[cfg(test)] -mod levels_tests { - use super::levels_fn; - - #[test] - fn levels_remaps_the_input_range_midtones_and_output_range() { - let close = |a: f32, b: f32| (a - b).abs() < 1e-5; - // Identity by default. - for v in [0.0, 0.25, 0.5, 1.0] { - assert!(close(levels_fn(v, 0.0, 0.5, 1.0, 0.0, 1.0), v)); - } - // The input range stretches and clips. - assert!(close(levels_fn(0.4, 0.2, 0.5, 0.6, 0.0, 1.0), 0.5)); - assert!(close(levels_fn(0.1, 0.2, 0.5, 0.6, 0.0, 1.0), 0.0)); - assert!(close(levels_fn(0.9, 0.2, 0.5, 0.6, 0.0, 1.0), 1.0)); - // Mid is relative to the input range: the value there becomes 0.5. - assert!(close(levels_fn(0.25, 0.0, 0.25, 1.0, 0.0, 1.0), 0.5)); - assert!(close(levels_fn(0.3, 0.2, 0.25, 0.6, 0.0, 1.0), 0.5)); - // The output range, inverted when low > high. - assert!(close(levels_fn(0.5, 0.0, 0.5, 1.0, 0.2, 0.6), 0.4)); - assert!(close(levels_fn(0.0, 0.0, 0.5, 1.0, 1.0, 0.0), 1.0)); - // A collapsed input range is a threshold; NaN never escapes. - assert_eq!(levels_fn(0.49, 0.5, 0.5, 0.5, 0.0, 1.0), 0.0); - assert_eq!(levels_fn(0.5, 0.5, 0.5, 0.5, 0.0, 1.0), 1.0); - assert!(levels_fn(f32::NAN, 0.0, 0.5, 1.0, 0.0, 1.0).is_finite()); - assert!(levels_fn(0.5, f32::NAN, 0.5, f32::NAN, 0.0, 1.0).is_finite()); - } -} diff --git a/_to_delete/nodes_catalog.test.rs b/_to_delete/nodes_catalog.test.rs deleted file mode 100644 index 36e5165..0000000 --- a/_to_delete/nodes_catalog.test.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Parameter resolution tests. - -use std::collections::BTreeMap; - -use materialcraft_core::Value; - -use crate::{catalog, clamp_params, find, resolve_params}; - -fn over(k: &str, v: Value) -> BTreeMap<String, Value> { - BTreeMap::from([(k.to_string(), v)]) -} - -#[test] -fn resolve_params_clamps_to_hard_limits() { - let def = find("splatter").unwrap(); - let p = resolve_params(def, &over("size", Value::Float(1e30))); - assert_eq!(p["size"], Value::Float(17.0)); - let p = resolve_params(def, &over("size", Value::Float(-1e30))); - assert_eq!(p["size"], Value::Float(-16.0)); - let p = resolve_params(def, &over("count", Value::Int(i32::MAX))); - assert_eq!(p["count"], Value::Int(33984)); - let p = resolve_params(def, &over("size", Value::Float(f32::NAN))); - assert_eq!(p["size"], def.param("size").unwrap().default); - let shape = find("shape").unwrap(); - let p = resolve_params(shape, &over("size_xy", Value::Float2([1e9, -1e9]))); - assert_eq!(p["size_xy"], Value::Float2([34.0, -32.0])); -} - -#[test] -fn clamp_params_covers_values_set_after_resolution() { - let def = find("splatter").unwrap(); - let mut p = resolve_params(def, &BTreeMap::new()); - p.insert("size".into(), Value::Float(1e9)); - clamp_params(def, &mut p); - assert_eq!(p["size"], Value::Float(17.0)); -} - -#[test] -fn defaults_lie_inside_their_hard_limits() { - for def in catalog() { - let p = resolve_params(def, &BTreeMap::new()); - for d in &def.params { - assert_eq!(p[d.id], d.default, "{}.{} default is outside its range", def.id, d.id); - } - } -} - -#[test] -fn manual_values_beyond_slider_and_multiple_angle_turns_survive() { - let def = find("splatter").unwrap(); - assert_eq!(resolve_params(def, &over("size", Value::Float(1.25)))["size"], Value::Float(1.25)); - for def in catalog() { - for p in &def.params { - if p.angle && matches!(p.default, Value::Float(_)) { - let v = p.max + (p.max - p.min); - assert_eq!(resolve_params(def, &over(p.id, Value::Float(v)))[p.id], Value::Float(v)); - } - } - } -} diff --git a/_to_delete/nodes_filters.rs b/_to_delete/nodes_filters.rs deleted file mode 100644 index f722c93..0000000 --- a/_to_delete/nodes_filters.rs +++ /dev/null @@ -1,950 +0,0 @@ -//! Filters: adjustments, blending, blurs, channels, effects, normal map tools, tiling and -//! transforms. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind, luminance}; - -use crate::atomic::{height_to_normal, levels_fn, transform_sample}; -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::ops; - -#[cfg(test)] -#[path = "filters.test.rs"] -mod tests; - -const ADJ: &str = "Filters/Adjustments"; -const BLENDING: &str = "Filters/Blending"; -const BLURS: &str = "Filters/Blurs"; -const CHANNELS: &str = "Filters/Channels"; -const EFFECTS: &str = "Filters/Effects"; -const NORMAL: &str = "Filters/Normal map"; -const TILING: &str = "Filters/Tiling"; -const TRANSFORMS: &str = "Filters/Transforms"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - // ---- Adjustments - node("auto_levels", "Auto Levels", ADJ).desc("Stretches the input to the full 0..1 range.").any_in("input", "Input").cook(auto_levels), - node("clamp", "Clamp", ADJ) - .desc("Clamps values between a minimum and a maximum.") - .any_in("input", "Input") - .float("min", "Min", 0.0, 0.0, 1.0) - .float("max", "Max", 1.0, 0.0, 1.0) - .cook(clamp), - node("color_to_mask", "Color to Mask", ADJ) - .desc("White where the input is close to a key color.") - .color_in("input", "Input") - .color("color", "Key color", [1.0, 0.0, 0.0, 1.0]) - .float("range", "Range", 0.2, 0.0, 1.0) - .float("softness", "Softness", 0.1, 0.0, 1.0) - .gray_out() - .cook(color_to_mask), - node("contrast_luminosity", "Contrast/Luminosity", ADJ) - .desc("Contrast and brightness (0 = unchanged).") - .any_in("input", "Input") - .float("contrast", "Contrast", 0.0, -1.0, 1.0) - .float("luminosity", "Luminosity", 0.0, -1.0, 1.0) - .cook(contrast_luminosity), - node("exposure", "Exposure", ADJ).desc("Exposure in stops.").any_in("input", "Input").float("stops", "Exposure (EV)", 0.0, -10.0, 10.0).cook(exposure), - node("gamma", "Gamma", ADJ).desc("Raises values to a power.").any_in("input", "Input").float("gamma", "Gamma", 1.0, 0.01, 10.0).cook(gamma), - node("histogram_range", "Histogram Range", ADJ) - .desc("Compresses values into a range around a position.") - .gray_in("input", "Input") - .float("range", "Range", 0.5, 0.0, 1.0) - .float("position", "Position", 0.5, 0.0, 1.0) - .gray_out() - .cook(histogram_range), - node("histogram_scan", "Histogram Scan", ADJ) - .desc("Thresholds the input at a position with adjustable contrast.") - .gray_in("input", "Input") - .float("position", "Position", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .boolean("invert", "Invert position", false) - .gray_out() - .cook(histogram_scan), - node("histogram_shift", "Histogram Shift", ADJ) - .desc("Shifts values with wrap-around.") - .gray_in("input", "Input") - .float("position", "Position", 0.5, 0.0, 1.0) - .gray_out() - .cook(histogram_shift), - node("invert", "Invert", ADJ).desc("1 minus the input (alpha kept).").any_in("input", "Input").boolean("alpha", "Invert alpha", false).cook(invert), - node("posterize", "Posterize", ADJ) - .desc("Quantizes values to a number of steps.") - .any_in("input", "Input") - .int("steps", "Steps", 4, 2, 256) - .cook(posterize), - node("replace_color", "Replace Color", ADJ) - .desc("Shifts colors near a source color towards a target color.") - .color_in("input", "Input") - .color("source", "Source color", [1.0, 0.0, 0.0, 1.0]) - .color("target", "Target color", [0.0, 0.0, 1.0, 1.0]) - .float("range", "Range", 0.3, 0.0, 1.0) - .color_out() - .cook(replace_color), - node("threshold", "Threshold", ADJ) - .desc("White above the threshold, black below.") - .gray_in("input", "Input") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .gray_out() - .cook(threshold), - node("colorize", "Colorize", ADJ) - .desc("Tints a grayscale image between two colors.") - .gray_in("input", "Input") - .color("dark", "Dark color", [0.05, 0.03, 0.02, 1.0]) - .color("light", "Light color", [0.9, 0.75, 0.5, 1.0]) - .color_out() - .cook(colorize), - node("channel_mixer", "Channel Mixer", ADJ) - .desc("Each output channel as a weighted sum of the input channels.") - .color_in("input", "Input") - .float2("red_rg", "Red from R, G", [1.0, 0.0], -2.0, 2.0) - .float("red_b", "Red from B", 0.0, -2.0, 2.0) - .float2("green_rg", "Green from R, G", [0.0, 1.0], -2.0, 2.0) - .float("green_b", "Green from B", 0.0, -2.0, 2.0) - .float2("blue_rg", "Blue from R, G", [0.0, 0.0], -2.0, 2.0) - .float("blue_b", "Blue from B", 1.0, -2.0, 2.0) - .color_out() - .cook(channel_mixer), - // ---- Blending - node("height_blend", "Height Blend", BLENDING) - .desc("Blends two height maps by which is higher, with a soft contrast; also outputs the mask.") - .gray_in("top", "Height top") - .gray_in("bottom", "Height bottom") - .gray_in("mask", "Mask") - .float("offset", "Height offset", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.9, 0.0, 1.0) - .output("height", "Height", PortKind::Gray) - .output("blend_mask", "Blend mask", PortKind::Gray) - .cook(height_blend), - node("alpha_merge", "Alpha Merge", BLENDING) - .desc("Puts a grayscale image in a color image's alpha.") - .color_in("input", "Color") - .gray_in("alpha", "Alpha") - .color_out() - .cook(alpha_merge), - node("rgba_merge", "RGBA Merge", CHANNELS) - .desc("Builds a color image from four grayscale channels.") - .gray_in("r", "R") - .gray_in("g", "G") - .gray_in("b", "B") - .gray_in("a", "A") - .color_out() - .cook(rgba_merge), - node("rgba_split", "RGBA Split", CHANNELS) - .desc("Splits a color image into four grayscale channels.") - .color_in("input", "RGBA") - .output("r", "R", PortKind::Gray) - .output("g", "G", PortKind::Gray) - .output("b", "B", PortKind::Gray) - .output("a", "A", PortKind::Gray) - .cook(rgba_split), - node("switch", "Switch", BLENDING) - .desc("Outputs input A or input B.") - .any_in("a", "Input A") - .any_in("b", "Input B") - .boolean("use_b", "Use input B", false) - .cook(switch), - // ---- Blurs - node("anisotropic_blur", "Anisotropic Blur", BLURS) - .desc("A Gaussian blur stronger along one direction.") - .any_in("input", "Input") - .float("intensity", "Intensity", 4.0, 0.0, 32.0) - .float("anisotropy", "Anisotropy", 0.5, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .cook(anisotropic_blur), - node("non_uniform_blur", "Non Uniform Blur", BLURS) - .desc("Blurs more where the blur map is white.") - .any_in("input", "Input") - .gray_in("blur_map", "Blur map") - .float("intensity", "Intensity", 4.0, 0.0, 32.0) - .cook(non_uniform_blur), - node("radial_blur", "Radial Blur", BLURS) - .desc("Zoom blur from a center.") - .any_in("input", "Input") - .float("intensity", "Intensity", 0.2, 0.0, 1.0) - .float2("center", "Center", [0.5, 0.5], 0.0, 1.0) - .cook(radial_blur), - node("slope_blur", "Slope Blur", BLURS) - .desc("Smears the input along the slopes of a map, like flowing material.") - .any_in("input", "Input") - .gray_in("slope", "Slope") - .float("intensity", "Intensity", 8.0, -64.0, 64.0) - .int("samples", "Samples", 8, 1, 32) - .choice("mode", "Mode", &["Blur", "Min", "Max"], 0) - .cook(slope_blur), - // ---- Effects - node("ambient_occlusion", "Ambient Occlusion", EFFECTS) - .desc("Darkens creases of a height map.") - .gray_in("height", "Height") - .float("spread", "Spreading", 0.15, 0.0, 1.0) - .float("intensity", "Height depth", 0.5, 0.0, 1.0) - .gray_out() - .cook(ambient_occlusion), - node("bevel", "Bevel", EFFECTS) - .desc("Rounds the edges of a mask into a height ramp.") - .gray_in("input", "Mask") - .float("distance", "Distance", 0.05, -1.0, 1.0) - .float("smoothing", "Smoothing", 0.0, 0.0, 1.0) - .gray_out() - .cook(bevel), - node("curvature", "Curvature", EFFECTS) - .desc("Convexity (white) and concavity (black) of a normal map.") - .color_in("normal", "Normal") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .gray_out() - .cook(curvature), - node("dilation", "Dilation", EFFECTS) - .desc("Grows bright areas (maximum filter).") - .any_in("input", "Input") - .int("radius", "Radius", 2, 0, 64) - .cook(dilation), - node("erosion", "Erosion", EFFECTS) - .desc("Shrinks bright areas (minimum filter).") - .any_in("input", "Input") - .int("radius", "Radius", 2, 0, 64) - .cook(erosion), - node("edge_detect", "Edge Detect", EFFECTS) - .desc("White along the edges of a mask.") - .gray_in("input", "Input") - .float("width", "Edge width", 2.0, 0.0, 32.0) - .float("roundness", "Edge roundness", 0.5, 0.0, 1.0) - .gray_out() - .cook(edge_detect), - node("glow", "Glow", EFFECTS) - .desc("A soft glow around bright areas.") - .any_in("input", "Input") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .float("size", "Size", 8.0, 0.0, 64.0) - .float("amount", "Amount", 0.5, 0.0, 2.0) - .cook(glow), - node("highpass", "Highpass", EFFECTS) - .desc("Keeps the fine detail, centered on gray.") - .any_in("input", "Input") - .float("radius", "Radius", 6.0, 0.0, 64.0) - .cook(highpass), - node("mosaic", "Mosaic", EFFECTS).desc("Pixelates into blocks.").any_in("input", "Input").int("cells", "Cells", 16, 1, 512).cook(mosaic), - node("swirl", "Swirl", EFFECTS) - .desc("Twists the image around its center.") - .any_in("input", "Input") - .float("amount", "Amount", 0.5, -4.0, 4.0) - .float("radius", "Radius", 0.5, 0.0, 1.0) - .cook(swirl), - node("vignette", "Vignette", EFFECTS) - .desc("Darkens towards the borders.") - .any_in("input", "Input") - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.5, 0.0, 1.0) - .cook(vignette), - node("quantize", "Quantize Grayscale", EFFECTS) - .desc("Snaps gray values to steps with soft transitions.") - .gray_in("input", "Input") - .int("steps", "Steps", 4, 2, 64) - .float("smoothness", "Smoothness", 0.1, 0.0, 1.0) - .gray_out() - .cook(quantize), - // ---- Normal map - node("height_to_normal", "Height to Normal", NORMAL) - .desc("Same as Normal: a normal map from a height map.") - .gray_in("input", "Height") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) - .color_out() - .cook(height_normal), - node("normal_blend", "Normal Blend", NORMAL) - .desc("Combines two normal maps (reoriented normal mapping).") - .color_in("base", "Normal base") - .color_in("detail", "Normal detail") - .gray_in("mask", "Mask") - .float("opacity", "Opacity", 1.0, 0.0, 1.0) - .color_out() - .cook(normal_blend), - node("normal_invert", "Normal Invert", NORMAL) - .desc("Flips the green (and optionally red) channel: OpenGL / DirectX.") - .color_in("input", "Normal") - .boolean("red", "Invert red", false) - .boolean("green", "Invert green", true) - .color_out() - .cook(normal_invert), - node("normal_normalize", "Normal Normalize", NORMAL) - .desc("Rescales normals to unit length.") - .color_in("input", "Normal") - .color_out() - .cook(normal_normalize), - node("normal_intensity", "Normal Intensity", NORMAL) - .desc("Strengthens or flattens a normal map.") - .color_in("input", "Normal") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .color_out() - .cook(normal_intensity), - node("normal_to_height", "Normal to Height", NORMAL) - .desc("Reconstructs a height map from a normal map.") - .color_in("input", "Normal") - .float("intensity", "Height scale", 1.0, 0.0, 10.0) - .gray_out() - .cook(normal_to_height), - // ---- Tiling - node("make_it_tile", "Make It Tile", TILING) - .desc("Cross-fades the borders so a photo tiles.") - .any_in("input", "Input") - .float("blend", "Blend width", 0.25, 0.0, 0.5) - .cook(make_it_tile), - node("safe_transform", "Safe Transform", TILING) - .desc("Tiling-safe transform: whole-number tiling, offsets and 90° rotations.") - .any_in("input", "Input") - .int("tile", "Tile", 1, 1, 64) - .float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0) - .choice("rotation", "Rotation", &["0°", "90°", "180°", "270°"], 0) - .boolean("flip", "Flip", false) - .cook(safe_transform), - // ---- Transforms - node("mirror", "Mirror", TRANSFORMS) - .desc("Mirrors one half of the image onto the other.") - .any_in("input", "Input") - .choice("axis", "Mirror type", &["Horizontal", "Vertical", "Corner"], 0) - .boolean("flip", "Flip side", false) - .cook(mirror), - node("kaleidoscope", "Kaleidoscope", TRANSFORMS) - .desc("Repeats a wedge of the image around the center.") - .any_in("input", "Input") - .int("segments", "Segments", 6, 2, 64) - .angle("angle", "Angle", 0.0) - .cook(kaleidoscope), - node("cartesian_to_polar", "Cartesian to Polar", TRANSFORMS) - .desc("Wraps the image around the center.") - .any_in("input", "Input") - .cook(cartesian_to_polar), - node("polar_to_cartesian", "Polar to Cartesian", TRANSFORMS) - .desc("Unwraps a circular image into bands.") - .any_in("input", "Input") - .cook(polar_to_cartesian), - node("skew", "Skew", TRANSFORMS) - .desc("Shears the image.") - .any_in("input", "Input") - .float("amount", "Amount", 0.25, -2.0, 2.0) - .boolean("vertical", "Vertical", false) - .cook(skew), - ] -} - -fn src(ctx: &Ctx) -> Image { - ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0]) -} - -fn per_value(ctx: &Ctx, f: impl Fn(f32) -> f32 + Sync) -> CookResult { - let img = src(ctx); - Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) -} - -fn auto_levels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (lo, hi) = img.range(); - let span = (hi - lo).max(1e-6); - per_value(ctx, |v| (v - lo) / span) -} - -fn clamp(ctx: &Ctx) -> CookResult { - let (a, b) = (ctx.f("min"), ctx.f("max")); - per_value(ctx, |v| v.max(a).min(b.max(a))) -} - -fn color_to_mask(ctx: &Ctx) -> CookResult { - let img = src(ctx).to_color(); - let (k, r, s) = (ctx.v4("color"), ctx.f("range"), ctx.f("softness").max(1e-4)); - Ok(vec![img.map(Kind::Gray, |p| { - let d = ((p[0] - k[0]).powi(2) + (p[1] - k[1]).powi(2) + (p[2] - k[2]).powi(2)).sqrt(); - [(1.0 - (d - r) / s).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn contrast_luminosity(ctx: &Ctx) -> CookResult { - let (c, l) = (ctx.f("contrast"), ctx.f("luminosity")); - let k = if c >= 0.0 { 1.0 / (1.0 - c * 0.99) } else { 1.0 + c }; - per_value(ctx, |v| ((v - 0.5) * k + 0.5 + l).clamp(0.0, 1.0)) -} - -fn exposure(ctx: &Ctx) -> CookResult { - // Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite. - let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0)); - per_value(ctx, |v| v * k) -} - -fn gamma(ctx: &Ctx) -> CookResult { - let g = ctx.f("gamma").max(0.01); - per_value(ctx, |v| v.max(0.0).powf(1.0 / g)) -} - -fn histogram_range(ctx: &Ctx) -> CookResult { - let (r, p) = (ctx.f("range"), ctx.f("position")); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |c| [(p + (c[0] - 0.5) * r).clamp(0.0, 1.0), 0.0, 0.0, 0.0])]) -} - -/// The Histogram Scan mapping. -pub fn histogram_scan_fn(v: f32, position: f32, contrast: f32) -> f32 { - let width = (1.0 - contrast).max(0.001); - let lo = position * (1.0 + width) - width; - levels_fn(v, lo, 0.5, lo + width, 0.0, 1.0) -} - -fn histogram_scan(ctx: &Ctx) -> CookResult { - let p = if ctx.b("invert") { 1.0 - ctx.f("position") } else { ctx.f("position") }; - let c = ctx.f("contrast"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |v| [histogram_scan_fn(v[0], 1.0 - p, c), 0.0, 0.0, 0.0])]) -} - -fn histogram_shift(ctx: &Ctx) -> CookResult { - let p = ctx.f("position"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |v| [(v[0] + p).rem_euclid(1.0), 0.0, 0.0, 0.0])]) -} - -fn invert(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let a = ctx.b("alpha"); - Ok(vec![img.map(img.kind, |p| [1.0 - p[0], 1.0 - p[1], 1.0 - p[2], if a { 1.0 - p[3] } else { p[3] }])]) -} - -fn posterize(ctx: &Ctx) -> CookResult { - let n = (ctx.i("steps").max(2) - 1) as f32; - per_value(ctx, |v| (v * n).round() / n) -} - -fn replace_color(ctx: &Ctx) -> CookResult { - let img = src(ctx).to_color(); - let (s, t, r) = (ctx.v4("source"), ctx.v4("target"), ctx.f("range").max(1e-4)); - Ok(vec![img.map(Kind::Color, |p| { - let d = ((p[0] - s[0]).powi(2) + (p[1] - s[1]).powi(2) + (p[2] - s[2]).powi(2)).sqrt(); - let w = (1.0 - d / r).clamp(0.0, 1.0); - [p[0] + (t[0] - s[0]) * w, p[1] + (t[1] - s[1]) * w, p[2] + (t[2] - s[2]) * w, p[3]] - })]) -} - -fn threshold(ctx: &Ctx) -> CookResult { - let t = ctx.f("threshold"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |v| [if v[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])]) -} - -fn colorize(ctx: &Ctx) -> CookResult { - let (a, b) = (ctx.v4("dark"), ctx.v4("light")); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Color, |v| { - let t = v[0]; - [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, 1.0] - })]) -} - -fn channel_mixer(ctx: &Ctx) -> CookResult { - let img = src(ctx).to_color(); - let (r, g, b) = (ctx.v2("red_rg"), ctx.v2("green_rg"), ctx.v2("blue_rg")); - let (rb, gb, bb) = (ctx.f("red_b"), ctx.f("green_b"), ctx.f("blue_b")); - Ok(vec![ - img.map(Kind::Color, |p| [r[0] * p[0] + r[1] * p[1] + rb * p[2], g[0] * p[0] + g[1] * p[1] + gb * p[2], b[0] * p[0] + b[1] * p[1] + bb * p[2], p[3]]), - ]) -} - -fn height_blend(ctx: &Ctx) -> CookResult { - let (top, bot) = (ctx.gray_or(0, 0.0), ctx.gray_or(1, 0.0)); - let mask = ctx.sized(2).map(|m| m.to_gray()); - let (off, c) = (ctx.f("offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999)); - let soft = (1.0 - c) * 0.5 + 1e-4; - let n = (ctx.w * ctx.h) as usize; - let mut h = vec![0.0; n]; - let mut m = vec![0.0; n]; - for i in 0..n { - let (t, b) = (top.data[i] + off, bot.data[i]); - let mut k = ((t - b) / soft * 0.5 + 0.5).clamp(0.0, 1.0); - if let Some(mm) = &mask { - k *= mm.data[i]; - } - h[i] = b + (t - b) * k; - m[i] = k; - } - Ok(vec![ops::gray_from(ctx.w, ctx.h, h), ops::gray_from(ctx.w, ctx.h, m)]) -} - -fn alpha_merge(ctx: &Ctx) -> CookResult { - let c = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - let a = ctx.gray_or(1, 1.0); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let p = c.get(x as i64, y as i64, false); - [p[0], p[1], p[2], a.get_gray(x as i64, y as i64, false)] - })]) -} - -fn rgba_merge(ctx: &Ctx) -> CookResult { - let ch: Vec<Image> = (0..4).map(|i| ctx.gray_or(i, if i == 3 { 1.0 } else { 0.0 })).collect(); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let i = (y * ctx.w + x) as usize; - [ch[0].data[i], ch[1].data[i], ch[2].data[i], ch[3].data[i]] - })]) -} - -fn rgba_split(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); - Ok((0..4).map(|k| img.map(Kind::Gray, |p| [p[k], 0.0, 0.0, 0.0])).collect()) -} - -fn switch(ctx: &Ctx) -> CookResult { - let i = usize::from(ctx.b("use_b")); - Ok(vec![ctx.sized(i).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))]) -} - -fn anisotropic_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let s = ctx.f("intensity") * ctx.w as f32 / 512.0; - let an = ctx.f("anisotropy"); - let a = ctx.f("angle") * TAU; - // Blur in a rotated frame: rotate, blur x/y separately, rotate back. - let (sx, sy) = (s, s * (1.0 - an)); - if a.abs() < 1e-4 { - return Ok(vec![blur_xy(&img, sx, sy, ctx.tile)]); - } - let rotated = - Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, [0.0, 0.0], [1.0, 1.0], a / TAU, false, true).unwrap_or([0.0; 4])); - let b = blur_xy(&rotated, sx, sy, true); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))]) -} - -fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { - if !sx.is_finite() || !sy.is_finite() { - return img.clone(); - } - // Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so - // blur fully with the smaller sigma and add the extra along x. - let cap = img.w.max(img.h) as f32; - let (sx, sy) = (sx.min(cap), sy.min(cap)); - let base = ops::gaussian(img, sy, tile); - let extra = (sx * sx - sy * sy).max(0.0).sqrt(); - if extra < 0.1 { - return base; - } - // Independent Gaussians compose in quadrature, so one horizontal Gaussian of sigma `extra` - // finishes the job (box passes: O(1) per pixel, sigma clamped to the image size). - ops::gaussian_h(&base, extra, tile) -} - -fn non_uniform_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let map = ctx.gray_or(1, 1.0); - let s = ctx.f("intensity") * ctx.w as f32 / 512.0; - // Four blur levels, blended by the map. - let levels: Vec<Image> = (0..4).map(|i| ops::gaussian(&img, s * i as f32 / 3.0, ctx.tile)).collect(); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let t = map.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0) * 3.0; - let i = (t.floor() as usize).min(2); - let f = t - i as f32; - let (a, b) = (levels[i].get(x as i64, y as i64, false), levels[i + 1].get(x as i64, y as i64, false)); - [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] - })]) -} - -fn radial_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (k, c) = (ctx.f("intensity"), ctx.v2("center")); - let n = 24; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let mut acc = [0.0; 4]; - for i in 0..n { - let t = 1.0 - k * i as f32 / n as f32; - let p = img.sample(c[0] + (u - c[0]) * t, c[1] + (v - c[1]) * t, ctx.tile); - for j in 0..4 { - acc[j] += p[j] / n as f32; - } - } - acc - })]) -} - -fn slope_blur(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let slope = ops::gaussian(&ctx.gray_or(1, 0.5), 1.0, ctx.tile); - let k = ctx.f("intensity") / 256.0; - let n = ctx.i("samples").clamp(1, 64); - let mode = ctx.i("mode"); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (mut pu, mut pv) = (u, v); - let mut acc = img.sample(u, v, ctx.tile); - let mut cnt = 1.0; - for _ in 0..n { - let (x, y) = ((pu * ctx.w as f32) as i64, (pv * ctx.h as f32) as i64); - let (dx, dy) = ops::slope(&slope, x, y, ctx.tile); - let l = (dx * dx + dy * dy).sqrt().max(1e-6); - pu -= dx / l * k / n as f32 * 4.0; - pv -= dy / l * k / n as f32 * 4.0; - let p = img.sample(pu, pv, ctx.tile); - for j in 0..4 { - acc[j] = match mode { - 1 => acc[j].min(p[j]), - 2 => acc[j].max(p[j]), - _ => acc[j] + p[j], - }; - } - cnt += 1.0; - } - if mode == 0 { acc.map(|a| a / cnt) } else { acc } - })]) -} - -fn ambient_occlusion(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let spread = ctx.f("spread").max(0.001) * ctx.w as f32 * 0.25; - let depth = ctx.f("intensity"); - let wide = ops::gaussian(&h, spread, ctx.tile); - let mid = ops::gaussian(&h, spread * 0.35, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let i = (y * ctx.w + x) as usize; - let occ = ((wide.data[i] - h.data[i]).max(0.0) * 0.6 + (mid.data[i] - h.data[i]).max(0.0) * 0.4) * depth * 6.0; - [(1.0 - occ).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn bevel(ctx: &Ctx) -> CookResult { - let m = ctx.gray_or(0, 0.0); - let d = ctx.f("distance"); - let dist_px = (d.abs() * ctx.w as f32).max(1e-3); - let data = m.data.clone(); - let outside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile); - let inside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile); - let v: Vec<f32> = (0..outside.len()) - .map(|i| { - if d >= 0.0 { - // Inner bevel: ramp up from the edge inward. - if data[i] > 0.5 { (inside[i].sqrt() / dist_px).min(1.0) } else { 0.0 } - } else if data[i] > 0.5 { - 1.0 - } else { - (1.0 - outside[i].sqrt() / dist_px).max(0.0) - } - }) - .collect(); - let img = ops::gray_from(ctx.w, ctx.h, v); - let s = ctx.f("smoothing") * ctx.w as f32 / 128.0; - Ok(vec![ops::gaussian(&img.map(Kind::Gray, |p| [(p[0] * std::f32::consts::FRAC_PI_2).sin(), 0.0, 0.0, 0.0]), s, ctx.tile)]) -} - -fn curvature(ctx: &Ctx) -> CookResult { - let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color(); - let k = ctx.f("intensity") * 2.0; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let (x, y) = (x as i64, y as i64); - let dx = n.get(x + 1, y, ctx.tile)[0] - n.get(x - 1, y, ctx.tile)[0]; - let dy = n.get(x, y + 1, ctx.tile)[1] - n.get(x, y - 1, ctx.tile)[1]; - [(0.5 + (dx - dy) * k).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn morph(ctx: &Ctx, max: bool) -> CookResult { - let img = src(ctx); - let r = ctx.i("radius").clamp(0, 64) as i64; - if r == 0 { - return Ok(vec![img]); - } - // Separable square window: rows then columns. - let pass = |src: &Image, horizontal: bool| { - Image::generate(src.w, src.h, src.kind, |x, y| { - let mut acc = src.get(x as i64, y as i64, ctx.tile); - for o in -r..=r { - let p = if horizontal { src.get(x as i64 + o, y as i64, ctx.tile) } else { src.get(x as i64, y as i64 + o, ctx.tile) }; - for k in 0..4 { - acc[k] = if max { acc[k].max(p[k]) } else { acc[k].min(p[k]) }; - } - } - acc - }) - }; - Ok(vec![pass(&pass(&img, true), false)]) -} - -fn dilation(ctx: &Ctx) -> CookResult { - morph(ctx, true) -} - -fn erosion(ctx: &Ctx) -> CookResult { - morph(ctx, false) -} - -fn edge_detect(ctx: &Ctx) -> CookResult { - let m = ctx.gray_or(0, 0.0); - let w = (ctx.f("width") * ctx.w as f32 / 256.0).max(0.5); - let data = m.data.clone(); - let a = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile); - let b = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile); - let round = ctx.f("roundness"); - let v: Vec<f32> = a - .iter() - .zip(&b) - .map(|(a, b)| { - let d = a.sqrt().max(b.sqrt()); - let t = (1.0 - d / w).max(0.0); - // A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2. - t.powf((1.0 - round * 0.8).max(0.01)) - }) - .collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn glow(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (t, amt) = (ctx.f("threshold"), ctx.f("amount")); - let bright = img.map(img.kind, |p| { - let l = luminance(p); - let k = if l > t { 1.0 } else { 0.0 }; - [p[0] * k, p[1] * k, p[2] * k, p[3]] - }); - let b = ops::gaussian(&bright, ctx.f("size") * ctx.w as f32 / 256.0, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (p, g) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - [p[0] + g[0] * amt, p[1] + g[1] * amt, p[2] + g[2] * amt, p[3]] - })]) -} - -fn highpass(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let b = ops::gaussian(&img, ctx.f("radius") * ctx.w as f32 / 256.0, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (p, q) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - [p[0] - q[0] + 0.5, p[1] - q[1] + 0.5, p[2] - q[2] + 0.5, p[3]] - })]) -} - -fn mosaic(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let n = ctx.i("cells").max(1) as f32; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| img.sample(((u * n).floor() + 0.5) / n, ((v * n).floor() + 0.5) / n, ctx.tile))]) -} - -fn swirl(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (amt, rad) = (ctx.f("amount") * TAU, ctx.f("radius").max(1e-3)); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = (u - 0.5, v - 0.5); - let r = (x * x + y * y).sqrt(); - let t = (1.0 - r / rad).max(0.0); - let a = amt * t * t; - let (s, c) = a.sin_cos(); - img.sample(x * c - y * s + 0.5, x * s + y * c + 0.5, ctx.tile) - })]) -} - -fn vignette(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (amt, soft) = (ctx.f("amount"), ctx.f("softness").max(0.01)); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let p = img.sample_nearest(u, v, false); - let r = ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() * std::f32::consts::SQRT_2; - let k = 1.0 - amt * ((r - (1.0 - soft)) / soft).clamp(0.0, 1.0); - [p[0] * k, p[1] * k, p[2] * k, p[3]] - })]) -} - -fn quantize(ctx: &Ctx) -> CookResult { - let n = (ctx.i("steps").max(2) - 1) as f32; - let s = ctx.f("smoothness").clamp(0.0, 1.0) * 0.5; - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |p| { - let x = p[0] * n; - let f = x.fract(); - let t = if s > 0.0 { ((f - 0.5 + s) / (2.0 * s)).clamp(0.0, 1.0) } else { (f >= 0.5) as i32 as f32 }; - [(x.floor() + t * t * (3.0 - 2.0 * t)) / n, 0.0, 0.0, 0.0] - })]) -} - -fn height_normal(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - Ok(vec![height_to_normal(&h, ctx.f("intensity") * ctx.w as f32 / 32.0, ctx.i("format") == 1, ctx.tile, false)]) -} - -fn unpack(p: [f32; 4]) -> [f32; 3] { - [p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0] -} - -fn pack(n: [f32; 3], a: f32) -> [f32; 4] { - let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6); - [n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a] -} - -fn flat_normal(ctx: &Ctx, i: usize) -> Image { - ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color() -} - -fn normal_blend(ctx: &Ctx) -> CookResult { - let (base, det) = (flat_normal(ctx, 0), flat_normal(ctx, 1)); - let mask = ctx.sized(2).map(|m| m.to_gray()); - let op = ctx.f("opacity"); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (x, y) = (x as i64, y as i64); - let k = op * mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); - let b = unpack(base.get(x, y, false)); - let mut d = unpack(det.get(x, y, false)); - d = [d[0] * k, d[1] * k, 1.0 + (d[2] - 1.0) * k]; - // Reoriented normal mapping (Barré-Brisebois & Hill). - let t = [b[0], b[1], b[2] + 1.0]; - let u = [-d[0], -d[1], d[2]]; - // A base normal pointing straight away (z = -1) has no reorientation; keep it. - if t[2].abs() < 1e-4 { - return pack(b, 1.0); - } - let dot = t[0] * u[0] + t[1] * u[1] + t[2] * u[2]; - let r = [t[0] * dot / t[2] - u[0], t[1] * dot / t[2] - u[1], t[2] * dot / t[2] - u[2]]; - pack(r, 1.0) - })]) -} - -fn normal_invert(ctx: &Ctx) -> CookResult { - let n = flat_normal(ctx, 0); - let (r, g) = (ctx.b("red"), ctx.b("green")); - Ok(vec![n.map(Kind::Color, |p| [if r { 1.0 - p[0] } else { p[0] }, if g { 1.0 - p[1] } else { p[1] }, p[2], p[3]])]) -} - -fn normal_normalize(ctx: &Ctx) -> CookResult { - let n = flat_normal(ctx, 0); - Ok(vec![n.map(Kind::Color, |p| pack(unpack(p), p[3]))]) -} - -fn normal_intensity(ctx: &Ctx) -> CookResult { - let n = flat_normal(ctx, 0); - let k = ctx.f("intensity"); - Ok(vec![n.map(Kind::Color, |p| { - let v = unpack(p); - pack([v[0] * k, v[1] * k, v[2].max(1e-3)], p[3]) - })]) -} - -fn normal_to_height(ctx: &Ctx) -> CookResult { - // Integrate the slopes at several scales (a multigrid-style Poisson solve: coarse levels set - // the broad shape, finer ones the detail). - let n = flat_normal(ctx, 0); - let (w, h) = (ctx.w, ctx.h); - let gx = n.map(Kind::Gray, |p| { - let v = unpack(p); - [-v[0] / v[2].max(0.1), 0.0, 0.0, 0.0] - }); - let gy = n.map(Kind::Gray, |p| { - let v = unpack(p); - [v[1] / v[2].max(0.1), 0.0, 0.0, 0.0] - }); - let mut height = Image::filled(8.min(w), 8.min(h), Kind::Gray, [0.0; 4]); - let mut size = 8u32; - loop { - let (sw, sh) = (size.min(w), size.min(h)); - let (gxs, gys) = (gx.resize(sw, sh, true), gy.resize(sw, sh, true)); - let scale = w as f32 / sw as f32; - let mut cur = height.resize(sw, sh, true); - for _ in 0..40 { - let prev = cur.clone(); - cur = Image::generate(sw, sh, Kind::Gray, |x, y| { - let (x, y) = (x as i64, y as i64); - let nb = prev.get(x - 1, y, true)[0] + prev.get(x + 1, y, true)[0] + prev.get(x, y - 1, true)[0] + prev.get(x, y + 1, true)[0]; - // Divergence of the slope field in pixels of this level: the slopes are per - // full-size pixel and one pixel here spans `scale` of them, so multiply. - let div = (gxs.get(x + 1, y, true)[0] - gxs.get(x - 1, y, true)[0] + gys.get(x, y + 1, true)[0] - gys.get(x, y - 1, true)[0]) * 0.5 * scale; - [(nb - div) * 0.25, 0.0, 0.0, 0.0] - }); - } - height = cur; - if sw >= w && sh >= h { - break; - } - size *= 2; - } - let (lo, hi) = height.range(); - let k = ctx.f("intensity"); - let span = (hi - lo).max(1e-6); - Ok(vec![height.map(Kind::Gray, |p| [(((p[0] - lo) / span - 0.5) * k + 0.5).clamp(0.0, 1.0), 0.0, 0.0, 0.0])]) -} - -fn make_it_tile(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let b = ctx.f("blend").clamp(0.01, 0.5); - // Blend the image with a half-offset copy near the borders. - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let p = img.sample(u, v, true); - let q = img.sample(u + 0.5, v + 0.5, true); - let edge = (u.min(1.0 - u)).min(v.min(1.0 - v)); - let t = (edge / b).clamp(0.0, 1.0); - let t = t * t * (3.0 - 2.0 * t); - [q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t, q[2] + (p[2] - q[2]) * t, q[3] + (p[3] - q[3]) * t] - })]) -} - -fn safe_transform(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let n = ctx.i("tile").max(1) as f32; - let off = ctx.v2("offset"); - let (rot, flip) = (ctx.i("rotation"), ctx.b("flip")); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (mut x, mut y) = ((u * n - off[0]).rem_euclid(1.0), (v * n - off[1]).rem_euclid(1.0)); - for _ in 0..rot.rem_euclid(4) { - (x, y) = (y, 1.0 - x); - } - if flip { - x = 1.0 - x; - } - img.sample(x, y, true) - })]) -} - -fn mirror(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (axis, flip) = (ctx.i("axis"), ctx.b("flip")); - let m = |t: f32| { - if flip { - if t < 0.5 { 1.0 - t } else { t } - } else if t > 0.5 { - 1.0 - t - } else { - t - } - }; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| match axis { - 1 => img.sample(u, m(v), ctx.tile), - 2 => img.sample(m(u), m(v), ctx.tile), - _ => img.sample(m(u), v, ctx.tile), - })]) -} - -fn kaleidoscope(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let seg = TAU / ctx.i("segments").clamp(2, 64) as f32; - let a0 = ctx.f("angle") * TAU; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = (u - 0.5, v - 0.5); - let r = (x * x + y * y).sqrt(); - let mut a = (y.atan2(x) - a0).rem_euclid(seg); - if a > seg * 0.5 { - a = seg - a; - } - let a = a + a0; - img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile) - })]) -} - -fn cartesian_to_polar(ctx: &Ctx) -> CookResult { - let img = src(ctx); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (x, y) = (u - 0.5, v - 0.5); - let r = (x * x + y * y).sqrt() * 2.0; - let a = (y.atan2(x) / TAU).rem_euclid(1.0); - img.sample(a, r, true) - })]) -} - -fn polar_to_cartesian(ctx: &Ctx) -> CookResult { - let img = src(ctx); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (a, r) = (u * TAU, v * 0.5); - img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile) - })]) -} - -fn skew(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (k, vert) = (ctx.f("amount"), ctx.b("vertical")); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - if vert { img.sample(u, v + (u - 0.5) * k, ctx.tile) } else { img.sample(u + (v - 0.5) * k, v, ctx.tile) } - })]) -} diff --git a/_to_delete/nodes_filters.test.rs b/_to_delete/nodes_filters.test.rs deleted file mode 100644 index a3cf032..0000000 --- a/_to_delete/nodes_filters.test.rs +++ /dev/null @@ -1,103 +0,0 @@ -#[cfg(test)] -mod normal_blend_tests { - use std::collections::BTreeMap; - - use materialcraft_image::{Image, Kind}; - - use crate::catalog::Ctx; - use crate::catalog::{find, resolve_params}; - - /// A base normal pointing straight away from the viewer (blue = 0) used to divide by zero. - #[test] - fn normal_blend_with_a_black_base_stays_finite() { - let def = find("normal_blend").expect("normal_blend exists"); - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let black = Image::filled(8, 8, Kind::Color, [0.0, 0.0, 0.0, 1.0]); - let bump = Image::filled(8, 8, Kind::Color, [0.7, 0.4, 0.6, 1.0]); - let inputs = vec![Some(black), Some(bump), None]; - let ctx = Ctx { w: 8, h: 8, seed: 1, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - let out = (def.cook)(&ctx).expect("cooks"); - assert!(out[0].data.iter().all(|v| v.is_finite()), "NaN or Inf in the blended normal"); - } -} - -// Tests for the blur helpers. - -use materialcraft_image::{Image, Kind}; - -use super::blur_xy; - -fn noise(n: u32) -> Image { - Image::generate(n, n, Kind::Gray, |x, y| [((x * 7 + y * 13) % 17) as f32 / 16.0, 0.0, 0.0, 1.0]) -} - -#[test] -fn blur_xy_huge_sigma_is_bounded_and_finite() { - let t = std::time::Instant::now(); - let out = blur_xy(&noise(64), 1e14, 1.0, true); - assert!(out.data.iter().all(|v| v.is_finite())); - assert!(t.elapsed().as_secs() < 20, "took {:?}", t.elapsed()); -} - -#[test] -fn blur_xy_horizontal_blur_is_stronger_than_vertical() { - // Vertical stripes survive a vertical-only blur but are smoothed by a horizontal one. - let img = Image::generate(64, 64, Kind::Gray, |x, _| [(x % 2) as f32, 0.0, 0.0, 1.0]); - let out = blur_xy(&img, 6.0, 0.0, true); - let range = out.data.chunks(1).map(|v| v[0]).fold((f32::MAX, f32::MIN), |a, v| (a.0.min(v), a.1.max(v))); - assert!(range.1 - range.0 < 0.1, "stripes should be blurred away: {range:?}"); - let mean: f32 = out.data.iter().sum::<f32>() / out.data.len() as f32; - assert!((mean - 0.5).abs() < 0.02); -} - -mod height_roundtrip { - //! Round-trip test for Height to Normal -> Normal to Height on a smooth analytic bump. - - use std::collections::BTreeMap; - - use materialcraft_core::Value; - use materialcraft_image::{Image, Kind}; - - use crate::{Ctx, find, resolve_params}; - - fn run(id: &str, input: &Image, size: u32, over: &[(&str, Value)]) -> Image { - let def = find(id).unwrap(); - let over: BTreeMap<String, Value> = over.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(); - let params = resolve_params(def, &over); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = [Some(input.clone())]; - let ctx = Ctx { w: size, h: size, seed: 1, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap().remove(0) - } - - fn pearson(a: &Image, b: &Image) -> f32 { - let n = (a.w * a.h) as usize; - let (ma, mb) = (a.data.iter().take(n).sum::<f32>() / n as f32, b.data.iter().take(n).sum::<f32>() / n as f32); - let (mut sab, mut saa, mut sbb) = (0.0f32, 0.0f32, 0.0f32); - for i in 0..n { - let (da, db) = (a.data[i] - ma, b.data[i] - mb); - sab += da * db; - saa += da * da; - sbb += db * db; - } - sab / (saa * sbb).sqrt().max(1e-9) - } - - #[test] - fn normal_to_height_recovers_the_broad_shape_of_a_bump() { - for size in [256u32, 1024] { - // A wide wrap-around Gaussian bump: nearly all of its energy is at coarse scales. - let bump = Image::generate_uv(size, size, Kind::Gray, |u, v| { - let (dx, dy) = (u - 0.5, v - 0.5); - [(-(dx * dx + dy * dy) / (2.0 * 0.12 * 0.12)).exp(), 0.0, 0.0, 0.0] - }); - let normal = run("height_to_normal", &bump, size, &[("intensity", Value::Float(2.0))]); - let back = run("normal_to_height", &normal, size, &[]); - let c = pearson(&bump, &back); - assert!(c > 0.99, "size {size}: correlation {c}"); - } - } -} diff --git a/_to_delete/nodes_filters_extra.rs b/_to_delete/nodes_filters_extra.rs deleted file mode 100644 index 4d1de25..0000000 --- a/_to_delete/nodes_filters_extra.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! More filters: random per-tile transforms, horizon-based ambient occlusion, a 5×5 Sobel normal -//! map, value band selection, palette quantization and block-averaged pixelation. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind, luminance}; -use rayon::prelude::*; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::filters_more::pack; -use crate::noise::rand2; -use crate::noises_more::smoothstep; - -const ADJ: &str = "Filters/Adjustments"; -const EFFECTS: &str = "Filters/Effects"; -const NORMAL: &str = "Filters/Normal map"; -const TILING: &str = "Filters/Tiling"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("tile_random", "Tile Random", TILING) - .desc("Cuts the image into a grid and shows a randomly offset, flipped and rotated window of the input in each tile (breaks up repetition).") - .any_in("input", "Input") - .int("x_amount", "X amount", 4, 1, 256) - .int("y_amount", "Y amount", 4, 1, 256) - .float("offset_random", "Offset random", 1.0, 0.0, 1.0) - .boolean("rotate", "Random 90° rotation", true) - .boolean("flip", "Random flip", true) - .float("luminance_random", "Luminance random", 0.0, 0.0, 1.0) - .cook(tile_random), - node("ambient_occlusion_fast", "Ambient Occlusion (Fast)", EFFECTS) - .desc("Horizon-based ambient occlusion of a height map: how much of the sky each pixel sees within the radius.") - .gray_in("height", "Height") - .float("radius", "Radius", 12.0, 1.0, 128.0) - .float("height_depth", "Height depth", 0.3, 0.0, 1.0) - .float("intensity", "Intensity", 1.0, 0.0, 2.0) - .gray_out() - .cook(ambient_occlusion_fast), - node("normal_from_height_hq", "Normal from Height HQ", NORMAL) - .desc("A smooth normal map from a height map with 5×5 Sobel slopes.") - .gray_in("input", "Height") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) - .color_out() - .cook(normal_from_height_hq), - node("histogram_select", "Histogram Select", ADJ) - .desc("White where values lie in a band around the position, fading out with the contrast.") - .gray_in("input", "Input") - .float("position", "Position", 0.5, 0.0, 1.0) - .float("range", "Range", 0.25, 0.0, 1.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(histogram_select), - node("quantize_color", "Quantize Color", ADJ) - .desc("Reduces the image to a palette of its most representative colors (k-means), with optional ordered dithering.") - .color_in("input", "Input") - .int("colors", "Colors", 8, 2, 64) - .float("dither", "Dither", 0.0, 0.0, 1.0) - .color_out() - .cook(quantize_color), - node("pixelate_color", "Pixelate Color", EFFECTS) - .desc("Averages the image over blocks (separate X and Y counts).") - .any_in("input", "Input") - .int("x_cells", "X cells", 32, 1, 1024) - .int("y_cells", "Y cells", 32, 1, 1024) - .cook(pixelate_color), - ] -} - -fn tile_random(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); - let (nx, ny) = (ctx.i("x_amount").clamp(1, 256) as f32, ctx.i("y_amount").clamp(1, 256) as f32); - let (off, rot, flip, lr, s) = (ctx.f("offset_random"), ctx.b("rotate"), ctx.b("flip"), ctx.f("luminance_random"), ctx.seed); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { - let (cx, cy) = ((u * nx).floor(), (v * ny).floor()); - let (ci, cj) = ((cx as i32).rem_euclid(nx as i32), (cy as i32).rem_euclid(ny as i32)); - let r = |k: u32| rand2(ci, cj, s ^ k.wrapping_mul(0x2545_f491)); - // Offset from the tile center in uv, flipped and turned by quarter turns. - let (mut a, mut b) = ((u * nx - cx - 0.5) / nx, (v * ny - cy - 0.5) / ny); - if flip && r(1) < 0.5 { - a = -a; - } - if rot { - for _ in 0..(r(2) * 4.0) as i32 { - (a, b) = (-b, a); - } - } - let su = (cx + 0.5) / nx + a + (r(3) - 0.5) * off; - let sv = (cy + 0.5) / ny + b + (r(4) - 0.5) * off; - let p = img.sample(su, sv, true); - let k = 1.0 - lr * r(5); - [p[0] * k, p[1] * k, p[2] * k, p[3]] - })]) -} - -fn ambient_occlusion_fast(ctx: &Ctx) -> CookResult { - const DIRS: usize = 8; - const STEPS: usize = 6; - let h = ctx.gray_or(0, 0.0); - let scale = ctx.w as f32 / 256.0; - let rad = (ctx.f("radius") * scale).clamp(1.0, 1024.0); - let hs = ctx.f("height_depth") * 64.0 * scale; - let k = ctx.f("intensity"); - // Integer offsets along each direction, denser near the pixel, and their true distances. - let taps: Vec<(i64, i64, f32)> = (0..DIRS) - .flat_map(|d| { - let (sn, cs) = ((d as f32 + 0.5) / DIRS as f32 * TAU).sin_cos(); - (1..=STEPS).map(move |s| { - let dist = rad * (s as f32 / STEPS as f32).powf(1.5); - let (ox, oy) = ((cs * dist).round(), (sn * dist).round()); - (ox as i64, oy as i64, (ox * ox + oy * oy).sqrt().max(1.0)) - }) - }) - .collect(); - let tile = ctx.tile; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let (x, y) = (x as i64, y as i64); - let h0 = h.get_gray(x, y, tile); - let occ: f32 = taps - .chunks(STEPS) - .map(|dir| { - // Tangent of the highest horizon in this direction, as the sine of its angle. - let m = dir.iter().fold(0.0f32, |m, &(ox, oy, d)| m.max((h.get_gray(x + ox, y + oy, tile) - h0) * hs / d)); - m / (1.0 + m * m).sqrt() - }) - .sum(); - [(1.0 - k * occ / DIRS as f32).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn normal_from_height_hq(ctx: &Ctx) -> CookResult { - const SMOOTH: [f32; 5] = [1.0, 4.0, 6.0, 4.0, 1.0]; - const DERIV: [f32; 5] = [-1.0, -2.0, 0.0, 2.0, 1.0]; - let h = ctx.gray_or(0, 0.0); - // The kernels sum to 128 × the slope of a linear ramp. - let k = ctx.f("intensity") * ctx.w as f32 / 32.0 / 128.0; - let dx_fmt = ctx.i("format") == 1; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (mut gx, mut gy) = (0.0, 0.0); - for j in 0..5 { - for i in 0..5 { - let v = h.get_gray(x as i64 + i as i64 - 2, y as i64 + j as i64 - 2, ctx.tile); - gx += SMOOTH[j] * DERIV[i] * v; - gy += DERIV[j] * SMOOTH[i] * v; - } - } - let ny = gy * k; - pack([-gx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0) - })]) -} - -fn histogram_select(ctx: &Ctx) -> CookResult { - let (pos, half) = (ctx.f("position"), ctx.f("range") * 0.5); - let soft = (1.0 - ctx.f("contrast").clamp(0.0, 1.0)) * 0.25 + 1e-3; - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |p| [1.0 - smoothstep(half, half + soft, (p[0] - pos).abs()), 0.0, 0.0, 0.0])]) -} - -/// Index of the color in `pal` nearest to `c`. -fn nearest(pal: &[[f32; 3]], c: [f32; 3]) -> usize { - let d = |p: &[f32; 3]| (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2); - pal.iter().enumerate().min_by(|a, b| d(a.1).total_cmp(&d(b.1))).map_or(0, |(i, _)| i) -} - -fn quantize_color(ctx: &Ctx) -> CookResult { - const BAYER: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0]; - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let k = ctx.i("colors").clamp(2, 64) as usize; - let rgb = |p: &[f32]| [p[0], p[1], p[2]]; - // Lloyd's k-means on up to ~4096 samples, seeded at luminance quantiles. - let step = (img.data.len() / 4 / 4096).max(1); - let mut samples: Vec<[f32; 3]> = img.data.chunks_exact(4).step_by(step).map(rgb).collect(); - samples.sort_by(|a, b| luminance([a[0], a[1], a[2], 1.0]).total_cmp(&luminance([b[0], b[1], b[2], 1.0]))); - let mut pal: Vec<[f32; 3]> = (0..k).filter_map(|j| samples.get(((j as f32 + 0.5) / k as f32 * samples.len() as f32) as usize).copied()).collect(); - for _ in 0..8 { - let mut acc = vec![[0.0f32; 4]; pal.len()]; - for s in &samples { - if let Some(a) = acc.get_mut(nearest(&pal, *s)) { - *a = [a[0] + s[0], a[1] + s[1], a[2] + s[2], a[3] + 1.0]; - } - } - for (p, a) in pal.iter_mut().zip(&acc) { - if a[3] > 0.0 { - *p = [a[0] / a[3], a[1] / a[3], a[2] / a[3]]; - } - } - } - let spread = ctx.f("dither") / (k as f32).cbrt(); - Ok(vec![Image::generate(img.w, img.h, Kind::Color, |x, y| { - let p = img.get(x as i64, y as i64, false); - let d = ((BAYER[(y as usize % 4) * 4 + x as usize % 4] + 0.5) / 16.0 - 0.5) * spread; - let c = pal.get(nearest(&pal, [p[0] + d, p[1] + d, p[2] + d])).copied().unwrap_or([p[0], p[1], p[2]]); - [c[0], c[1], c[2], p[3]] - })]) -} - -fn pixelate_color(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]); - let (w, h) = (img.w as usize, img.h as usize); - let (nx, ny) = (ctx.i("x_cells").clamp(1, 1024) as usize, ctx.i("y_cells").clamp(1, 1024) as usize); - // Block `b` of `n` over `len` pixels covers `b·len/n .. (b+1)·len/n` (at least one pixel). - let range = |n: usize, len: usize, b: usize| (b * len / n, ((b + 1) * len / n).max(b * len / n + 1).min(len)); - let block = |n: usize, len: usize, p: usize| (((p + 1) * n).saturating_sub(1) / len).min(n - 1); - let means: Vec<[f32; 4]> = (0..nx * ny) - .into_par_iter() - .map(|bi| { - let ((x0, x1), (y0, y1)) = (range(nx, w, bi % nx), range(ny, h, bi / nx)); - let mut s = [0.0f32; 4]; - for y in y0..y1 { - for x in x0..x1 { - let p = img.get(x as i64, y as i64, false); - s = std::array::from_fn(|c| s[c] + p[c]); - } - } - let n = ((x1 - x0) * (y1 - y0)).max(1) as f32; - s.map(|v| v / n) - }) - .collect(); - Ok(vec![Image::generate(img.w, img.h, img.kind, |x, y| { - means.get(block(ny, h, y as usize) * nx + block(nx, w, x as usize)).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]) - })]) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn nearest_and_block_math() { - assert_eq!(nearest(&[[0.0; 3], [1.0; 3]], [0.7; 3]), 1); - // Pixelate: a 2-cell split of a black/white image averages each half exactly. - let img = Image::gray(8, 2, |x, _| if x < 4 { 0.0 } else { 1.0 }); - let def = crate::catalog::find("pixelate_color").unwrap(); - let mut p = crate::catalog::resolve_params(def, &Default::default()); - p.insert("x_cells".into(), materialcraft_core::Value::Int(2)); - p.insert("y_cells".into(), materialcraft_core::Value::Int(1)); - let no_res = |_: &str| None; - let vars = Default::default(); - let inputs = [Some(img)]; - let ctx = Ctx { w: 8, h: 2, seed: 0, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars }; - let out = &pixelate_color(&ctx).unwrap()[0]; - assert_eq!((out.get(3, 1, false)[0], out.get(4, 0, false)[0]), (0.0, 1.0)); - } -} diff --git a/_to_delete/nodes_filters_more.rs b/_to_delete/nodes_filters_more.rs deleted file mode 100644 index 68c3941..0000000 --- a/_to_delete/nodes_filters_more.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! More filters: tone remaps and per-channel adjustments, two-input math, median and unsharp -//! mask, Sobel edges, glows and shadows from masks, curvature from height, and normal map tools. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::flood_fill::region_rand; -use crate::noise::fbm; -use crate::noises_more::smoothstep; -use crate::ops; - -const ADJ: &str = "Filters/Adjustments"; -const BLENDING: &str = "Filters/Blending"; -const BLURS: &str = "Filters/Blurs"; -const EFFECTS: &str = "Filters/Effects"; -const NORMAL: &str = "Filters/Normal map"; - -/// A tangent-space normal from a normal map pixel (0..1 → -1..1). -#[inline] -pub(crate) fn unpack(p: [f32; 4]) -> [f32; 3] { - [p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0] -} - -/// A normalized normal back to a normal map pixel. -#[inline] -pub(crate) fn pack(n: [f32; 3], a: f32) -> [f32; 4] { - let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6); - [n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a] -} - -/// The pixel offset of `dist` (pixels at 256) along `angle` (turns, y down). -fn offset(ctx: &Ctx, angle: f32, dist: f32) -> (i64, i64) { - let (s, c) = (angle * TAU).sin_cos(); - let d = dist * ctx.w as f32 / 256.0; - ((c * d).round() as i64, (-s * d).round() as i64) -} - -fn px(ctx: &Ctx, v: f32) -> f32 { - v * ctx.w as f32 / 256.0 -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let two = |id, label, desc| node(id, label, BLENDING).desc(desc).any_in("input_a", "A").any_in("input_b", "B"); - let mask_in = |id, label, cat| node(id, label, cat).gray_in("input", "Mask"); - vec![ - // ---- Adjustments - node("remap", "Remap", ADJ) - .desc("Maps the input range linearly onto the output range.") - .any_in("input", "Input") - .float("in_min", "Input min", 0.0, 0.0, 1.0) - .float("in_max", "Input max", 1.0, 0.0, 1.0) - .float("out_min", "Output min", 0.0, 0.0, 1.0) - .float("out_max", "Output max", 1.0, 0.0, 1.0) - .boolean("clamp", "Clamp", true) - .cook(remap), - node("smoothstep", "Smoothstep", ADJ) - .desc("A smooth S-shaped step from the low edge (black) to the high edge (white).") - .any_in("input", "Input") - .float("low", "Low edge", 0.25, 0.0, 1.0) - .float("high", "High edge", 0.75, 0.0, 1.0) - .cook(smoothstep_node), - node("s_curve", "S-Curve Contrast", ADJ) - .desc("Raises contrast around a pivot with a smooth S curve (keeps black and white).") - .any_in("input", "Input") - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("pivot", "Pivot", 0.5, 0.01, 0.99) - .cook(s_curve), - node("channel_levels", "Channel Levels", ADJ) - .desc("Levels with a separate input range per channel.") - .any_in("input", "Input") - .color("low", "Input low", [0.0, 0.0, 0.0, 0.0]) - .color("high", "Input high", [1.0, 1.0, 1.0, 1.0]) - .float("gamma", "Gamma", 1.0, 0.1, 4.0) - .cook(channel_levels), - node("auto_levels_channels", "Auto Levels per Channel", ADJ) - .desc("Stretches each color channel separately to the full 0..1 range.") - .any_in("input", "Input") - .cook(auto_levels_channels), - node("invert_channels", "Invert Channels", ADJ) - .desc("Inverts the chosen channels.") - .any_in("input", "Input") - .boolean("red", "Red", true) - .boolean("green", "Green", true) - .boolean("blue", "Blue", true) - .boolean("alpha", "Alpha", false) - .cook(invert_channels), - node("clamp_channels", "Clamp Channels", ADJ) - .desc("Clamps each channel between its own minimum and maximum.") - .any_in("input", "Input") - .color("min", "Min", [0.0, 0.0, 0.0, 0.0]) - .color("max", "Max", [1.0, 1.0, 1.0, 1.0]) - .cook(clamp_channels), - node("color_variation", "Color Variation", ADJ) - .desc("Random hue, saturation and value shifts: per region when a flood fill index map is connected, else from soft noise.") - .color_in("input", "Input") - .color_in("index", "Index map (optional)") - .float("hue", "Hue random", 0.03, 0.0, 0.5) - .float("saturation", "Saturation random", 0.15, 0.0, 1.0) - .float("value", "Value random", 0.2, 0.0, 1.0) - .float("scale", "Noise scale", 4.0, 1.0, 64.0) - .color_out() - .cook(color_variation), - // ---- Blending - node("lerp", "Lerp", BLENDING) - .desc("Linear interpolation from A to B by a mask (or a constant position without one).") - .any_in("input_a", "A") - .any_in("input_b", "B") - .gray_in("mask", "Mask") - .float("position", "Position (no mask)", 0.5, 0.0, 1.0) - .cook(lerp), - two("minimum", "Minimum", "The darker of A and B, per channel.").cook(minimum), - two("maximum", "Maximum", "The brighter of A and B, per channel.").cook(maximum), - two("multiply", "Multiply", "A times B.").cook(multiply), - two("difference", "Difference", "The absolute difference of A and B.").cook(difference), - two("add", "Add", "A plus B.").boolean("clamp", "Clamp", true).cook(add), - two("subtract", "Subtract", "A minus B.").boolean("clamp", "Clamp", true).cook(subtract), - // ---- Blurs - node("median", "Median", BLURS) - .desc("Median of each neighbourhood: removes specks while keeping edges.") - .any_in("input", "Input") - .choice("size", "Size", &["3 × 3", "5 × 5"], 0) - .cook(median), - node("unsharp_mask", "Unsharp Mask", BLURS) - .desc("Sharpens by adding back the difference from a blurred copy.") - .any_in("input", "Input") - .float("radius", "Radius", 2.0, 0.0, 32.0) - .float("amount", "Amount", 1.0, 0.0, 5.0) - .float("threshold", "Threshold", 0.0, 0.0, 1.0) - .cook(unsharp_mask), - // ---- Effects - node("sobel", "Sobel Edges", EFFECTS) - .desc("Edge strength from the Sobel operator.") - .gray_in("input", "Input") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .gray_out() - .cook(sobel), - mask_in("outer_glow", "Outer Glow", EFFECTS) - .desc("A glow fading outward from a mask (by exact distance).") - .float("size", "Size", 16.0, 0.0, 256.0) - .float("intensity", "Intensity", 1.0, 0.0, 1.0) - .float("falloff", "Falloff", 2.0, 0.25, 8.0) - .gray_out() - .cook(outer_glow), - mask_in("inner_shadow", "Inner Shadow", EFFECTS) - .desc("Darkens the inside of a mask along the edges facing the light.") - .angle("angle", "Light angle", -0.125) - .float("distance", "Distance", 6.0, 0.0, 64.0) - .float("size", "Size", 8.0, 0.0, 128.0) - .float("opacity", "Opacity", 0.75, 0.0, 1.0) - .gray_out() - .cook(inner_shadow), - mask_in("drop_shadow", "Drop Shadow", EFFECTS) - .desc("An offset, blurred shadow under a mask.") - .angle("angle", "Angle", -0.125) - .float("distance", "Distance", 8.0, 0.0, 128.0) - .float("size", "Blur", 4.0, 0.0, 64.0) - .float("opacity", "Opacity", 0.75, 0.0, 1.0) - .output("output", "Output", PortKind::Gray) - .output("shadow", "Shadow", PortKind::Gray) - .cook(drop_shadow), - node("height_curvature", "Curvature from Height", EFFECTS) - .desc("Convex areas above 0.5, concave below, from a height map.") - .gray_in("input", "Height") - .float("radius", "Radius", 2.0, 0.25, 32.0) - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .gray_out() - .cook(height_curvature), - mask_in("outline", "Outline", EFFECTS) - .desc("A line of constant width around the edges of a mask.") - .float("width", "Width", 4.0, 0.0, 64.0) - .choice("position", "Position", &["Outside", "Center", "Inside"], 1) - .gray_out() - .cook(outline), - // ---- Normal map - node("normal_combine", "Normal Combine", NORMAL) - .desc("Combines a detail normal map over a base one (whiteout blending).") - .color_in("base", "Base normal") - .color_in("detail", "Detail normal") - .float("intensity", "Detail intensity", 1.0, 0.0, 4.0) - .color_out() - .cook(normal_combine), - node("normal_rotate", "Normal Rotate", NORMAL) - .desc("Rotates the directions of a normal map (for rotated textures).") - .color_in("input", "Normal") - .angle("angle", "Angle", 0.0) - .color_out() - .cook(normal_rotate), - node("normal_sobel", "Normal Sobel", NORMAL) - .desc("A normal map from a height map with Sobel slopes (smoother than plain differences).") - .gray_in("input", "Height") - .float("intensity", "Intensity", 1.0, 0.0, 10.0) - .choice("format", "Format", &["OpenGL", "DirectX"], 0) - .color_out() - .cook(normal_sobel), - ] -} - -fn src(ctx: &Ctx) -> Image { - ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0]) -} - -/// Map R, G and B (gray: the value) with `f(value, channel)`; alpha kept. -fn per_channel(ctx: &Ctx, f: impl Fn(f32, usize) -> f32 + Sync) -> CookResult { - let img = src(ctx); - Ok(vec![img.map(img.kind, |p| [f(p[0], 0), f(p[1], 1), f(p[2], 2), p[3]])]) -} - -fn remap(ctx: &Ctx) -> CookResult { - let (a, b, c, d, cl) = (ctx.f("in_min"), ctx.f("in_max"), ctx.f("out_min"), ctx.f("out_max"), ctx.b("clamp")); - let span = if (b - a).abs() < 1e-6 { 1e-6 } else { b - a }; - per_channel(ctx, |v, _| { - let t = (v - a) / span; - c + (d - c) * if cl { t.clamp(0.0, 1.0) } else { t } - }) -} - -fn smoothstep_node(ctx: &Ctx) -> CookResult { - let (lo, hi) = (ctx.f("low"), ctx.f("high")); - per_channel(ctx, |v, _| smoothstep(lo, hi.max(lo + 1e-4), v)) -} - -fn s_curve(ctx: &Ctx) -> CookResult { - // A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1). - let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99)); - per_channel(ctx, |v, _| { - let v = v.clamp(0.0, 1.0); - if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) } - }) -} - -fn channel_levels(ctx: &Ctx) -> CookResult { - let (lo, hi, g) = (ctx.v4("low"), ctx.v4("high"), 1.0 / ctx.f("gamma").max(0.01)); - per_channel(ctx, |v, c| { - let span = (hi[c] - lo[c]).abs().max(1e-6).copysign(hi[c] - lo[c]); - ((v - lo[c]) / span).clamp(0.0, 1.0).powf(g) - }) -} - -fn auto_levels_channels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let c = img.channels(); - let mut lo = [f32::INFINITY; 3]; - let mut hi = [f32::NEG_INFINITY; 3]; - for p in img.data.chunks(c) { - for k in 0..c.min(3) { - lo[k] = lo[k].min(p[k]); - hi[k] = hi[k].max(p[k]); - } - } - per_channel(ctx, |v, k| { - let k = if c == 1 { 0 } else { k }; - let span = hi[k] - lo[k]; - if span.is_finite() && span > 1e-6 { (v - lo[k]) / span } else { v } - }) -} - -fn invert_channels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let flags = [ctx.b("red"), ctx.b("green"), ctx.b("blue"), ctx.b("alpha")]; - Ok(vec![img.map(img.kind, |p| std::array::from_fn(|k| if flags[k] { 1.0 - p[k] } else { p[k] }))]) -} - -fn clamp_channels(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let (lo, hi) = (ctx.v4("min"), ctx.v4("max")); - Ok(vec![img.map(img.kind, |p| std::array::from_fn(|k| p[k].max(lo[k]).min(hi[k].max(lo[k]))))]) -} - -fn color_variation(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let index = ctx.input(1); - let (hr, sr, vr, sc, s, tile) = (ctx.f("hue"), ctx.f("saturation"), ctx.f("value"), ctx.f("scale").max(1.0).round(), ctx.seed, ctx.tile); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Color, |u, v| { - let p = img.sample_nearest(u, v, false); - // Three random shifts in -1..1: per flood fill region, or from noise. - let r: [f32; 3] = match index.map(|i| i.sample_nearest(u, v, tile)) { - Some(q) if q[3] > 0.5 => std::array::from_fn(|k| region_rand(q[2], 10 + k as u32, s) * 2.0 - 1.0), - Some(_) => [0.0; 3], - None => std::array::from_fn(|k| (fbm(u, v, sc, 3, 0.5, s.wrapping_add(k as u32 * 101)) - 0.5) * 4.0), - }; - let hsl = ops::rgb_to_hsl(p); - let c = ops::hsl_to_rgb(hsl[0] + hr * r[0], (hsl[1] * (1.0 + sr * r[1])).clamp(0.0, 1.0), (hsl[2] * (1.0 + vr * r[2])).max(0.0)); - [c[0], c[1], c[2], p[3]] - })]) -} - -fn lerp(ctx: &Ctx) -> CookResult { - let kind = ctx.main_kind(Kind::Gray); - let (a, b) = (ctx.any_or(0, kind, [0.0, 0.0, 0.0, 1.0]).to_kind(kind), ctx.any_or(1, kind, [1.0; 4]).to_kind(kind)); - let m = ctx.gray_or(2, ctx.f("position")); - Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| { - let (x, y) = (x as i64, y as i64); - let (p, q, t) = (a.get(x, y, false), b.get(x, y, false), m.get_gray(x, y, false)); - std::array::from_fn(|k| p[k] + (q[k] - p[k]) * t) - })]) -} - -/// Per-channel `f(a, b)` of two inputs (in the kind of the first connected one); B defaults to -/// `b_default`; alpha from A. -fn binary(ctx: &Ctx, b_default: f32, f: impl Fn(f32, f32) -> f32 + Sync) -> CookResult { - let kind = ctx.main_kind(Kind::Gray); - let a = ctx.any_or(0, kind, [0.0, 0.0, 0.0, 1.0]).to_kind(kind); - let b = ctx.any_or(1, kind, [b_default, b_default, b_default, 1.0]).to_kind(kind); - Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| { - let (p, q) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - [f(p[0], q[0]), f(p[1], q[1]), f(p[2], q[2]), p[3]] - })]) -} - -fn minimum(ctx: &Ctx) -> CookResult { - binary(ctx, 1.0, f32::min) -} - -fn maximum(ctx: &Ctx) -> CookResult { - binary(ctx, 0.0, f32::max) -} - -fn multiply(ctx: &Ctx) -> CookResult { - binary(ctx, 1.0, |a, b| a * b) -} - -fn difference(ctx: &Ctx) -> CookResult { - binary(ctx, 0.0, |a, b| (a - b).abs()) -} - -fn add(ctx: &Ctx) -> CookResult { - let cl = ctx.b("clamp"); - binary(ctx, 0.0, |a, b| if cl { (a + b).clamp(0.0, 1.0) } else { a + b }) -} - -fn subtract(ctx: &Ctx) -> CookResult { - let cl = ctx.b("clamp"); - binary(ctx, 0.0, |a, b| if cl { (a - b).clamp(0.0, 1.0) } else { a - b }) -} - -fn median(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let r: i64 = if ctx.i("size") == 1 { 2 } else { 1 }; - let c = img.channels(); - let tile = ctx.tile; - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let mut buf = [[0.0f32; 25]; 4]; - let mut n = 0; - for dy in -r..=r { - for dx in -r..=r { - let p = img.get(x as i64 + dx, y as i64 + dy, tile); - for (k, b) in buf.iter_mut().enumerate() { - b[n] = p[k]; - } - n += 1; - } - } - let mut out = [0.0; 4]; - for (k, b) in buf.iter_mut().enumerate().take(c) { - let s = &mut b[..n]; - let (_, m, _) = s.select_nth_unstable_by(n / 2, f32::total_cmp); - out[k] = *m; - } - out - })]) -} - -fn unsharp_mask(ctx: &Ctx) -> CookResult { - let img = src(ctx); - let blurred = ops::gaussian(&img, px(ctx, ctx.f("radius")), ctx.tile); - let (amt, th) = (ctx.f("amount"), ctx.f("threshold")); - Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { - let (p, q) = (img.get(x as i64, y as i64, false), blurred.get(x as i64, y as i64, false)); - let f = |a: f32, b: f32| if (a - b).abs() > th { a + (a - b) * amt } else { a }; - [f(p[0], q[0]), f(p[1], q[1]), f(p[2], q[2]), p[3]] - })]) -} - -/// Sobel slopes (dx, dy) of a gray image, in value units per pixel. -fn sobel_slope(img: &Image, x: i64, y: i64, tile: bool) -> (f32, f32) { - let g = |dx: i64, dy: i64| img.get_gray(x + dx, y + dy, tile); - let gx = g(1, -1) + 2.0 * g(1, 0) + g(1, 1) - g(-1, -1) - 2.0 * g(-1, 0) - g(-1, 1); - let gy = g(-1, 1) + 2.0 * g(0, 1) + g(1, 1) - g(-1, -1) - 2.0 * g(0, -1) - g(1, -1); - (gx / 8.0, gy / 8.0) -} - -fn sobel(ctx: &Ctx) -> CookResult { - let img = ctx.gray_or(0, 0.0); - let k = ctx.f("intensity") * 2.0; - Ok(vec![Image::gray(ctx.w, ctx.h, |x, y| { - let (dx, dy) = sobel_slope(&img, x as i64, y as i64, ctx.tile); - ((dx * dx + dy * dy).sqrt() * k).min(1.0) - })]) -} - -/// The mask input (inside where above 0.5). -fn mask(ctx: &Ctx) -> Image { - ctx.gray_or(0, 0.0) -} - -fn outer_glow(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let d2 = ops::distance_sq(ctx.w, ctx.h, |i| m.data.get(i).is_some_and(|v| *v > 0.5), ctx.tile); - let (size, amt, fall) = (px(ctx, ctx.f("size")).max(1e-3), ctx.f("intensity"), ctx.f("falloff").max(0.01)); - let v = d2.iter().zip(m.data.iter()).map(|(d, mv)| mv.max((1.0 - d.sqrt() / size).max(0.0).powf(fall) * amt)).collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn inner_shadow(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let (ox, oy) = offset(ctx, ctx.f("angle"), ctx.f("distance")); - let (w, tile) = (ctx.w as usize, ctx.tile); - // Distance to the nearest pixel outside the mask shifted toward the shadow. - let d2 = ops::distance_sq(ctx.w, ctx.h, |i| m.get_gray((i % w) as i64 - ox, (i / w) as i64 - oy, tile) <= 0.5, tile); - let (size, op) = (px(ctx, ctx.f("size")).max(1e-3), ctx.f("opacity")); - let v = d2.iter().zip(m.data.iter()).map(|(d, mv)| mv * (1.0 - op * (1.0 - d.sqrt() / size).clamp(0.0, 1.0))).collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn drop_shadow(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let (ox, oy) = offset(ctx, ctx.f("angle"), ctx.f("distance")); - let shifted = Image::gray(ctx.w, ctx.h, |x, y| m.get_gray(x as i64 - ox, y as i64 - oy, ctx.tile)); - let op = ctx.f("opacity"); - let shadow = ops::gaussian(&shifted, px(ctx, ctx.f("size")), ctx.tile).map(Kind::Gray, |p| [p[0] * op, 0.0, 0.0, 0.0]); - let out = Image::gray(ctx.w, ctx.h, |x, y| m.get_gray(x as i64, y as i64, false).max(shadow.get_gray(x as i64, y as i64, false))); - Ok(vec![out, shadow]) -} - -fn height_curvature(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let r = px(ctx, ctx.f("radius")); - // Difference of Gaussians: a band-limited Laplacian that ignores pixel noise. - let (fine, wide) = (ops::gaussian(&h, r * 0.5, ctx.tile), ops::gaussian(&h, r * 2.0, ctx.tile)); - let k = ctx.f("intensity") * 8.0; - let v = fine.data.iter().zip(wide.data.iter()).map(|(a, b)| (0.5 + (a - b) * k).clamp(0.0, 1.0)).collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn outline(ctx: &Ctx) -> CookResult { - let m = mask(ctx); - let inside = |i: usize| m.data.get(i).is_some_and(|v| *v > 0.5); - let to_in = ops::distance_sq(ctx.w, ctx.h, inside, ctx.tile); - let to_out = ops::distance_sq(ctx.w, ctx.h, |i| !inside(i), ctx.tile); - let w = px(ctx, ctx.f("width")); - let (lo, hi) = match ctx.i("position") { - 0 => (0.0, w), - 2 => (-w, 0.0), - _ => (-w * 0.5, w * 0.5), - }; - // Signed distance to the edge (positive outside), half a pixel off each side of it. - let v = (0..to_in.len()) - .map(|i| { - let sd = if inside(i) { 0.5 - to_out[i].sqrt() } else { to_in[i].sqrt() - 0.5 }; - (sd - lo + 0.5).clamp(0.0, 1.0) * (hi - sd + 0.5).clamp(0.0, 1.0) - }) - .collect(); - Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) -} - -fn flat(ctx: &Ctx, i: usize) -> Image { - ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color() -} - -fn normal_combine(ctx: &Ctx) -> CookResult { - let (base, det) = (flat(ctx, 0), flat(ctx, 1)); - let k = ctx.f("intensity"); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (b, d) = (unpack(base.get(x as i64, y as i64, false)), unpack(det.get(x as i64, y as i64, false))); - // Whiteout blending: add the slopes, multiply the heights. - pack([b[0] + d[0] * k, b[1] + d[1] * k, b[2] * (1.0 + (d[2] - 1.0) * k.min(1.0)).max(1e-3)], 1.0) - })]) -} - -fn normal_rotate(ctx: &Ctx) -> CookResult { - let n = flat(ctx, 0); - let (s, c) = (ctx.f("angle") * TAU).sin_cos(); - Ok(vec![n.map(Kind::Color, |p| { - let v = unpack(p); - pack([v[0] * c - v[1] * s, v[0] * s + v[1] * c, v[2]], p[3]) - })]) -} - -fn normal_sobel(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let k = ctx.f("intensity") * ctx.w as f32 / 32.0; - let dx_fmt = ctx.i("format") == 1; - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let (dx, dy) = sobel_slope(&h, x as i64, y as i64, ctx.tile); - let ny = dy * k; - pack([-dx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0) - })]) -} diff --git a/_to_delete/nodes_flood_fill.rs b/_to_delete/nodes_flood_fill.rs deleted file mode 100644 index ccc7c65..0000000 --- a/_to_delete/nodes_flood_fill.rs +++ /dev/null @@ -1,306 +0,0 @@ -//! Filters › Flood fill: labels the connected white regions of a tile mask and turns each region -//! into per-region data (random values, colors, gradients, sizes, positions). -//! -//! The index map that [`flood_fill`] writes holds, per region pixel: R, G = the region's -//! bounding-box center (UV), B = a random id, A = 1. Gaps are all zero. Downstream nodes re-label -//! the index map (pixels of one region share the same RGB), so they recover the exact bounding -//! box, and a pixel's place inside it, at any size. Labeling wraps across the image edges when -//! the graph tiles, so a tile crossing an edge is one region. - -use std::f32::consts::TAU; - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::noise::{hash3, rand1}; - -const FLOOD: &str = "Filters/Flood fill"; -const NONE: u32 = u32::MAX; - -/// Connected regions of an image. -pub struct Regions { - /// Region index per pixel (`u32::MAX` = background). - pub label: Vec<u32>, - /// Unwrapped pixel coordinates (a region crossing an edge continues past it). - pub pos: Vec<[i32; 2]>, - /// Per region: min x, min y, max x, max y (unwrapped, inclusive). - pub bbox: Vec<[i32; 4]>, -} - -/// Label the 4-connected regions of pixels where `inside` holds and neighbours are `same`. -pub fn label(w: u32, h: u32, tile: bool, inside: impl Fn(usize) -> bool, same: impl Fn(usize, usize) -> bool) -> Regions { - let (wi, hi) = (w as i32, h as i32); - let n = w as usize * h as usize; - let mut label = vec![NONE; n]; - let mut pos = vec![[0i32; 2]; n]; - let mut bbox = Vec::new(); - let mut queue: Vec<usize> = Vec::new(); - for start in 0..n { - if label[start] != NONE || !inside(start) { - continue; - } - let id = bbox.len() as u32; - let s = [(start % w as usize) as i32, (start / w as usize) as i32]; - label[start] = id; - pos[start] = s; - let mut b = [s[0], s[1], s[0], s[1]]; - queue.clear(); - queue.push(start); - let mut head = 0; - while let Some(&i) = queue.get(head) { - head += 1; - let p = pos[i]; - for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { - let q = [p[0] + dx, p[1] + dy]; - let (x, y) = if tile { - (q[0].rem_euclid(wi), q[1].rem_euclid(hi)) - } else if (0..wi).contains(&q[0]) && (0..hi).contains(&q[1]) { - (q[0], q[1]) - } else { - continue; - }; - let j = (y * wi + x) as usize; - if label[j] != NONE || !inside(j) || !same(i, j) { - continue; - } - label[j] = id; - pos[j] = q; - b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])]; - queue.push(j); - } - } - bbox.push(b); - } - Regions { label, pos, bbox } -} - -/// What a downstream node knows about the region under a pixel. -pub struct RegionPx { - /// The region's random id (0..1). - pub id: f32, - /// Bounding-box center (UV, wrapped into 0..1). - pub center: [f32; 2], - /// Bounding-box size (UV). - pub size: [f32; 2], - /// The pixel's place inside the bounding box (0..1). - pub local: [f32; 2], -} - -/// Bounding-box center and size (UV) of a region. -fn bbox_uv(b: [i32; 4], w: u32, h: u32) -> ([f32; 2], [f32; 2]) { - let (wf, hf) = (w as f32, h as f32); - let (ex, ey) = ((b[2] - b[0] + 1) as f32, (b[3] - b[1] + 1) as f32); - let center = [((b[0] + b[2] + 1) as f32 * 0.5 / wf).rem_euclid(1.0), ((b[1] + b[3] + 1) as f32 * 0.5 / hf).rem_euclid(1.0)]; - (center, [(ex / wf).min(1.0), (ey / hf).min(1.0)]) -} - -/// A uniform random value per region (and per `k`), from the region's id and the node's seed. -pub fn region_rand(id: f32, k: u32, seed: u32) -> f32 { - rand1(id.to_bits() ^ k.wrapping_mul(0x9e37_79b9), seed) -} - -/// The index map input at the output size (nearest sampling keeps region values exact). -fn index_input(ctx: &Ctx, i: usize) -> Image { - match ctx.input(i) { - Some(img) => Image::generate_uv(ctx.w, ctx.h, Kind::Color, |u, v| img.sample_nearest(u, v, false)), - None => Image::filled(ctx.w, ctx.h, Kind::Color, [0.0; 4]), - } -} - -/// Run `f` for every region pixel of index map input `i`; background pixels get `bg`. -pub fn per_region(ctx: &Ctx, i: usize, kind: Kind, bg: [f32; 4], f: impl Fn(&RegionPx, f32, f32) -> [f32; 4] + Sync) -> Image { - let idx = index_input(ctx, i).to_color(); - let d = idx.data.as_slice(); - let px = |i: usize| d.get(i * 4..i * 4 + 4).unwrap_or(&[0.0; 4]); - let regions = label(ctx.w, ctx.h, ctx.tile, |i| px(i)[3] > 0.5, |a, b| px(a)[..3] == px(b)[..3]); - let (w, h) = (ctx.w, ctx.h); - Image::generate(w, h, kind, |x, y| { - let i = (y * w + x) as usize; - let Some(b) = regions.label.get(i).and_then(|l| regions.bbox.get(*l as usize)) else { - return bg; - }; - let (center, size) = bbox_uv(*b, w, h); - let p = regions.pos[i]; - let local = [(p[0] - b[0]) as f32 + 0.5, (p[1] - b[1]) as f32 + 0.5]; - let local = [local[0] / (b[2] - b[0] + 1) as f32, local[1] / (b[3] - b[1] + 1) as f32]; - let r = RegionPx { id: px(i)[2], center, size, local }; - f(&r, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32) - }) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let index_in = |id, label| node(id, label, FLOOD).color_in("input", "Index map"); - vec![ - node("flood_fill", "Flood Fill", FLOOD) - .desc("Finds every connected white region of a tile mask (regions crossing the edges are one) and writes an index map: R, G = region center, B = random id, A = 1.") - .gray_in("input", "Mask") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .output("output", "Index map", PortKind::Color) - .cook(flood_fill), - index_in("flood_fill_to_random_grayscale", "Flood Fill to Random Grayscale") - .desc("A random gray per region.") - .float("min", "Min", 0.0, 0.0, 1.0) - .float("max", "Max", 1.0, 0.0, 1.0) - .gray_out() - .cook(to_random_gray), - index_in("flood_fill_to_random_color", "Flood Fill to Random Color") - .desc("A random color per region.") - .float("saturation", "Saturation", 0.7, 0.0, 1.0) - .float("lightness", "Lightness", 0.5, 0.0, 1.0) - .float("lightness_random", "Lightness random", 0.3, 0.0, 1.0) - .color_out() - .cook(to_random_color), - index_in("flood_fill_to_gradient", "Flood Fill to Gradient") - .desc("A linear gradient across each region's bounding box.") - .angle("angle", "Angle", 0.0) - .float("angle_random", "Angle random", 0.0, 0.0, 1.0) - .float("slope_random", "Slope random", 0.0, 0.0, 1.0) - .gray_out() - .cook(to_gradient), - index_in("flood_fill_to_bbox_size", "Flood Fill to BBox Size") - .desc("Each region's bounding-box size.") - .choice("mode", "Size", &["Width", "Height", "Max", "Min", "Area"], 2) - .gray_out() - .cook(to_bbox_size), - index_in("flood_fill_to_position", "Flood Fill to Position") - .desc("Each region's center position (R = X, G = Y).") - .color_out() - .cook(to_position), - index_in("flood_fill_to_grayscale", "Flood Fill to Grayscale") - .desc("Each region takes the value of the input at its center.") - .gray_in("source", "Source") - .gray_out() - .cook(to_grayscale), - index_in("flood_fill_to_color", "Flood Fill to Color") - .desc("Each region takes the color of the input at its center.") - .color_in("source", "Source") - .color_out() - .cook(to_color), - ] -} - -fn flood_fill(ctx: &Ctx) -> CookResult { - let t = ctx.f("threshold"); - let m = ctx.gray_or(0, 0.0); - let d = m.data.as_slice(); - let regions = label(ctx.w, ctx.h, ctx.tile, |i| d.get(i).is_some_and(|v| *v > t), |_, _| true); - let (w, h, s) = (ctx.w, ctx.h, ctx.seed); - let info: Vec<[f32; 4]> = regions - .bbox - .iter() - .map(|b| { - let (c, size) = bbox_uv(*b, w, h); - // Stable per region: from its center and size, not its scan order. - let k = hash3((c[0] * 65536.0) as i32, (c[1] * 65536.0) as i32, s ^ (((size[0] * 4096.0) as u32) << 12) ^ ((size[1] * 4096.0) as u32)); - [c[0], c[1], ((k >> 8) as f32 / (1u32 << 24) as f32).max(1e-4), 1.0] - }) - .collect(); - Ok(vec![Image::generate(w, h, Kind::Color, |x, y| { - regions.label.get((y * w + x) as usize).and_then(|l| info.get(*l as usize)).copied().unwrap_or([0.0; 4]) - })]) -} - -fn to_random_gray(ctx: &Ctx) -> CookResult { - let (lo, hi, s) = (ctx.f("min"), ctx.f("max"), ctx.seed); - Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| [lo + (hi - lo) * region_rand(r.id, 0, s), 0.0, 0.0, 0.0])]) -} - -fn to_random_color(ctx: &Ctx) -> CookResult { - let (sat, l, lr, s) = (ctx.f("saturation"), ctx.f("lightness"), ctx.f("lightness_random"), ctx.seed); - Ok(vec![per_region(ctx, 0, Kind::Color, [0.0, 0.0, 0.0, 1.0], |r, _, _| { - let light = (l + (region_rand(r.id, 2, s) - 0.5) * lr).clamp(0.0, 1.0); - let c = crate::ops::hsl_to_rgb(region_rand(r.id, 1, s), sat, light); - [c[0], c[1], c[2], 1.0] - })]) -} - -fn to_gradient(ctx: &Ctx) -> CookResult { - let (a, ar, sr, s) = (ctx.f("angle"), ctx.f("angle_random"), ctx.f("slope_random"), ctx.seed); - Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| { - let (sn, cs) = ((a + (region_rand(r.id, 3, s) - 0.5) * ar) * TAU).sin_cos(); - // Projection onto the direction, normalized so the gradient spans 0..1 over the box. - let (x, y) = (r.local[0] - 0.5, r.local[1] - 0.5); - let t = 0.5 + (x * cs + y * sn) / (cs.abs() + sn.abs()).max(1e-6); - let slope = 1.0 - sr * region_rand(r.id, 4, s); - [(t * slope).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - })]) -} - -fn to_bbox_size(ctx: &Ctx) -> CookResult { - let mode = ctx.i("mode"); - Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| { - let [w, h] = r.size; - let v = match mode { - 0 => w, - 1 => h, - 3 => w.min(h), - 4 => w * h, - _ => w.max(h), - }; - [v, 0.0, 0.0, 0.0] - })]) -} - -fn to_position(ctx: &Ctx) -> CookResult { - Ok(vec![per_region(ctx, 0, Kind::Color, [0.0, 0.0, 0.0, 1.0], |r, _, _| [r.center[0], r.center[1], 0.0, 1.0])]) -} - -fn sample_at_center(ctx: &Ctx, kind: Kind) -> Image { - let src = ctx.input(1).map(|i| i.to_kind(kind)); - let tile = ctx.tile; - per_region(ctx, 0, kind, [0.0, 0.0, 0.0, 1.0], |r, _, _| src.as_ref().map_or([1.0; 4], |img| img.sample(r.center[0], r.center[1], tile))) -} - -fn to_grayscale(ctx: &Ctx) -> CookResult { - Ok(vec![sample_at_center(ctx, Kind::Gray)]) -} - -fn to_color(ctx: &Ctx) -> CookResult { - Ok(vec![sample_at_center(ctx, Kind::Color)]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use super::*; - use crate::{find, resolve_params}; - - fn cook(id: &str, inputs: &[Option<Image>], w: u32) -> Vec<Image> { - let def = find(id).unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w, h: w, seed: 3, tile: true, inputs, params: ¶ms, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap() - } - - #[test] - fn separate_squares_differ_and_edge_square_wraps() { - // Square A at 2..6, square B at 10..14, square C straddling the right edge (x 14..16 and 0..1) - // in rows 10..13. - let mask = Image::gray(16, 16, |x, y| { - let a = (2..6).contains(&x) && (2..6).contains(&y); - let b = (9..13).contains(&x) && (2..6).contains(&y); - let c = !(1..14).contains(&x) && (10..13).contains(&y); - (a || b || c) as i32 as f32 - }); - let idx = &cook("flood_fill", &[Some(mask)], 16)[0]; - let (a, b) = (idx.get(3, 3, false), idx.get(10, 3, false)); - assert_eq!(a[3], 1.0); - assert_ne!(a[2], b[2], "separate squares get different ids"); - assert_eq!(idx.get(0, 0, false), [0.0; 4], "gaps stay empty"); - let (l, r) = (idx.get(0, 11, false), idx.get(15, 11, false)); - assert_eq!(l, r, "a square across the edge is one region"); - // Pixels 14, 15 and 0 (wrapped to 16): the box middle is 15.5 px. - assert!((l[0] - 15.5 / 16.0).abs() < 1e-5, "{l:?}"); - let gray = &cook("flood_fill_to_random_grayscale", &[Some(idx.clone())], 16)[0]; - assert_eq!(gray.get(0, 11, false), gray.get(15, 11, false)); - assert_ne!(gray.get(3, 3, false), gray.get(10, 3, false)); - let size = &cook("flood_fill_to_bbox_size", &[Some(idx.clone())], 16)[0]; - assert!((size.get(15, 11, false)[0] - 3.0 / 16.0).abs() < 1e-5); - let grad = &cook("flood_fill_to_gradient", &[Some(idx.clone())], 16)[0]; - assert!(grad.get(2, 3, false)[0] < grad.get(5, 3, false)[0]); - assert!(grad.get(14, 11, false)[0] < grad.get(0, 11, false)[0], "the gradient continues across the edge"); - } -} diff --git a/_to_delete/nodes_function.rs b/_to_delete/nodes_function.rs deleted file mode 100644 index 50311c5..0000000 --- a/_to_delete/nodes_function.rs +++ /dev/null @@ -1,482 +0,0 @@ -//! Function graph evaluation: a [`FnGraph`] is compiled once into a flat instruction list -//! (dependency order from the output node), then run per pixel with a small register file. All -//! values are 4-wide; scalars are broadcast to every lane, so component-wise ops need no type -//! checks. The pixel processor samples its inputs at any position; the value processor runs once. - -use std::collections::BTreeMap; - -use materialcraft_core::Value; -use materialcraft_core::function::FnGraph; -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx}; -use crate::noise; - -/// Function node operations: (id, label, input count, library category). -pub const FN_OPS: &[(&str, &str, usize, &str)] = &[ - ("const_float", "Float", 0, "Constant"), - ("const_float2", "Float2", 0, "Constant"), - ("const_float3", "Float3", 0, "Constant"), - ("const_float4", "Float4", 0, "Constant"), - ("const_int", "Integer", 0, "Constant"), - ("const_bool", "Boolean", 0, "Constant"), - ("get_pos", "$pos", 0, "Variables"), - ("get_size", "$size", 0, "Variables"), - ("get_var", "Get variable", 0, "Variables"), - ("sample_gray", "Sample Gray", 1, "Samplers"), - ("sample_color", "Sample Color", 1, "Samplers"), - ("vec2", "Vector Float2", 2, "Vector"), - ("vec3", "Vector Float3", 3, "Vector"), - ("vec4", "Vector Float4", 4, "Vector"), - ("swizzle", "Swizzle", 1, "Vector"), - ("to_int", "To Integer", 1, "Cast"), - ("to_float", "To Float", 1, "Cast"), - ("add", "Add", 2, "Operator"), - ("sub", "Subtraction", 2, "Operator"), - ("mul", "Multiplication", 2, "Operator"), - ("div", "Division", 2, "Operator"), - ("mod", "Modulo", 2, "Operator"), - ("neg", "Negation", 1, "Operator"), - ("dot", "Dot Product", 2, "Operator"), - ("and", "And", 2, "Logical"), - ("or", "Or", 2, "Logical"), - ("not", "Not", 1, "Logical"), - ("gt", "Greater", 2, "Comparison"), - ("ge", "Greater or equal", 2, "Comparison"), - ("lt", "Lower", 2, "Comparison"), - ("le", "Lower or equal", 2, "Comparison"), - ("eq", "Equal", 2, "Comparison"), - ("ne", "Not equal", 2, "Comparison"), - ("abs", "Absolute", 1, "Function"), - ("floor", "Floor", 1, "Function"), - ("ceil", "Ceil", 1, "Function"), - ("frac", "Fractional part", 1, "Function"), - ("sqrt", "Square root", 1, "Function"), - ("exp", "Exponential", 1, "Function"), - ("log", "Logarithm", 1, "Function"), - ("log2", "Logarithm base 2", 1, "Function"), - ("pow2", "2^x", 1, "Function"), - ("sin", "Sine", 1, "Function"), - ("cos", "Cosine", 1, "Function"), - ("tan", "Tangent", 1, "Function"), - ("atan2", "Arc tangent 2", 2, "Function"), - ("cartesian", "Cartesian", 2, "Function"), - ("pow", "Power", 2, "Function"), - ("min", "Minimum", 2, "Function"), - ("max", "Maximum", 2, "Function"), - ("clamp", "Clamp", 3, "Function"), - ("lerp", "Linear interpolation", 3, "Function"), - ("length", "Length", 1, "Function"), - ("normalize", "Normalize", 1, "Function"), - ("rand", "Random", 1, "Function"), - ("noise", "Perlin noise", 1, "Function"), - ("if_else", "If...Else", 3, "Control"), -]; - -#[derive(Clone, Debug)] -enum Op { - Const([f32; 4]), - Pos, - Size, - Sample { input: usize, gray: bool }, - Unary(fn(f32) -> f32), - Binary(fn(f32, f32) -> f32), - Ternary(fn(f32, f32, f32) -> f32), - Dot, - Length, - Normalize, - Vec(usize), - Swizzle([usize; 4]), - Rand, - Noise, - IfElse, - Cartesian, -} - -#[derive(Clone, Debug)] -struct Instr { - op: Op, - args: Vec<usize>, - /// Lanes that carry meaning (1 = scalar). - dims: usize, -} - -/// A compiled function graph. -#[derive(Clone, Debug)] -pub struct Program { - code: Vec<Instr>, - seed: u32, -} - -fn b(v: bool) -> f32 { - if v { 1.0 } else { 0.0 } -} - -/// Return zero for nonfinite arithmetic results. -fn finite_or_zero(v: f32) -> f32 { - if v.is_finite() { v } else { 0.0 } -} - -fn dims_of(v: &Value) -> usize { - match v { - Value::Float2(_) | Value::Int2(_) => 2, - Value::Float3(_) => 3, - Value::Float4(_) | Value::Color(_) => 4, - _ => 1, - } -} - -fn broadcast(v: &Value) -> [f32; 4] { - match dims_of(v) { - 1 => [v.as_f32().unwrap_or(0.0); 4], - _ => v.as_vec4().unwrap_or([0.0; 4]), - } -} - -/// Compile `g` for evaluation. `vars` resolves `get_var` names (exposed graph inputs). -pub fn compile(g: &FnGraph, vars: &BTreeMap<String, Value>, seed: u32) -> Result<Program, String> { - let out = g.output.ok_or("the function has no output node")?; - let mut code: Vec<Instr> = Vec::new(); - let mut reg: BTreeMap<u32, usize> = BTreeMap::new(); - // Iterative post-order from the output; a node seen twice on the current path is a cycle. - let mut stack: Vec<(u32, bool)> = vec![(out, false)]; - let mut on_path = std::collections::BTreeSet::new(); - while let Some((id, done)) = stack.pop() { - if reg.contains_key(&id) { - continue; - } - let n = g.node(id).ok_or_else(|| format!("missing function node {id}"))?; - if !done { - if !on_path.insert(id) { - return Err("the function graph has a cycle".into()); - } - stack.push((id, true)); - for i in n.inputs.iter().flatten() { - if !reg.contains_key(i) { - stack.push((*i, false)); - } - } - continue; - } - on_path.remove(&id); - if code.len() > 4096 { - return Err("the function graph is too large".into()); - } - let args: Vec<usize> = n.inputs.iter().map(|i| i.and_then(|i| reg.get(&i).copied())).map(|r| r.unwrap_or(usize::MAX)).collect(); - let arity = FN_OPS.iter().find(|o| o.0 == n.op).map(|o| o.2).ok_or_else(|| format!("unknown function op `{}`", n.op))?; - if args.len() < arity || args.iter().take(arity).any(|a| *a == usize::MAX) { - return Err(format!("`{}` needs {arity} connected input(s)", n.op)); - } - let dim = |k: usize| args.get(k).and_then(|r| code.get(*r)).map_or(1, |i: &Instr| i.dims); - let maxd = (0..arity).map(dim).max().unwrap_or(1); - let (op, dims) = match n.op.as_str() { - o if o.starts_with("const_") => { - let v = n.value.clone().unwrap_or(Value::Float(0.0)); - (Op::Const(broadcast(&v)), dims_of(&v)) - } - "get_pos" => (Op::Pos, 2), - "get_size" => (Op::Size, 2), - "get_var" => { - let name = match &n.value { - Some(Value::Text(s)) => s.as_str(), - _ => "", - }; - let v = vars.get(name).cloned().unwrap_or(Value::Float(0.0)); - (Op::Const(broadcast(&v)), dims_of(&v)) - } - "sample_gray" | "sample_color" => { - let input = n.value.as_ref().and_then(Value::as_i32).unwrap_or(0).clamp(0, 3) as usize; - let gray = n.op == "sample_gray"; - (Op::Sample { input, gray }, if gray { 1 } else { 4 }) - } - "vec2" => (Op::Vec(2), 2), - "vec3" => (Op::Vec(3), 3), - "vec4" => (Op::Vec(4), 4), - "swizzle" => { - let s = match &n.value { - Some(Value::Text(s)) => s.clone(), - _ => "x".into(), - }; - let mut idx = [0usize; 4]; - let mut len = 0; - for (k, ch) in s.chars().take(4).enumerate() { - idx[k] = match ch { - 'y' | 'g' => 1, - 'z' | 'b' => 2, - 'w' | 'a' => 3, - _ => 0, - }; - len = k + 1; - } - if len == 1 { - idx = [idx[0]; 4]; - } - (Op::Swizzle(idx), len.max(1)) - } - "to_int" | "floor" => (Op::Unary(f32::floor), maxd), - "to_float" => (Op::Unary(|a| a), maxd), - "add" => (Op::Binary(|a, b| a + b), maxd), - "sub" => (Op::Binary(|a, b| a - b), maxd), - "mul" => (Op::Binary(|a, b| a * b), maxd), - "div" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a / b }), maxd), - "mod" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a.rem_euclid(b) }), maxd), - "neg" => (Op::Unary(|a| -a), maxd), - "dot" => (Op::Dot, 1), - "and" => (Op::Binary(|a, x| b(a != 0.0 && x != 0.0)), maxd), - "or" => (Op::Binary(|a, x| b(a != 0.0 || x != 0.0)), maxd), - "not" => (Op::Unary(|a| b(a == 0.0)), maxd), - "gt" => (Op::Binary(|a, x| b(a > x)), maxd), - "ge" => (Op::Binary(|a, x| b(a >= x)), maxd), - "lt" => (Op::Binary(|a, x| b(a < x)), maxd), - "le" => (Op::Binary(|a, x| b(a <= x)), maxd), - "eq" => (Op::Binary(|a, x| b(a == x)), maxd), - "ne" => (Op::Binary(|a, x| b(a != x)), maxd), - "abs" => (Op::Unary(f32::abs), maxd), - "ceil" => (Op::Unary(f32::ceil), maxd), - "frac" => (Op::Unary(|a| a - a.floor()), maxd), - "sqrt" => (Op::Unary(|a| a.max(0.0).sqrt()), maxd), - "exp" => (Op::Unary(f32::exp), maxd), - "log" => (Op::Unary(|a| if a > 0.0 { a.ln() } else { 0.0 }), maxd), - "log2" => (Op::Unary(|a| if a > 0.0 { finite_or_zero(a.log2()) } else { 0.0 }), maxd), - "pow2" => (Op::Unary(|a| finite_or_zero(a.exp2())), maxd), - "sin" => (Op::Unary(f32::sin), maxd), - "cos" => (Op::Unary(f32::cos), maxd), - "tan" => (Op::Unary(f32::tan), maxd), - "atan2" => (Op::Binary(f32::atan2), maxd), - "cartesian" => (Op::Cartesian, 2), - "pow" => (Op::Binary(|a, x| if a < 0.0 && x.fract() != 0.0 { 0.0 } else { a.powf(x) }), maxd), - "min" => (Op::Binary(f32::min), maxd), - "max" => (Op::Binary(f32::max), maxd), - "clamp" => (Op::Ternary(|a, lo, hi| a.max(lo).min(hi.max(lo))), maxd), - "lerp" => (Op::Ternary(|a, x, t| a + (x - a) * t), maxd.max(dim(0)).max(dim(1))), - "length" => (Op::Length, 1), - "normalize" => (Op::Normalize, dim(0)), - "rand" => (Op::Rand, dim(0)), - "noise" => (Op::Noise, 1), - "if_else" => (Op::IfElse, dim(1).max(dim(2))), - other => return Err(format!("unknown function op `{other}`")), - }; - reg.insert(id, code.len()); - code.push(Instr { op, args: args.into_iter().take(arity).collect(), dims }); - } - Ok(Program { code, seed }) -} - -impl Program { - /// Lanes of the result. - pub fn dims(&self) -> usize { - self.code.last().map_or(1, |i| i.dims) - } - - /// Run at normalized position `pos` of an image of `size`, sampling `inputs`. - pub fn eval(&self, pos: [f32; 2], size: [f32; 2], inputs: &[Option<Image>], tile: bool, regs: &mut Vec<[f32; 4]>) -> [f32; 4] { - regs.clear(); - for ins in &self.code { - let a = |k: usize| ins.args.get(k).and_then(|r| regs.get(*r)).copied().unwrap_or([0.0; 4]); - let v = match &ins.op { - Op::Const(c) => *c, - Op::Pos => [pos[0], pos[1], 0.0, 0.0], - Op::Size => [size[0], size[1], 0.0, 0.0], - Op::Sample { input, gray } => { - let p = a(0); - match inputs.get(*input).and_then(Option::as_ref) { - Some(img) if *gray => [img.sample_gray(p[0], p[1], tile); 4], - Some(img) => img.sample(p[0], p[1], tile), - None => [0.0, 0.0, 0.0, 1.0], - } - } - Op::Unary(f) => a(0).map(f), - Op::Binary(f) => { - let (x, y) = (a(0), a(1)); - [f(x[0], y[0]), f(x[1], y[1]), f(x[2], y[2]), f(x[3], y[3])] - } - Op::Ternary(f) => { - let (x, y, z) = (a(0), a(1), a(2)); - [f(x[0], y[0], z[0]), f(x[1], y[1], z[1]), f(x[2], y[2], z[2]), f(x[3], y[3], z[3])] - } - Op::Dot => { - let (x, y) = (a(0), a(1)); - let n = ins.args.iter().filter_map(|r| self.code.get(*r)).map(|i| i.dims).max().unwrap_or(1); - [(0..n).map(|k| x[k] * y[k]).sum(); 4] - } - Op::Length => { - let x = a(0); - let n = ins.args.first().and_then(|r| self.code.get(*r)).map_or(1, |i| i.dims); - [(0..n).map(|k| x[k] * x[k]).sum::<f32>().sqrt(); 4] - } - Op::Normalize => { - let x = a(0); - let l = (0..ins.dims).map(|k| x[k] * x[k]).sum::<f32>().sqrt(); - if l > 0.0 { x.map(|c| c / l) } else { x } - } - Op::Vec(n) => { - let mut o = [0.0; 4]; - for k in 0..*n { - o[k] = a(k)[0]; - } - o - } - Op::Swizzle(idx) => { - let x = a(0); - idx.map(|i| x[i]) - } - Op::Rand => a(0).map(|c| noise::rand1(c.to_bits(), self.seed)), - Op::Noise => { - let p = a(0); - [noise::perlin(p[0], p[1], 0, self.seed) * 0.5 + 0.5; 4] - } - Op::Cartesian => { - // Inputs are radius and angle (radians); the result is a Float2. - let (radius, angle) = (a(0)[0], a(1)[0]); - if radius.is_finite() && angle.is_finite() { - let (sin, cos) = angle.sin_cos(); - [finite_or_zero(radius * cos), finite_or_zero(radius * sin), 0.0, 0.0] - } else { - [0.0; 4] - } - } - Op::IfElse => { - if a(0)[0] != 0.0 { - a(1) - } else { - a(2) - } - } - }; - regs.push(v); - } - regs.last().copied().unwrap_or([0.0; 4]) - } -} - -/// The default pixel processor function: the first input, unchanged. -pub fn default_pixel_function() -> FnGraph { - let mut g = FnGraph::default(); - let pos = g.add("get_pos", &[], None); - let s = g.add("sample_color", &[pos], Some(Value::Int(0))); - g.output = Some(s); - g -} - -pub(crate) fn pixel_processor(ctx: &Ctx) -> CookResult { - let f = ctx.function("function").ok_or("no function")?; - let prog = compile(f, ctx.vars, ctx.seed)?; - let gray = ctx.i("output") == 1; - let dims = prog.dims(); - let size = [ctx.w as f32, ctx.h as f32]; - let kind = if gray { Kind::Gray } else { Kind::Color }; - Ok(vec![Image::generate_uv(ctx.w, ctx.h, kind, |u, v| { - // shortcut: one register file per pixel; a thread-local would save the allocation. - let mut regs = Vec::with_capacity(prog.code.len()); - let r = prog.eval([u, v], size, ctx.inputs, ctx.tile, &mut regs); - match (gray, dims) { - (true, _) => [r[0], 0.0, 0.0, 0.0], - (false, 1) => [r[0], r[0], r[0], 1.0], - (false, 2) => [r[0], r[1], 0.0, 1.0], - (false, 3) => [r[0], r[1], r[2], 1.0], - _ => r, - } - })]) -} - -pub(crate) fn value_processor(ctx: &Ctx) -> CookResult { - let f = ctx.function("function").ok_or("no function")?; - let prog = compile(f, ctx.vars, ctx.seed)?; - let r = prog.eval([0.5, 0.5], [ctx.w as f32, ctx.h as f32], ctx.inputs, ctx.tile, &mut Vec::new()); - Ok(vec![if prog.dims() == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [r[0]; 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, r) }]) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn evaluate_math(op: &str, values: &[Value]) -> (usize, [f32; 4]) { - let mut g = FnGraph::default(); - let inputs: Vec<_> = values - .iter() - .map(|value| { - let op = match value { - Value::Float2(_) => "const_float2", - Value::Float3(_) => "const_float3", - Value::Float4(_) => "const_float4", - _ => "const_float", - }; - g.add(op, &[], Some(value.clone())) - }) - .collect(); - g.output = Some(g.add(op, &inputs, None)); - let p = compile(&g, &BTreeMap::new(), 0).unwrap(); - (p.dims(), p.eval([0.0; 2], [1.0; 2], &[], true, &mut Vec::new())) - } - - #[test] - fn base_two_functions_preserve_lanes_and_scalar_broadcast() { - let (dims, result) = evaluate_math("pow2", &[Value::Float4([-2.0, 0.0, 1.0, 3.0])]); - assert_eq!((dims, result), (4, [0.25, 1.0, 2.0, 8.0])); - let (dims, result) = evaluate_math("log2", &[Value::Float4([0.25, 1.0, 2.0, 8.0])]); - assert_eq!((dims, result), (4, [-2.0, 0.0, 1.0, 3.0])); - assert_eq!(evaluate_math("pow2", &[Value::Float(3.0)]), (1, [8.0; 4])); - assert_eq!(evaluate_math("log2", &[Value::Float(8.0)]), (1, [3.0; 4])); - for op in ["pow2", "log2"] { - assert_eq!(evaluate_math(op, &[Value::Float2([1.0, 2.0])]).0, 2); - assert_eq!(evaluate_math(op, &[Value::Float3([1.0, 2.0, 3.0])]).0, 3); - } - } - - #[test] - fn cartesian_uses_radius_then_angle_in_radians() { - for (radius, angle, expected) in [ - (2.0, 0.0, [2.0, 0.0]), - (2.0, std::f32::consts::FRAC_PI_2, [0.0, 2.0]), - (2.0, -std::f32::consts::FRAC_PI_2, [0.0, -2.0]), - (2.0, std::f32::consts::PI, [-2.0, 0.0]), - (0.0, 1.0, [0.0, 0.0]), - ] { - let (dims, result) = evaluate_math("cartesian", &[Value::Float(radius), Value::Float(angle)]); - assert_eq!(dims, 2); - assert!((result[0] - expected[0]).abs() < 1e-6); - assert!((result[1] - expected[1]).abs() < 1e-6); - assert_eq!(&result[2..], &[0.0, 0.0]); - } - } - - #[test] - fn new_math_functions_handle_invalid_domains_and_missing_inputs() { - assert_eq!(evaluate_math("log2", &[Value::Float4([0.0, -1.0, f32::NAN, f32::INFINITY])]).1, [0.0; 4]); - assert_eq!(evaluate_math("pow2", &[Value::Float4([128.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY])]).1, [0.0; 4]); - for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert_eq!(evaluate_math("cartesian", &[Value::Float(invalid), Value::Float(0.0)]).1, [0.0; 4]); - assert_eq!(evaluate_math("cartesian", &[Value::Float(1.0), Value::Float(invalid)]).1, [0.0; 4]); - } - for op in ["pow2", "log2", "cartesian"] { - let mut g = FnGraph::default(); - g.output = Some(g.add(op, &[], None)); - assert!(compile(&g, &BTreeMap::new(), 0).is_err()); - } - } - - #[test] - fn compiles_and_runs_arithmetic() { - let mut g = FnGraph::default(); - let pos = g.add("get_pos", &[], None); - let x = g.add("swizzle", &[pos], Some(Value::Text("x".into()))); - let two = g.add("const_float", &[], Some(Value::Float(2.0))); - let m = g.add("mul", &[x, two], None); - g.output = Some(m); - let p = compile(&g, &BTreeMap::new(), 0).unwrap(); - assert_eq!(p.dims(), 1); - let r = p.eval([0.25, 0.5], [8.0, 8.0], &[], true, &mut Vec::new()); - assert_eq!(r[0], 0.5); - } - - #[test] - fn rejects_bad_graphs() { - let mut g = FnGraph::default(); - let a = g.add("add", &[], None); - g.output = Some(a); - assert!(compile(&g, &BTreeMap::new(), 0).is_err()); - g.nodes[0].inputs = vec![Some(a), Some(a)]; - assert!(compile(&g, &BTreeMap::new(), 0).is_err()); - assert!(compile(&FnGraph::default(), &BTreeMap::new(), 0).is_err()); - } -} diff --git a/_to_delete/nodes_fx_map.rs b/_to_delete/nodes_fx_map.rs deleted file mode 100644 index baae5ad..0000000 --- a/_to_delete/nodes_fx_map.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! Atomic › FX-Map: a pattern instancer (regular grid, random scatter or random quadtree -//! subdivision), plus the shared splatting engine of the scatter nodes. Instances wrap across the -//! edges, so the output tiles. - -use std::f32::consts::{SQRT_2, TAU}; - -use materialcraft_image::{Image, Kind}; - -use crate::atomic::ATOMIC; -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::noise::{hash, rand1}; -use crate::patterns::{PATTERNS, SHAPES, shape}; - -/// One placed pattern: center (uv), half extents (uv), rotation (turns), luminance and the index -/// of the pattern it shows. -#[derive(Clone, Copy, Debug)] -pub(crate) struct Inst { - pub c: [f32; 2], - pub r: [f32; 2], - pub rot: f32, - pub lum: f32, - pub pat: usize, -} - -pub(crate) const BLENDS: &[&str] = &["Max", "Add", "Alpha over"]; - -/// Renders `items` over black. Item `i` covers the rotated box ±`r` around its center, where -/// `pat(i, x, y)` is its pattern (0..1) at local coordinates -1..1. Items are binned on a grid about -/// their size so a pixel only tests its neighbours; later items draw on top (Alpha over). -pub(crate) fn splat(ctx: &Ctx, items: &[Inst], blend: i32, pat: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image { - let valid = |it: &Inst| it.r[0] > 1e-6 && it.r[1] > 1e-6 && it.c.iter().chain(&it.r).all(|v| v.is_finite()); - let n = items.iter().filter(|it| valid(it)).count().max(1); - let mean_r = items.iter().filter(|it| valid(it)).map(|it| it.r[0].max(it.r[1])).sum::<f32>() / n as f32; - let g = ((0.5 / mean_r.max(1e-4)) as usize).clamp(1, 256); - let gf = g as f32; - let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g]; - for (i, it) in items.iter().enumerate().filter(|(_, it)| valid(it)) { - let br = it.r[0].max(it.r[1]) * SQRT_2; - // At most one full turn of bins per axis, so no item lands twice in a bin. - let span = |c: f32| { - let a = ((c - br) * gf).floor() as i64; - (a, (((c + br) * gf).floor() as i64).min(a + g as i64 - 1)) - }; - let ((x0, x1), (y0, y1)) = (span(it.c[0]), span(it.c[1])); - for gy in y0..=y1 { - for gx in x0..=x1 { - if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) { - b.push(i as u32); - } - } - } - } - let rots: Vec<(f32, f32)> = items.iter().map(|it| (-it.rot * TAU).sin_cos()).collect(); - let tile = ctx.tile; - Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let mut acc = 0.0f32; - let bin = bins.get(((v * gf) as usize).min(g - 1) * g + ((u * gf) as usize).min(g - 1)); - for &i in bin.into_iter().flatten() { - let (Some(it), Some(&(s, c))) = (items.get(i as usize), rots.get(i as usize)) else { continue }; - let (mut dx, mut dy) = (u - it.c[0], v - it.c[1]); - if tile { - dx -= dx.round(); - dy -= dy.round(); - } - let (x, y) = ((dx * c - dy * s) / it.r[0], (dx * s + dy * c) / it.r[1]); - if x.abs() > 1.0 || y.abs() > 1.0 { - continue; - } - let p = pat(i as usize, x, y); - if p <= 0.0 { - continue; - } - acc = match blend { - 1 => acc + p * it.lum, - 2 => acc + (it.lum - acc) * p.min(1.0), - _ => acc.max(p * it.lum), - }; - } - [acc, 0.0, 0.0, 0.0] - }) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("fx_map", "FX-Map", ATOMIC) - .desc( - "Instances up to three patterns on a grid, at random positions or in a random quadtree, with per-instance scale, rotation, \ - position and luminance jitter. Scale 1 fills an instance's cell. Unconnected: soft discs. Tiles.", - ) - .atomic() - .generator() - .gray_in("pattern0", "Pattern 0") - .gray_in("pattern1", "Pattern 1") - .gray_in("pattern2", "Pattern 2") - .choice("mode", "Mode", &["Grid", "Random", "Quadtree"], 2) - .int("count", "Count (random)", 64, 1, 20000) - .int("x_amount", "X amount", 4, 1, 256) - .int("y_amount", "Y amount", 4, 1, 256) - .int("subdivisions", "Subdivisions (quadtree)", 3, 0, 8) - .float("split_chance", "Subdivide chance", 0.5, 0.0, 1.0) - .float("scale", "Scale", 0.9, 0.0, 2.0) - .float("scale_random", "Scale random", 0.2, 0.0, 1.0) - .angle("rotation", "Rotation", 0.0) - .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) - .float("position_random", "Position random", 0.0, 0.0, 1.0) - .float("luminance", "Luminance", 1.0, 0.0, 1.0) - .float("luminance_random", "Luminance random", 0.4, 0.0, 1.0) - .float("pattern_random", "Pattern random", 1.0, 0.0, 1.0) - .choice("blending", "Blending", BLENDS, 0) - .int("seed_offset", "Seed offset", 0, 0, 10000) - .gray_out() - .cook(fx_map), - node("shape_splatter", "Shape Splatter", PATTERNS) - .desc("Scatters the pattern input (or a shape) with random scale, rotation and luminance; the mask input sets where instances land.") - .generator() - .gray_in("pattern", "Pattern") - .gray_in("mask", "Mask") - .choice("shape", "Shape (no input)", SHAPES, 3) - .int("count", "Count", 300, 1, 20000) - .float("size", "Size", 0.05, 0.0, 1.0) - .float("size_random", "Size random", 0.5, 0.0, 1.0) - .float("rotation_random", "Rotation random", 1.0, 0.0, 1.0) - .float("luminance_random", "Luminance random", 0.4, 0.0, 1.0) - .choice("blending", "Blending", BLENDS, 0) - .gray_out() - .cook(shape_splatter), - ] -} - -/// A connected pattern at local `(x, y)` (-1..1), or a soft disc when there is none. -pub(crate) fn sample_pattern(pats: &[Image], k: usize, x: f32, y: f32) -> f32 { - match pats.get(k) { - Some(img) => img.sample_gray((x + 1.0) * 0.5, (y + 1.0) * 0.5, false), - None => shape(3, x, y), - } -} - -/// Cells of a random quadtree over an `nx × ny` root grid: (center, size, key). A cell splits -/// with probability `chance` until `depth`. -fn quadtree(nx: i32, ny: i32, depth: i32, chance: f32, seed: u32) -> Vec<([f32; 2], [f32; 2], u32)> { - const MAX_CELLS: usize = 1 << 18; - let mut out = Vec::new(); - let mut stack: Vec<([f32; 2], [f32; 2], i32, u32)> = Vec::new(); - for j in (0..ny).rev() { - for i in (0..nx).rev() { - let size = [1.0 / nx as f32, 1.0 / ny as f32]; - stack.push(([i as f32 * size[0], j as f32 * size[1]], size, 0, hash((j * nx + i) as u32 ^ 0x5157_0000))); - } - } - while let Some((p, s, lvl, key)) = stack.pop() { - if lvl < depth && rand1(key, seed ^ 0x51ed) < chance && out.len() + stack.len() + 4 <= MAX_CELLS { - let h = [s[0] * 0.5, s[1] * 0.5]; - for q in (0..4u32).rev() { - let o = [p[0] + (q & 1) as f32 * h[0], p[1] + (q >> 1) as f32 * h[1]]; - stack.push((o, h, lvl + 1, hash(key.wrapping_mul(4).wrapping_add(q + 1)))); - } - } else { - out.push(([p[0] + s[0] * 0.5, p[1] + s[1] * 0.5], s, key)); - } - } - out -} - -/// The instances an FX-Map places (separate from rendering, so it can be tested). -pub(crate) fn fx_instances(ctx: &Ctx, n_patterns: usize) -> Vec<Inst> { - let seed = ctx.seed.wrapping_add(ctx.i("seed_offset") as u32); - let (nx, ny) = (ctx.i("x_amount").clamp(1, 256), ctx.i("y_amount").clamp(1, 256)); - let cells: Vec<([f32; 2], [f32; 2], u32)> = match ctx.i("mode") { - 0 => (0..ny) - .flat_map(|j| { - (0..nx).map(move |i| ([(i as f32 + 0.5) / nx as f32, (j as f32 + 0.5) / ny as f32], [1.0 / nx as f32, 1.0 / ny as f32], (j * nx + i) as u32)) - }) - .collect(), - 1 => { - let count = ctx.i("count").clamp(1, 20000) as u32; - let side = 1.0 / (count as f32).sqrt(); - (0..count).map(|i| ([rand1(i * 2, seed ^ 0xa11), rand1(i * 2 + 1, seed ^ 0xa11)], [side, side], i)).collect() - } - _ => quadtree(nx, ny, ctx.i("subdivisions").clamp(0, 8), ctx.f("split_chance"), seed), - }; - let (sc, sr, rot, rr, pr) = (ctx.f("scale"), ctx.f("scale_random"), ctx.f("rotation"), ctx.f("rotation_random"), ctx.f("position_random")); - let (lum, lr, patr) = (ctx.f("luminance"), ctx.f("luminance_random"), ctx.f("pattern_random")); - let n = n_patterns.max(1); - cells - .into_iter() - .map(|(c, size, key)| { - let r = |k: u32| rand1(key.wrapping_mul(8).wrapping_add(k), seed); - let s = sc * (1.0 - sr * r(2)); - Inst { - c: [c[0] + (r(0) - 0.5) * pr * size[0], c[1] + (r(1) - 0.5) * pr * size[1]], - r: [size[0] * 0.5 * s, size[1] * 0.5 * s], - rot: rot + (r(3) - 0.5) * rr, - lum: lum * (1.0 - lr * r(4)), - pat: if r(5) < patr { ((r(6) * n as f32) as usize).min(n - 1) } else { 0 }, - } - }) - .collect() -} - -fn fx_map(ctx: &Ctx) -> CookResult { - let pats: Vec<Image> = (0..3).filter_map(|i| ctx.input(i).map(Image::to_gray)).collect(); - let items = fx_instances(ctx, pats.len()); - Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| sample_pattern(&pats, items.get(i).map_or(0, |it| it.pat), x, y))]) -} - -fn shape_splatter(ctx: &Ctx) -> CookResult { - let pats: Vec<Image> = ctx.input(0).map(Image::to_gray).into_iter().collect(); - let mask = ctx.input(1); - let (k, s) = (ctx.i("shape"), ctx.seed); - let (size, sr, rr, lr) = (ctx.f("size"), ctx.f("size_random"), ctx.f("rotation_random"), ctx.f("luminance_random")); - let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 20000) as u32) - .filter_map(|i| { - let r = |k: u32| rand1(i * 8 + k, s); - let c = [r(0), r(1)]; - // Instances land where the mask is bright: kept with probability = mask value. - if mask.is_some_and(|m| r(2) >= m.sample_gray(c[0], c[1], ctx.tile)) { - return None; - } - let rad = size * (1.0 - sr * r(3)); - Some(Inst { c, r: [rad, rad], rot: (r(4) - 0.5) * rr, lum: 1.0 - lr * r(5), pat: 0 }) - }) - .collect(); - Ok(vec![splat(ctx, &items, ctx.i("blending"), |_, x, y| if pats.is_empty() { shape(k, x, y) } else { sample_pattern(&pats, 0, x, y) })]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use materialcraft_core::Value; - - use super::*; - use crate::catalog::{find, resolve_params}; - - fn with(params: &[(&str, Value)], f: impl FnOnce(&Ctx)) { - let def = find("fx_map").unwrap(); - let mut p = resolve_params(def, &BTreeMap::new()); - for (k, v) in params { - p.insert(k.to_string(), v.clone()); - } - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = [None, None, None]; - f(&Ctx { w: 64, h: 64, seed: 3, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars }); - } - - #[test] - fn fx_map_instance_counts() { - with(&[("mode", Value::Enum(0)), ("x_amount", Value::Int(5)), ("y_amount", Value::Int(3))], |c| assert_eq!(fx_instances(c, 1).len(), 15)); - with(&[("mode", Value::Enum(1)), ("count", Value::Int(77))], |c| assert_eq!(fx_instances(c, 1).len(), 77)); - let quad = |chance: f32, depth: i32| { - let mut n = 0; - with( - &[ - ("mode", Value::Enum(2)), - ("x_amount", Value::Int(2)), - ("y_amount", Value::Int(1)), - ("subdivisions", Value::Int(depth)), - ("split_chance", Value::Float(chance)), - ], - |c| n = fx_instances(c, 1).len(), - ); - n - }; - assert_eq!(quad(0.0, 3), 2); - assert_eq!(quad(1.0, 3), 2 * 64); - let some = quad(0.5, 4); - assert!(some > 2 && some < 2 * 256, "{some}"); - } - - #[test] - fn fx_map_is_deterministic_per_seed() { - let cook = |off: i32| { - let mut img = None; - with(&[("seed_offset", Value::Int(off))], |c| img = Some(fx_map(c).unwrap().remove(0))); - img.unwrap() - }; - assert_eq!(cook(0), cook(0)); - assert_ne!(cook(0), cook(1)); - assert!(cook(0).mean()[0] > 0.05); - } -} diff --git a/_to_delete/nodes_generators.rs b/_to_delete/nodes_generators.rs deleted file mode 100644 index 5fb15df..0000000 --- a/_to_delete/nodes_generators.rs +++ /dev/null @@ -1,419 +0,0 @@ -//! Texture generators › Noises. All tile seamlessly: lattice scales are whole numbers of cells. - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::noise::{self, cellular, fbm, perlin, rand2, ridged, value, value_xy}; -use crate::ops; - -pub const NOISES: &str = "Texture generators/Noises"; - -fn scale(ctx: &Ctx) -> f32 { - ctx.f("scale").max(1.0).round() -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let n = |id, label| node(id, label, NOISES).generator(); - vec![ - n("anisotropic_noise", "Anisotropic Noise") - .desc("Streaks of value noise stretched along one axis.") - .float("scale", "X amount", 4.0, 1.0, 64.0) - .float("scale_y", "Y amount", 64.0, 1.0, 512.0) - .float("smoothness", "Smoothness", 0.5, 0.0, 1.0) - .float("interpolation", "Interpolation", 1.0, 0.0, 1.0) - .gray_out() - .cook(anisotropic), - n("bnw_spots_1", "BnW Spots 1") - .desc("Contrasted black and white spots.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(bnw1), - n("bnw_spots_2", "BnW Spots 2") - .desc("Rounder black and white spots.") - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.3, 0.0, 1.0) - .gray_out() - .cook(bnw2), - n("bnw_spots_3", "BnW Spots 3") - .desc("Fine black and white speckles.") - .float("scale", "Scale", 16.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.6, 0.0, 1.0) - .gray_out() - .cook(bnw3), - n("cells_1", "Cells 1") - .desc("Distance to the nearest cell point (soft bumps).") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells1), - n("cells_2", "Cells 2") - .desc("Cell borders (second minus first distance).") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells2), - n("cells_3", "Cells 3") - .desc("Flat cells, each a random gray.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells3), - n("cells_4", "Cells 4") - .desc("Chebyshev cells: square bumps.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells4), - n("clouds_1", "Clouds 1") - .desc("Soft fractal clouds.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(clouds1), - n("clouds_2", "Clouds 2") - .desc("Warped, wispy clouds.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.55, 0.0, 1.0) - .gray_out() - .cook(clouds2), - n("clouds_3", "Clouds 3") - .desc("Detailed, contrasted clouds.") - .float("scale", "Scale", 6.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.6, 0.0, 1.0) - .gray_out() - .cook(clouds3), - n("creased", "Creased") - .desc("Ridged fractal noise: folds and creases.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.55, 0.0, 1.0) - .float("warp", "Warp intensity", 0.3, 0.0, 1.0) - .gray_out() - .cook(creased), - n("crystal_1", "Crystal 1").desc("Faceted crystal plates.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal1), - n("crystal_2", "Crystal 2").desc("Sharp crystal shards.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal2), - n("dirt", "Dirt").desc("Clumps of dirt.").float("scale", "Scale", 6.0, 1.0, 64.0).float("density", "Density", 0.5, 0.0, 1.0).gray_out().cook(dirt), - n("dust", "Dust").desc("Sparse specks of dust.").float("density", "Density", 0.02, 0.0, 0.2).float("size", "Size", 1.0, 0.0, 8.0).gray_out().cook(dust), - n("fractal_sum_base", "Fractal Sum Base") - .desc("Sum of Perlin noise octaves.") - .float("scale", "Min level", 2.0, 1.0, 64.0) - .int("octaves", "Octaves", 8, 1, 12) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(fractal_sum), - n("fur", "Fur") - .desc("Short directional fibers.") - .float("scale", "Density", 1.0, 0.1, 4.0) - .angle("angle", "Direction", 0.25) - .float("length", "Length", 8.0, 0.0, 64.0) - .gray_out() - .cook(fur), - n("gaussian_noise", "Gaussian Noise") - .desc("Smoothly interpolated value noise.") - .float("scale", "Scale", 16.0, 1.0, 256.0) - .gray_out() - .cook(gaussian_noise), - n("grunge_map_1", "Grunge Map 1") - .desc("Stains and blotches.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(grunge1), - n("grunge_map_2", "Grunge Map 2") - .desc("Speckled grime.") - .float("scale", "Scale", 5.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(grunge2), - n("grunge_map_3", "Grunge Map 3") - .desc("Streaky leaks.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(grunge3), - n("liquid", "Liquid") - .desc("Domain-warped flowing noise.") - .float("scale", "Scale", 3.0, 1.0, 32.0) - .float("warp", "Warp", 0.6, 0.0, 2.0) - .gray_out() - .cook(liquid), - n("moisture_noise", "Moisture Noise") - .desc("Damp patches with soft edges.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() - .cook(moisture), - n("perlin_noise", "Perlin Noise") - .desc("Single-octave gradient noise.") - .float("scale", "Scale", 8.0, 1.0, 256.0) - .float("disorder", "Disorder", 0.0, 0.0, 1.0) - .gray_out() - .cook(perlin_noise), - n("plasma", "Plasma").desc("Interfering sine waves through noise.").float("scale", "Scale", 4.0, 1.0, 32.0).gray_out().cook(plasma), - n("turbulence", "Turbulence") - .desc("Billowing absolute-value fractal noise.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(turbulence), - n("voronoi", "Voronoi") - .desc("Cellular noise with a choice of distance and output.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .choice("metric", "Distance", &["Euclidean", "Manhattan", "Chebyshev"], 0) - .choice("style", "Output", &["F1", "F2", "F2 - F1", "Cell id"], 2) - .gray_out() - .cook(voronoi), - n("white_noise", "White Noise").desc("Independent random value per pixel.").choice("mode", "Output", &["Grayscale", "Color"], 0).cook(white_noise), - ] -} - -fn anisotropic(ctx: &Ctx) -> CookResult { - let (sx, sy) = (scale(ctx), ctx.f("scale_y").max(1.0).round()); - let smooth = ctx.f("smoothness"); - let s = ctx.seed; - let base = ctx.gen_gray(|u, v| { - let a = value_xy(u * sx, v * sy, sx as i32, sy as i32, s); - let b = value_xy(u * sx * 2.0, v * sy, (sx * 2.0) as i32, sy as i32, s ^ 77) * 0.5; - (a * 0.75 + b * 0.25 * (1.0 - smooth) + 0.125 * smooth).clamp(0.0, 1.0) - }); - Ok(vec![if smooth > 0.0 { ops::gaussian(&base, smooth * 2.0, ctx.tile) } else { base }]) -} - -fn contrast(v: f32, c: f32) -> f32 { - ((v - 0.5) * (1.0 + c * 8.0) + 0.5).clamp(0.0, 1.0) -} - -fn bnw1(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 6, 0.3 + r * 0.4, s), 0.6))]) -} - -fn bnw2(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 3, 0.3 + r * 0.4, s), 1.2))]) -} - -fn bnw3(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 7, 0.4 + r * 0.4, s), 0.9))]) -} - -fn cell_cook(ctx: &Ctx, metric: u32, f: impl Fn(noise::Cell) -> f32 + Sync) -> CookResult { - let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| f(cellular(u * sc, v * sc, sc as i32, dis, metric, s)).clamp(0.0, 1.0))]) -} - -fn cells1(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 0, |c| 1.0 - c.f1 * 1.2) -} - -fn cells2(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 0, |c| ((c.f2 - c.f1) * 2.5).min(1.0)) -} - -fn cells3(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 0, |c| c.id) -} - -fn cells4(ctx: &Ctx) -> CookResult { - cell_cook(ctx, 2, |c| 1.0 - c.f1 * 1.6) -} - -fn crystal1(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, 1.0, 0, s); - (c.id * 0.6 + (c.f2 - c.f1).min(0.4) + 0.1).clamp(0.0, 1.0) - })]) -} - -fn crystal2(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, 1.0, 1, s); - (c.id * 0.7 + (1.0 - c.f1).max(0.0) * 0.3).clamp(0.0, 1.0) - })]) -} - -fn dirt(ctx: &Ctx) -> CookResult { - let (sc, d, s) = (scale(ctx), ctx.f("density"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let base = fbm(u, v, sc, 6, 0.55, s); - let spots = 1.0 - cellular(u * sc * 4.0, v * sc * 4.0, (sc * 4.0) as i32, 1.0, 0, s ^ 9).f1; - let t = 1.0 - d; - (((base * 0.7 + spots * 0.3) - t * 0.6) * 3.0).clamp(0.0, 1.0) - })]) -} - -fn dust(ctx: &Ctx) -> CookResult { - let (d, s) = (ctx.f("density"), ctx.seed); - let img = Image::gray(ctx.w, ctx.h, |x, y| if noise::rand2(x as i32, y as i32, s) < d { 0.5 + 0.5 * noise::rand2(y as i32, x as i32, s ^ 3) } else { 0.0 }); - let sigma = ctx.f("size") * ctx.w as f32 / 1024.0; - let b = ops::gaussian(&img, sigma, ctx.tile); - let gain = 1.0 + sigma * sigma * 4.0; - Ok(vec![b.map(Kind::Gray, |p| [(p[0] * gain).min(1.0), 0.0, 0.0, 0.0])]) -} - -fn fractal_sum(ctx: &Ctx) -> CookResult { - let (sc, o, r, s) = (scale(ctx), ctx.i("octaves").clamp(1, 12) as u32, ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, o, r, s))]) -} - -fn fur(ctx: &Ctx) -> CookResult { - let s = ctx.seed; - let density = ctx.f("scale").clamp(0.1, 4.0); - let img = Image::gray(ctx.w, ctx.h, |x, y| { - let r = rand2(x as i32, y as i32, s); - if r < 0.15 * density { rand2(y as i32, x as i32, s ^ 5) } else { 0.0 } - }); - let len = ctx.f("length") * ctx.w as f32 / 256.0; - let (dx, dy) = ((ctx.f("angle") * std::f32::consts::TAU).cos(), -(ctx.f("angle") * std::f32::consts::TAU).sin()); - let n = (len.ceil() as i32).clamp(1, 256); - let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32); - Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let mut acc = 0.0; - for i in 0..=n { - let t = i as f32 / n as f32 * len; - acc += img.sample_nearest(u - dx * t * iw, v - dy * t * ih, ctx.tile)[0] * (1.0 - i as f32 / (n + 1) as f32); - } - [(acc * 2.5 / (n as f32).sqrt()).min(1.0), 0.0, 0.0, 0.0] - })]) -} - -fn gaussian_noise(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let a = value(u * sc, v * sc, sc as i32, s); - let b = value(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 1); - (a * 0.7 + b * 0.3).clamp(0.0, 1.0) - })]) -} - -fn grunge(ctx: &Ctx, f: impl Fn(f32, f32, f32, u32) -> f32 + Sync) -> CookResult { - let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(f(u, v, sc, s), c))]) -} - -fn grunge1(ctx: &Ctx) -> CookResult { - grunge(ctx, |u, v, sc, s| { - let a = fbm(u, v, sc, 7, 0.6, s); - let b = 1.0 - cellular(u * sc * 3.0, v * sc * 3.0, (sc * 3.0) as i32, 1.0, 0, s ^ 4).f1; - a * 0.75 + b * 0.25 - }) -} - -fn grunge2(ctx: &Ctx) -> CookResult { - grunge(ctx, |u, v, sc, s| { - let a = fbm(u, v, sc, 8, 0.65, s); - let speck = if rand2((u * 512.0) as i32, (v * 512.0) as i32, s ^ 8) > 0.9 { 0.25 } else { 0.0 }; - (a - speck).clamp(0.0, 1.0) - }) -} - -fn grunge3(ctx: &Ctx) -> CookResult { - grunge(ctx, |u, v, sc, s| { - // Whole cell counts per axis (and the matching periods) so both edges tile. - let cy = (sc * 0.5).round().max(1.0); - let streak = value_xy(u * sc * 8.0, v * cy, (sc * 8.0) as i32, cy as i32, s); - let a = fbm(u, v, sc, 6, 0.55, s ^ 2); - streak * 0.5 + a * 0.5 - }) -} - -fn liquid(ctx: &Ctx) -> CookResult { - let (sc, w, s) = (scale(ctx), ctx.f("warp"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = fbm(u, v, sc, 4, 0.5, s) - 0.5; - let qy = fbm(u + 0.37, v + 0.71, sc, 4, 0.5, s ^ 3) - 0.5; - fbm(u + qx * w, v + qy * w, sc, 5, 0.5, s ^ 7) - })]) -} - -fn moisture(ctx: &Ctx) -> CookResult { - let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let a = fbm(u, v, sc, 6, 0.5, s); - let b = (perlin(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 6)).abs(); - contrast(a * 0.8 + (1.0 - b) * 0.2, c) - })]) -} - -fn perlin_noise(ctx: &Ctx) -> CookResult { - let (sc, d, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let (wu, wv) = if d > 0.0 { ((perlin(u * 3.0, v * 3.0, 3, s ^ 1)) * d * 0.1, (perlin(u * 3.0, v * 3.0, 3, s ^ 2)) * d * 0.1) } else { (0.0, 0.0) }; - (perlin((u + wu) * sc, (v + wv) * sc, sc as i32, s) * 0.5 + 0.5).clamp(0.0, 1.0) - })]) -} - -fn plasma(ctx: &Ctx) -> CookResult { - let (sc, s) = (scale(ctx), ctx.seed); - let tau = std::f32::consts::TAU; - Ok(vec![ctx.gen_gray(|u, v| { - let n = fbm(u, v, sc, 3, 0.5, s) * 2.0; - let a = (u * tau * sc + n * 3.0).sin() + (v * tau * sc + n * 2.0).sin() + ((u + v) * tau * sc.round() + n).sin(); - (a / 6.0 + 0.5).clamp(0.0, 1.0) - })]) -} - -fn turbulence(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - // A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN. - Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())]) -} - -fn creased(ctx: &Ctx) -> CookResult { - let (sc, r, w, s) = (scale(ctx), ctx.f("roughness"), ctx.f("warp"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = fbm(u, v, sc, 3, 0.5, s ^ 11) - 0.5; - ridged(u + q * w * 0.3, v - q * w * 0.3, sc, 6, r, s) - })]) -} - -fn clouds1(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, 8, r, s))]) -} - -fn clouds2(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5; - fbm(u + q * 0.35, v + q * 0.35, sc, 8, r, s) - })]) -} - -fn clouds3(ctx: &Ctx) -> CookResult { - let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 9, r, s), 0.35))]) -} - -fn voronoi(ctx: &Ctx) -> CookResult { - let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); - let (metric, style) = (ctx.i("metric").clamp(0, 2) as u32, ctx.i("style")); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, dis, metric, s); - match style { - 0 => c.f1.min(1.0), - 1 => (c.f2 * 0.8).min(1.0), - 3 => c.id, - _ => ((c.f2 - c.f1) * 2.0).min(1.0), - } - })]) -} - -fn white_noise(ctx: &Ctx) -> CookResult { - let s = ctx.seed; - Ok(vec![if ctx.i("mode") == 1 { - Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - [rand2(x as i32, y as i32, s), rand2(x as i32, y as i32, s ^ 1), rand2(x as i32, y as i32, s ^ 2), 1.0] - }) - } else { - Image::gray(ctx.w, ctx.h, |x, y| rand2(x as i32, y as i32, s)) - }]) -} - -#[cfg(test)] -#[path = "generators.test.rs"] -mod tests; diff --git a/_to_delete/nodes_generators.test.rs b/_to_delete/nodes_generators.test.rs deleted file mode 100644 index adc0238..0000000 --- a/_to_delete/nodes_generators.test.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Tiling tests for generators whose cell counts differ per axis. - -use std::collections::BTreeMap; - -use materialcraft_core::Value; -use materialcraft_image::Image; - -use crate::{Ctx, find, resolve_params}; - -fn cook(id: &str, scale: f32, extra: &[(&str, Value)]) -> Image { - let def = find(id).unwrap(); - let mut over: BTreeMap<String, Value> = extra.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(); - over.insert("scale".into(), Value::Float(scale)); - let params = resolve_params(def, &over); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = vec![None; def.inputs.len()]; - let ctx = Ctx { w: 64, h: 64, seed: 5, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap().remove(0) -} - -/// Wrap jump along both axes versus the typical neighbour difference. -fn seams(img: &Image) -> (f32, f32, f32, f32) { - let (mut hs, mut hi, mut vs, mut vi) = (0.0f32, 0.0f32, 0.0f32, 0.0f32); - for k in 0..64 { - hs += (img.get(63, k, false)[0] - img.get(0, k, false)[0]).abs(); - hi += (img.get(31, k, false)[0] - img.get(32, k, false)[0]).abs(); - vs += (img.get(k, 63, false)[0] - img.get(k, 0, false)[0]).abs(); - vi += (img.get(k, 31, false)[0] - img.get(k, 32, false)[0]).abs(); - } - (hs, hi, vs, vi) -} - -#[test] -fn grunge_map_3_tiles_at_odd_scales() { - for scale in [3.0, 5.0, 7.0] { - let (hs, hi, vs, vi) = seams(&cook("grunge_map_3", scale, &[])); - assert!(hs <= hi * 3.0 + 0.5, "scale {scale}: horizontal seam {hs} vs {hi}"); - assert!(vs <= vi * 3.0 + 0.5, "scale {scale}: vertical seam {vs} vs {vi}"); - } -} - -#[test] -fn anisotropic_noise_tiles_with_different_axis_scales() { - let (hs, hi, vs, vi) = seams(&cook("anisotropic_noise", 8.0, &[("scale_y", Value::Float(3.0))])); - assert!(hs <= hi * 3.0 + 0.5, "horizontal seam {hs} vs {hi}"); - assert!(vs <= vi * 3.0 + 0.5, "vertical seam {vs} vs {vi}"); -} diff --git a/_to_delete/nodes_material.rs b/_to_delete/nodes_material.rs deleted file mode 100644 index 8825290..0000000 --- a/_to_delete/nodes_material.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Material filters: nodes that make or process whole PBR materials (several outputs). - -use materialcraft_image::{Image, Kind, linear_to_srgb, srgb_to_linear}; - -use crate::atomic::height_to_normal; -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::ops; - -const PBR: &str = "Material filters/PBR utilities"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("pbr_base_material", "PBR Base Material", PBR) - .desc("A uniform PBR material: base color, normal, roughness, metallic, height and ambient occlusion.") - .generator() - .color("base_color", "Base color", [0.5, 0.5, 0.5, 1.0]) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("metallic", "Metallic", 0.0, 0.0, 1.0) - .float("height", "Height", 0.5, 0.0, 1.0) - .float("ao", "Ambient occlusion", 1.0, 0.0, 1.0) - .output("base_color", "Base color", PortKind::Color) - .output("normal", "Normal", PortKind::Color) - .output("roughness", "Roughness", PortKind::Gray) - .output("metallic", "Metallic", PortKind::Gray) - .output("height", "Height", PortKind::Gray) - .output("ambient_occlusion", "Ambient occlusion", PortKind::Gray) - .cook(pbr_base), - node("height_normal_ao", "Height to Normal and AO", PBR) - .desc("A normal map and an ambient occlusion map from one height map.") - .gray_in("height", "Height") - .float("normal_intensity", "Normal intensity", 1.0, 0.0, 10.0) - .float("ao_spread", "AO spreading", 0.15, 0.0, 1.0) - .float("ao_depth", "AO depth", 0.5, 0.0, 1.0) - .output("normal", "Normal", PortKind::Color) - .output("ambient_occlusion", "Ambient occlusion", PortKind::Gray) - .cook(height_normal_ao), - node("albedo_safe", "Albedo Safe Color", PBR) - .desc("Keeps base colors inside the physically plausible range (sRGB 30-240).") - .color_in("input", "Base color") - .color_out() - .cook(albedo_safe), - node("metallic_mask", "Metallic From Mask", PBR) - .desc("Turns a mask into a clean metallic map (fully metallic or not).") - .gray_in("input", "Mask") - .float("threshold", "Threshold", 0.5, 0.0, 1.0) - .gray_out() - .cook(metallic_mask), - ] -} - -fn pbr_base(ctx: &Ctx) -> CookResult { - let (w, h) = (ctx.w, ctx.h); - let g = |v: f32| Image::filled(w, h, Kind::Gray, [v; 4]); - Ok(vec![ - Image::filled(w, h, Kind::Color, ctx.v4("base_color")), - Image::filled(w, h, Kind::Color, [0.5, 0.5, 1.0, 1.0]), - g(ctx.f("roughness")), - g(ctx.f("metallic")), - g(ctx.f("height")), - g(ctx.f("ao")), - ]) -} - -fn height_normal_ao(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.5); - let n = height_to_normal(&h, ctx.f("normal_intensity") * ctx.w as f32 / 32.0, false, ctx.tile, false); - let spread = ctx.f("ao_spread").max(0.001) * ctx.w as f32 * 0.25; - let wide = ops::gaussian(&h, spread, ctx.tile); - let depth = ctx.f("ao_depth"); - let ao = Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { - let i = (y * ctx.w + x) as usize; - [(1.0 - (wide.data[i] - h.data[i]).max(0.0) * depth * 6.0).clamp(0.0, 1.0), 0.0, 0.0, 0.0] - }); - Ok(vec![n, ao]) -} - -fn albedo_safe(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let (lo, hi) = (30.0 / 255.0, 240.0 / 255.0); - Ok(vec![img.map(Kind::Color, |p| { - let f = |v: f32| srgb_to_linear(linear_to_srgb(v).clamp(lo, hi)); - [f(p[0]), f(p[1]), f(p[2]), p[3]] - })]) -} - -fn metallic_mask(ctx: &Ctx) -> CookResult { - let t = ctx.f("threshold"); - let img = ctx.gray_or(0, 0.0); - Ok(vec![img.map(Kind::Gray, |p| [if p[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])]) -} diff --git a/_to_delete/nodes_material_more.rs b/_to_delete/nodes_material_more.rs deleted file mode 100644 index 6206b35..0000000 --- a/_to_delete/nodes_material_more.rs +++ /dev/null @@ -1,274 +0,0 @@ -//! More material filters: blending whole PBR materials (by mask or by height), weathering masks -//! (edge wear, dirt, dust) and base color utilities. - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{B, CookResult, Ctx, NodeDef, PortKind, node}; -use crate::filters_more::{pack, unpack}; -use crate::noise::fbm; -use crate::noises_more::smoothstep; -use crate::ops; - -const MAT_BLEND: &str = "Material filters/Blending"; -const WEATHER: &str = "Material filters/Weathering"; -const PBR: &str = "Material filters/PBR utilities"; - -/// The channels of a blended material: kind and default (unconnected) value. -const KINDS: [(PortKind, [f32; 4]); 5] = [ - (PortKind::Color, [0.5, 0.5, 0.5, 1.0]), - (PortKind::Color, [0.5, 0.5, 1.0, 1.0]), - (PortKind::Gray, [0.5; 4]), - (PortKind::Gray, [0.0; 4]), - (PortKind::Gray, [0.5; 4]), -]; -const IN_1: [(&str, &str); 5] = - [("base_color_1", "Base color 1"), ("normal_1", "Normal 1"), ("roughness_1", "Roughness 1"), ("metallic_1", "Metallic 1"), ("height_1", "Height 1")]; -const IN_2: [(&str, &str); 5] = - [("base_color_2", "Base color 2"), ("normal_2", "Normal 2"), ("roughness_2", "Roughness 2"), ("metallic_2", "Metallic 2"), ("height_2", "Height 2")]; -const OUT: [(&str, &str); 5] = [("base_color", "Base color"), ("normal", "Normal"), ("roughness", "Roughness"), ("metallic", "Metallic"), ("height", "Height")]; - -/// Inputs for two materials, then the blended material's outputs. -fn material_ports(mut b: B) -> B { - for set in [IN_1, IN_2] { - for ((id, label), (kind, _)) in set.into_iter().zip(KINDS) { - b = b.input(id, label, kind); - } - } - for ((id, label), (kind, _)) in OUT.into_iter().zip(KINDS) { - b = b.output(id, label, kind); - } - b -} - -fn kind_of(k: PortKind) -> Kind { - if k == PortKind::Color { Kind::Color } else { Kind::Gray } -} - -/// Material `slot` (0 or 1), channel `c`, at the output size. -fn channel(ctx: &Ctx, slot: usize, c: usize) -> Image { - let (pk, def) = KINDS[c]; - let kind = kind_of(pk); - ctx.any_or(slot * 5 + c, kind, def).to_kind(kind) -} - -/// Blend the two input materials by `t` per pixel (0 = material 1); normals are renormalized. -fn mix_materials(ctx: &Ctx, t: &[f32]) -> Vec<Image> { - (0..5) - .map(|c| { - let (a, b) = (channel(ctx, 0, c), channel(ctx, 1, c)); - Image::generate(ctx.w, ctx.h, a.kind, |x, y| { - let t = t.get((y * ctx.w + x) as usize).copied().unwrap_or(0.0); - let (p, q) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); - let mut o: [f32; 4] = std::array::from_fn(|k| p[k] + (q[k] - p[k]) * t); - if c == 1 { - let (n1, n2) = (unpack(p), unpack(q)); - o = pack(std::array::from_fn(|k| n1[k] + (n2[k] - n1[k]) * t), o[3]); - } - o - }) - }) - .collect() -} - -/// Weathering parameters shared by the mask nodes. -fn weather_params(b: B) -> B { - b.float("amount", "Amount", 0.5, 0.0, 1.0) - .float("noise_scale", "Noise scale", 8.0, 1.0, 64.0) - .float("noise_amount", "Noise amount", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.6, 0.0, 1.0) -} - -/// A weathering mask: `base(i)` (0..1, where the effect belongs) broken up by fractal noise and -/// thresholded by the amount. -fn weather(ctx: &Ctx, base: impl Fn(usize) -> f32 + Sync) -> Image { - let (amt, ns, na, s) = (ctx.f("amount"), ctx.f("noise_scale").max(1.0).round(), ctx.f("noise_amount"), ctx.seed); - let soft = (1.0 - ctx.f("contrast")) * 0.5 + 0.01; - Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let i = ((v * ctx.h as f32) as usize).min((ctx.h as usize).saturating_sub(1)) * ctx.w as usize - + ((u * ctx.w as f32) as usize).min((ctx.w as usize).saturating_sub(1)); - let val = base(i) - 2.0 * na * (1.0 - fbm(u, v, ns, 6, 0.6, s)); - [smoothstep(1.0 - amt - soft, 1.0 - amt + soft, val), 0.0, 0.0, 0.0] - }) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - material_ports(node("material_blend", "Material Blend", MAT_BLEND)) - .desc("Blends two whole PBR materials by a mask (white = material 2).") - .gray_in("mask", "Mask") - .float("opacity", "Opacity", 1.0, 0.0, 1.0) - .cook(material_blend), - material_ports(node("material_height_blend", "Material Height Blend", MAT_BLEND)) - .desc("Blends two whole PBR materials by their heights: the higher one shows, with a soft transition.") - .float("height_offset", "Height offset", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.9, 0.0, 1.0) - .output("mask", "Mask", PortKind::Gray) - .cook(material_height_blend), - weather_params( - node("edge_wear", "Edge Wear", WEATHER) - .desc("A mask of worn, exposed edges from the convex areas of a height map (or a curvature map), broken up by noise.") - .gray_in("height", "Height") - .gray_in("curvature", "Curvature (optional)") - .float("width", "Edge width", 4.0, 0.25, 64.0), - ) - .gray_out() - .cook(edge_wear), - weather_params( - node("dirt_mask", "Dirt Mask", WEATHER) - .desc("A mask of dirt gathering in cavities of a height map (and dark ambient occlusion), broken up by noise.") - .gray_in("height", "Height") - .gray_in("ao", "Ambient occlusion (optional)") - .float("spread", "Spread", 16.0, 0.5, 128.0), - ) - .gray_out() - .cook(dirt_mask), - weather_params( - node("dust_mask", "Dust Mask", WEATHER) - .desc("A mask of dust settling on surfaces facing a direction (from a normal map) and on flat areas.") - .color_in("normal", "Normal") - .angle("direction", "Up direction", 0.25) - .float("flat", "On flat areas", 0.3, 0.0, 1.0), - ) - .gray_out() - .cook(dust_mask), - node("material_color_adjust", "Material Color Adjust", PBR) - .desc("Hue, saturation and value of a base color, optionally through a mask.") - .color_in("input", "Base color") - .gray_in("mask", "Mask") - .float("hue", "Hue", 0.0, -0.5, 0.5) - .float("saturation", "Saturation", 0.0, -1.0, 1.0) - .float("value", "Value", 0.0, -1.0, 1.0) - .color_out() - .cook(material_color_adjust), - node("metal_base_color", "Metal Base Color", PBR) - .desc("The measured base color (linear reflectance) of a common metal, with metallic = 1.") - .generator() - .choice("metal", "Metal", &["Iron", "Silver", "Aluminum", "Gold", "Copper", "Chromium", "Nickel", "Titanium", "Cobalt", "Platinum"], 0) - .output("base_color", "Base color", PortKind::Color) - .output("metallic", "Metallic", PortKind::Gray) - .cook(metal_base_color), - ] -} - -fn material_blend(ctx: &Ctx) -> CookResult { - let op = ctx.f("opacity"); - let m = ctx.gray_or(10, 1.0); - let t: Vec<f32> = m.data.iter().map(|v| (v * op).clamp(0.0, 1.0)).collect(); - Ok(mix_materials(ctx, &t)) -} - -fn material_height_blend(ctx: &Ctx) -> CookResult { - let (h1, h2) = (channel(ctx, 0, 4), channel(ctx, 1, 4)); - let (off, c) = (ctx.f("height_offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999)); - let soft = (1.0 - c) * 0.5 + 1e-4; - let t: Vec<f32> = h1.data.iter().zip(h2.data.iter()).map(|(a, b)| ((b + off - a) / soft * 0.5 + 0.5).clamp(0.0, 1.0)).collect(); - let mut out = mix_materials(ctx, &t); - out.push(ops::gray_from(ctx.w, ctx.h, t)); - Ok(out) -} - -fn edge_wear(ctx: &Ctx) -> CookResult { - let edge: Vec<f32> = match ctx.sized(1) { - Some(c) => c.to_gray().data.iter().map(|v| ((v - 0.5) * 2.0).clamp(0.0, 1.0)).collect(), - None => { - let h = ctx.gray_or(0, 0.0); - let wide = ops::gaussian(&h, ctx.f("width") * ctx.w as f32 / 256.0, ctx.tile); - h.data.iter().zip(wide.data.iter()).map(|(a, b)| ((a - b) * 4.0).clamp(0.0, 1.0)).collect() - } - }; - Ok(vec![weather(ctx, |i| edge.get(i).copied().unwrap_or(0.0))]) -} - -fn dirt_mask(ctx: &Ctx) -> CookResult { - let h = ctx.gray_or(0, 0.0); - let wide = ops::gaussian(&h, ctx.f("spread") * ctx.w as f32 / 256.0, ctx.tile); - let ao = ctx.sized(1).map(|a| a.to_gray()); - let cav: Vec<f32> = (0..h.data.len()) - .map(|i| { - let c = ((wide.data[i] - h.data[i]) * 4.0).clamp(0.0, 1.0); - ao.as_ref().and_then(|a| a.data.get(i)).map_or(c, |a| c.max(1.0 - a)) - }) - .collect(); - Ok(vec![weather(ctx, |i| cav.get(i).copied().unwrap_or(0.0))]) -} - -fn dust_mask(ctx: &Ctx) -> CookResult { - let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color(); - let (s, c) = (ctx.f("direction") * std::f32::consts::TAU).sin_cos(); - let flat = ctx.f("flat"); - let base: Vec<f32> = n - .data - .chunks(4) - .map(|p| { - let v = unpack([p[0], p[1], p[2], 1.0]); - ((v[0] * c + v[1] * s) * 3.0 + flat * ((v[2] - 0.8) * 5.0).max(0.0)).clamp(0.0, 1.0) - }) - .collect(); - Ok(vec![weather(ctx, |i| base.get(i).copied().unwrap_or(0.0))]) -} - -fn material_color_adjust(ctx: &Ctx) -> CookResult { - let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); - let m = ctx.gray_or(1, 1.0); - let (dh, ds, dv) = (ctx.f("hue"), ctx.f("saturation"), ctx.f("value")); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { - let p = img.get(x as i64, y as i64, false); - let t = m.get_gray(x as i64, y as i64, false); - let hsl = ops::rgb_to_hsl(p); - let q = ops::hsl_to_rgb(hsl[0] + dh, (hsl[1] * (1.0 + ds)).clamp(0.0, 1.0), (hsl[2] * (1.0 + dv)).max(0.0)); - [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t, p[3]] - })]) -} - -/// Linear base colors (normal-incidence reflectance) of metals, from published measurements. -const METALS: [[f32; 3]; 10] = [ - [0.560, 0.570, 0.580], - [0.972, 0.960, 0.915], - [0.913, 0.922, 0.924], - [1.000, 0.766, 0.336], - [0.955, 0.638, 0.538], - [0.550, 0.556, 0.554], - [0.660, 0.609, 0.526], - [0.542, 0.497, 0.449], - [0.662, 0.655, 0.634], - [0.672, 0.637, 0.585], -]; - -fn metal_base_color(ctx: &Ctx) -> CookResult { - let c = METALS.get(ctx.i("metal").max(0) as usize).copied().unwrap_or(METALS[0]); - Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, [c[0], c[1], c[2], 1.0]), Image::filled(ctx.w, ctx.h, Kind::Gray, [1.0; 4])]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use materialcraft_image::{Image, Kind}; - - use crate::{Ctx, find, resolve_params}; - - #[test] - fn material_blend_picks_material_2_under_white_mask() { - let def = find("material_blend").unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let red = Image::filled(8, 8, Kind::Color, [1.0, 0.0, 0.0, 1.0]); - let tilted = Image::filled(8, 8, Kind::Color, [0.8, 0.5, 0.9, 1.0]); - let mut inputs = vec![None; def.inputs.len()]; - inputs[5] = Some(red); - inputs[6] = Some(tilted); - inputs[7] = Some(Image::filled(8, 8, Kind::Gray, [0.1; 4])); - inputs[10] = Some(Image::gray(8, 8, |x, _| if x < 4 { 0.0 } else { 1.0 })); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: 8, h: 8, seed: 0, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - let out = (def.cook)(&ctx).unwrap(); - assert_eq!(out.len(), 5); - assert_eq!(out[0].get(6, 2, false), [1.0, 0.0, 0.0, 1.0], "white mask: material 2's base color"); - assert_eq!(out[0].get(1, 2, false), [0.5, 0.5, 0.5, 1.0], "black mask: material 1 (default gray)"); - assert!((out[2].get(6, 2, false)[0] - 0.1).abs() < 1e-6); - let n = out[1].get(6, 2, false); - let len = ((n[0] * 2.0 - 1.0).powi(2) + (n[1] * 2.0 - 1.0).powi(2) + (n[2] * 2.0 - 1.0).powi(2)).sqrt(); - assert!((len - 1.0).abs() < 1e-4, "blended normals are unit length"); - assert!(n[0] > 0.7, "material 2's normal: {n:?}"); - } -} diff --git a/_to_delete/nodes_noise.rs b/_to_delete/nodes_noise.rs deleted file mode 100644 index d1a4af5..0000000 --- a/_to_delete/nodes_noise.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! Tileable noise primitives: integer hashing, value and gradient (Perlin) noise on a periodic -//! lattice, fractal sums and cellular (Worley) noise. Every function takes normalized coordinates -//! (0..1 across the image) and a period in cells, so whole-number scales tile seamlessly. - -/// A 32-bit integer hash (lowbias32 by Chris Wellons, public domain). -#[inline] -pub fn hash(mut x: u32) -> u32 { - x ^= x >> 16; - x = x.wrapping_mul(0x7feb_352d); - x ^= x >> 15; - x = x.wrapping_mul(0x846c_a68b); - x ^= x >> 16; - x -} - -#[inline] -pub fn hash3(x: i32, y: i32, seed: u32) -> u32 { - hash((x as u32).wrapping_mul(0x8da6_b343) ^ hash((y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f))) -} - -/// Uniform 0..1 from a lattice point. -#[inline] -pub fn rand2(x: i32, y: i32, seed: u32) -> f32 { - (hash3(x, y, seed) >> 8) as f32 / (1u32 << 24) as f32 -} - -/// Uniform 0..1 from an index. -#[inline] -pub fn rand1(i: u32, seed: u32) -> f32 { - (hash(i ^ hash(seed.wrapping_add(0x9e37_79b9))) >> 8) as f32 / (1u32 << 24) as f32 -} - -#[inline] -fn fade(t: f32) -> f32 { - t * t * t * (t * (t * 6.0 - 15.0) + 10.0) -} - -#[inline] -fn wrapi(i: i32, p: i32) -> i32 { - if p <= 0 { i } else { i.rem_euclid(p) } -} - -/// Value noise in 0..1, lattice period `p` cells (coordinates already scaled to cells). -pub fn value(x: f32, y: f32, p: i32, seed: u32) -> f32 { - value_xy(x, y, p, p, seed) -} - -/// Value noise in 0..1 with a separate lattice period per axis (`px`, `py` cells), so a noise -/// stretched differently along x and y still tiles. -pub fn value_xy(x: f32, y: f32, px: i32, py: i32, seed: u32) -> f32 { - let (x0, y0) = (x.floor(), y.floor()); - let (tx, ty) = (fade(x - x0), fade(y - y0)); - let (ix, iy) = (x0 as i32, y0 as i32); - let r = |i: i32, j: i32| rand2(wrapi(i, px), wrapi(j, py), seed); - let a = r(ix, iy) + (r(ix + 1, iy) - r(ix, iy)) * tx; - let b = r(ix, iy + 1) + (r(ix + 1, iy + 1) - r(ix, iy + 1)) * tx; - a + (b - a) * ty -} - -/// Gradient (Perlin) noise in about -1..1, lattice period `p` cells. -pub fn perlin(x: f32, y: f32, p: i32, seed: u32) -> f32 { - let (x0, y0) = (x.floor(), y.floor()); - let (fx, fy) = (x - x0, y - y0); - let (ix, iy) = (x0 as i32, y0 as i32); - let g = |i: i32, j: i32, dx: f32, dy: f32| { - let h = hash3(wrapi(i, p), wrapi(j, p), seed); - let a = (h >> 8) as f32 * (std::f32::consts::TAU / (1u32 << 24) as f32); - a.cos() * dx + a.sin() * dy - }; - let (u, v) = (fade(fx), fade(fy)); - let n00 = g(ix, iy, fx, fy); - let n10 = g(ix + 1, iy, fx - 1.0, fy); - let n01 = g(ix, iy + 1, fx, fy - 1.0); - let n11 = g(ix + 1, iy + 1, fx - 1.0, fy - 1.0); - let a = n00 + (n10 - n00) * u; - let b = n01 + (n11 - n01) * u; - (a + (b - a) * v) * std::f32::consts::SQRT_2 -} - -/// Fractal sum of Perlin noise in 0..1: `octaves` layers from `scale` cells, each `lacunarity` -/// (2) times finer and `gain` times weaker. Tileable when `scale` is whole. -pub fn fbm(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 { - let mut sum = 0.0; - let mut amp = 1.0; - let mut norm = 0.0; - let mut s = scale.max(1.0).round(); - for o in 0..octaves.clamp(1, 12) { - sum += perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 1013)) * amp; - norm += amp; - amp *= gain; - s *= 2.0; - } - (sum / norm.max(1e-6)) * 0.5 + 0.5 -} - -/// Ridged (creased) fractal: `1 - |perlin|` layers, 0..1. -pub fn ridged(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 { - let mut sum = 0.0; - let mut amp = 1.0; - let mut norm = 0.0; - let mut s = scale.max(1.0).round(); - for o in 0..octaves.clamp(1, 12) { - let n = 1.0 - perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 7919)).abs(); - sum += n * n * amp; - norm += amp; - amp *= gain; - s *= 2.0; - } - sum / norm.max(1e-6) -} - -/// Result of a cellular lookup: the nearest and second-nearest feature distances (in cells), -/// the nearest feature's random id (0..1) and its position (cells). -#[derive(Clone, Copy, Debug)] -pub struct Cell { - pub f1: f32, - pub f2: f32, - pub id: f32, - pub center: [f32; 2], -} - -/// Worley noise with one jittered feature point per cell (`jitter` 0..1), period `p` cells. -/// `metric`: 0 Euclidean, 1 Manhattan, 2 Chebyshev. -pub fn cellular(x: f32, y: f32, p: i32, jitter: f32, metric: u32, seed: u32) -> Cell { - let (ix, iy) = (x.floor() as i32, y.floor() as i32); - let mut f1 = f32::MAX; - let mut f2 = f32::MAX; - let mut id = 0.0; - let mut center = [0.0, 0.0]; - for j in -2..=2 { - for i in -2..=2 { - let (cx, cy) = (ix + i, iy + j); - let (wx, wy) = (wrapi(cx, p), wrapi(cy, p)); - let px = cx as f32 + 0.5 + (rand2(wx, wy, seed) - 0.5) * jitter; - let py = cy as f32 + 0.5 + (rand2(wx, wy, seed ^ 0x5bd1_e995) - 0.5) * jitter; - let (dx, dy) = (px - x, py - y); - let d = match metric { - 1 => dx.abs() + dy.abs(), - 2 => dx.abs().max(dy.abs()), - _ => (dx * dx + dy * dy).sqrt(), - }; - if d < f1 { - f2 = f1; - f1 = d; - id = rand2(wx, wy, seed ^ 0x2545_f491); - center = [px, py]; - } else if d < f2 { - f2 = d; - } - } - } - Cell { f1, f2, id, center } -} - -/// Gaussian-distributed sample (Box–Muller) from two uniforms. -pub fn gauss(u1: f32, u2: f32) -> f32 { - (-2.0 * u1.max(1e-7).ln()).sqrt() * (std::f32::consts::TAU * u2).cos() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn perlin_tiles_at_its_period() { - for k in 0..20 { - let y = k as f32 * 0.37; - let a = perlin(0.0, y, 4, 7); - let b = perlin(4.0, y, 4, 7); - assert!((a - b).abs() < 1e-5, "{a} {b}"); - } - let a = fbm(0.0, 0.3, 4.0, 5, 0.5, 1); - let b = fbm(1.0, 0.3, 4.0, 5, 0.5, 1); - assert!((a - b).abs() < 1e-4); - } - - #[test] - fn cellular_tiles_and_ranges() { - let a = cellular(0.1, 0.2, 5, 1.0, 0, 3).f1; - let b = cellular(5.1, 0.2, 5, 1.0, 0, 3).f1; - assert!((a - b).abs() < 1e-4); - assert!((0.0..1.5).contains(&a)); - } - - #[test] - fn rand_is_uniformish() { - let m: f32 = (0..10000).map(|i| rand1(i, 9)).sum::<f32>() / 10000.0; - assert!((m - 0.5).abs() < 0.02); - } -} diff --git a/_to_delete/nodes_noise3d.rs b/_to_delete/nodes_noise3d.rs deleted file mode 100644 index a443440..0000000 --- a/_to_delete/nodes_noise3d.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Texture generators › Noises: 3D noises that still tile. Perlin and Worley use a 3D lattice that -//! is periodic in x and y (whole-number scales) and free in z, so scrubbing `z` animates the -//! pattern. The simplex variant samples 4D simplex noise on a flat torus (u and v each mapped to a -//! circle), which tiles at any scale; `z` slides the torus through the 4D field. - -use std::f32::consts::TAU; - -use crate::catalog::{B, CookResult, Ctx, NodeDef, node}; -use crate::generators::NOISES; -use crate::noise::{hash, hash3}; -use crate::noises_more::fractal; - -#[inline] -fn wrap(i: i32, p: i32) -> i32 { - if p <= 0 { i } else { i.rem_euclid(p) } -} - -/// A hash of a 3D lattice point, periodic in x and y. -#[inline] -fn hash_xyz(i: i32, j: i32, k: i32, px: i32, py: i32, seed: u32) -> u32 { - hash(hash3(wrap(i, px), wrap(j, py), seed) ^ (k as u32).wrapping_mul(0x9e37_79b1)) -} - -#[inline] -fn fade(t: f32) -> f32 { - t * t * t * (t * (t * 6.0 - 15.0) + 10.0) -} - -/// 3D gradient (Perlin) noise in about -1..1, periods `px`, `py` cells in x and y. -pub fn perlin3(x: f32, y: f32, z: f32, px: i32, py: i32, seed: u32) -> f32 { - const G: [[f32; 3]; 12] = [ - [1.0, 1.0, 0.0], - [-1.0, 1.0, 0.0], - [1.0, -1.0, 0.0], - [-1.0, -1.0, 0.0], - [1.0, 0.0, 1.0], - [-1.0, 0.0, 1.0], - [1.0, 0.0, -1.0], - [-1.0, 0.0, -1.0], - [0.0, 1.0, 1.0], - [0.0, -1.0, 1.0], - [0.0, 1.0, -1.0], - [0.0, -1.0, -1.0], - ]; - let (x0, y0, z0) = (x.floor(), y.floor(), z.floor()); - let (fx, fy, fz) = (x - x0, y - y0, z - z0); - let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32); - let g = |a: i32, b: i32, c: i32| { - let gr = G[(hash_xyz(ix + a, iy + b, iz + c, px, py, seed) % 12) as usize]; - gr[0] * (fx - a as f32) + gr[1] * (fy - b as f32) + gr[2] * (fz - c as f32) - }; - let (u, v, w) = (fade(fx), fade(fy), fade(fz)); - let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t; - let x00 = lerp(g(0, 0, 0), g(1, 0, 0), u); - let x10 = lerp(g(0, 1, 0), g(1, 1, 0), u); - let x01 = lerp(g(0, 0, 1), g(1, 0, 1), u); - let x11 = lerp(g(0, 1, 1), g(1, 1, 1), u); - lerp(lerp(x00, x10, v), lerp(x01, x11, v), w) -} - -/// Uniform 0..1 from a hash. -#[inline] -fn unit(h: u32) -> f32 { - (h >> 8) as f32 / (1u32 << 24) as f32 -} - -/// 3D Worley noise: nearest and second-nearest feature distances (cells), periodic in x and y. -pub fn worley3(x: f32, y: f32, z: f32, px: i32, py: i32, jitter: f32, seed: u32) -> (f32, f32) { - let (ix, iy, iz) = (x.floor() as i32, y.floor() as i32, z.floor() as i32); - let (mut f1, mut f2) = (f32::MAX, f32::MAX); - for k in -1..=1 { - for j in -1..=1 { - for i in -1..=1 { - let (cx, cy, cz) = (ix + i, iy + j, iz + k); - let h = hash_xyz(cx, cy, cz, px, py, seed); - let o = |s: u32| 0.5 + (unit(hash(h ^ s)) - 0.5) * jitter; - let (dx, dy, dz) = (cx as f32 + o(1) - x, cy as f32 + o(2) - y, cz as f32 + o(3) - z); - let d = (dx * dx + dy * dy + dz * dz).sqrt(); - if d < f1 { - f2 = f1; - f1 = d; - } else if d < f2 { - f2 = d; - } - } - } - } - (f1, f2) -} - -/// 4D simplex noise in about -1..1 (after Gustavson's public description of the algorithm). -pub fn simplex4(p: [f32; 4], seed: u32) -> f32 { - const F4: f32 = 0.309_017; // (√5 − 1) / 4 - const G4: f32 = 0.138_196_6; // (5 − √5) / 20 - let s = (p[0] + p[1] + p[2] + p[3]) * F4; - let i: [f32; 4] = std::array::from_fn(|k| (p[k] + s).floor()); - let t = (i[0] + i[1] + i[2] + i[3]) * G4; - let x0: [f32; 4] = std::array::from_fn(|k| p[k] - (i[k] - t)); - // Rank the coordinates to find the simplex the point is in. - let mut rank = [0i32; 4]; - for a in 0..4 { - for b in a + 1..4 { - if x0[a] > x0[b] { - rank[a] += 1; - } else { - rank[b] += 1; - } - } - } - let ii: [i32; 4] = std::array::from_fn(|k| i[k] as i32); - let mut n = 0.0; - for c in 0..5 { - let off: [i32; 4] = std::array::from_fn(|k| (rank[k] >= 4 - c) as i32); - let x: [f32; 4] = std::array::from_fn(|k| x0[k] - off[k] as f32 + c as f32 * G4); - let t = 0.6 - x.iter().map(|v| v * v).sum::<f32>(); - if t <= 0.0 { - continue; - } - let h = hash(hash3(ii[0] + off[0], ii[1] + off[1], seed) ^ hash3(ii[2] + off[2], ii[3] + off[3], seed ^ 0x68e3_1da4)); - // 32 gradients: one coordinate zero, the other three ±1. - let zero = (h >> 3) as usize & 3; - let mut dot = 0.0; - let mut bit = 0; - for k in 0..4 { - if k != zero { - dot += if h >> bit & 1 == 0 { x[k] } else { -x[k] }; - bit += 1; - } - } - n += t * t * t * t * dot; - } - 27.0 * n -} - -/// Fractal 4D simplex on a torus at `(u, v)`: tiles in u and v for any scale. -fn simplex_torus(u: f32, v: f32, z: f32, scale: f32, octaves: i32, gain: f32, seed: u32) -> f32 { - let (su, cu) = (u * TAU).sin_cos(); - let (sv, cv) = (v * TAU).sin_cos(); - // Circumference `scale` cells per axis. - let r = scale / TAU; - fractal(octaves, gain, |m, o| { - let (r, z) = (r * m, z * m); - let p = [r * cu + z * 0.7, r * su + z * 0.3, r * cv - z * 0.5, r * sv + z * 0.4]; - (simplex4(p, seed.wrapping_add(o * 977)) * 0.5 + 0.5).clamp(0.0, 1.0) - }) -} - -/// Shared noise parameters. -fn noise_params(b: B, scale: f32, octaves: i32) -> B { - b.generator() - .float("scale", "Scale", scale, 1.0, 64.0) - .int("octaves", "Octaves", octaves, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("z", "Z (slice)", 0.0, 0.0, 16.0) - .float("contrast", "Contrast", 0.5, 0.0, 1.0) - .gray_out() -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let n = |id, label| node(id, label, NOISES); - vec![ - noise_params(n("perlin_noise_3d", "Perlin Noise 3D").desc("Fractal 3D gradient noise; Z scrubs through the volume. Tiles."), 4.0, 5) - .cook(perlin_noise_3d), - noise_params( - n("simplex_noise_3d", "Simplex Noise 3D").desc("Fractal simplex noise sampled on a 4D torus; Z moves through it. Tiles at any scale."), - 4.0, - 5, - ) - .cook(simplex_noise_3d), - noise_params( - n("worley_noise_3d", "Worley Noise 3D") - .desc("Cellular noise from 3D feature points; Z scrubs through the cells. Tiles.") - .choice("distance", "Distance", &["F1", "F2", "F2 - F1"], 0) - .float("jitter", "Jitter", 1.0, 0.0, 1.0), - 6.0, - 1, - ) - .cook(worley_noise_3d), - ] -} - -/// Common noise settings: whole-number scale, octaves, gain, z, contrast gain, seed. -fn settings(ctx: &Ctx) -> (f32, i32, f32, f32, f32, u32) { - (ctx.f("scale").max(1.0).round(), ctx.i("octaves"), ctx.f("roughness"), ctx.f("z"), 1.0 + ctx.f("contrast") * 3.0, ctx.seed) -} - -/// Expand around mid gray by `k`. -#[inline] -fn spread(v: f32, k: f32) -> f32 { - ((v - 0.5) * k + 0.5).clamp(0.0, 1.0) -} - -fn perlin_noise_3d(ctx: &Ctx) -> CookResult { - let (s, oct, gain, z, k, seed) = settings(ctx); - Ok(vec![ctx.gen_gray(|u, v| { - let n = fractal(oct, gain, |m, o| { - let p = s * m; - perlin3(u * p, v * p, z * m + o as f32 * 17.31, p as i32, p as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5 - }); - spread(n, k) - })]) -} - -fn simplex_noise_3d(ctx: &Ctx) -> CookResult { - let (_, oct, gain, z, k, seed) = settings(ctx); - let s = ctx.f("scale").max(0.1); - Ok(vec![ctx.gen_gray(|u, v| spread(simplex_torus(u, v, z, s, oct, gain, seed), k))]) -} - -fn worley_noise_3d(ctx: &Ctx) -> CookResult { - let (s, oct, gain, z, k, seed) = settings(ctx); - let (mode, jit) = (ctx.i("distance"), ctx.f("jitter").clamp(0.0, 1.0)); - Ok(vec![ctx.gen_gray(|u, v| { - let n = fractal(oct, gain, |m, o| { - let p = s * m; - let (f1, f2) = worley3(u * p, v * p, z * m, p as i32, p as i32, jit, seed.wrapping_add(o * 977)); - match mode { - 1 => f2 * 0.75, - 2 => (f2 - f1) * 1.5, - _ => f1, - } - .clamp(0.0, 1.0) - }); - // Cell distances already span 0..1: contrast 0.5 leaves them as they are. - spread(n, k * 0.4) - })]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use super::*; - use crate::catalog::{find, resolve_params}; - - #[test] - fn primitives_tile_and_stay_in_range() { - for k in 0..20 { - let (y, z) = (k as f32 * 0.37, k as f32 * 0.11); - assert!((perlin3(0.0, y, z, 4, 4, 7) - perlin3(4.0, y, z, 4, 4, 7)).abs() < 1e-5); - assert!((perlin3(y, 0.0, z, 4, 4, 7) - perlin3(y, 4.0, z, 4, 4, 7)).abs() < 1e-5); - assert!((worley3(0.0, y, z, 5, 5, 1.0, 3).0 - worley3(5.0, y, z, 5, 5, 1.0, 3).0).abs() < 1e-4); - } - let mut lo = f32::MAX; - let mut hi = f32::MIN; - for k in 0..20000 { - let p = [k as f32 * 0.131, k as f32 * 0.071 + 0.3, (k as f32 * 0.017).sin() * 9.0, k as f32 * 0.029]; - let v = simplex4(p, 1); - lo = lo.min(v); - hi = hi.max(v); - } - assert!(lo > -1.2 && hi < 1.2 && hi - lo > 1.0, "{lo} {hi}"); - } - - /// Each 3D noise matches across u = 0/1 and v = 0/1, and z changes it. - #[test] - fn noises_3d_tile_both_ways() { - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - for id in ["perlin_noise_3d", "simplex_noise_3d", "worley_noise_3d"] { - let def = find(id).unwrap(); - let cook = |z: f32| { - let mut p = resolve_params(def, &BTreeMap::new()); - p.insert("z".into(), materialcraft_core::Value::Float(z)); - let ctx = Ctx { w: 64, h: 64, seed: 5, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap().remove(0) - }; - let img = cook(0.5); - let (mut seam_x, mut seam_y, mut inner) = (0.0f32, 0.0f32, 0.0f32); - for i in 0..64 { - seam_x += (img.get(63, i, false)[0] - img.get(0, i, false)[0]).abs(); - seam_y += (img.get(i, 63, false)[0] - img.get(i, 0, false)[0]).abs(); - inner += (img.get(31, i, false)[0] - img.get(32, i, false)[0]).abs() + (img.get(i, 31, false)[0] - img.get(i, 32, false)[0]).abs(); - } - assert!(seam_x <= inner * 1.5 + 0.2 && seam_y <= inner * 1.5 + 0.2, "{id}: seams {seam_x} {seam_y} vs inner {inner}"); - assert_ne!(img, cook(1.7), "{id}: z changes the slice"); - let (lo, hi) = img.range(); - assert!(hi - lo > 0.3, "{id}: contrast {lo}..{hi}"); - } - } -} diff --git a/_to_delete/nodes_noises_more.rs b/_to_delete/nodes_noises_more.rs deleted file mode 100644 index d59f7cd..0000000 --- a/_to_delete/nodes_noises_more.rs +++ /dev/null @@ -1,440 +0,0 @@ -//! More Texture generators › Noises: fractal variants, fibers, organic cells and natural -//! materials (sand, wood, marble, stone, bark, concrete). All tile: every lattice uses whole-number -//! periods per axis. - -use std::f32::consts::{PI, TAU}; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::generators::NOISES; -use crate::noise::{cellular, fbm, hash3, rand1, rand2, value}; - -#[inline] -pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0).max(1e-6)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -#[inline] -fn wrap(i: i32, p: i32) -> i32 { - if p <= 0 { i } else { i.rem_euclid(p) } -} - -/// Gradient (Perlin) noise in about -1..1 with separate lattice periods per axis, so stretched -/// noise still tiles. -pub(crate) fn perlin_xy(x: f32, y: f32, px: i32, py: i32, seed: u32) -> f32 { - let (x0, y0) = (x.floor(), y.floor()); - let (fx, fy) = (x - x0, y - y0); - let (ix, iy) = (x0 as i32, y0 as i32); - let g = |i: i32, j: i32, dx: f32, dy: f32| { - let a = (hash3(wrap(i, px), wrap(j, py), seed) >> 8) as f32 * (TAU / (1u32 << 24) as f32); - a.cos() * dx + a.sin() * dy - }; - let fade = |t: f32| t * t * t * (t * (t * 6.0 - 15.0) + 10.0); - let (u, v) = (fade(fx), fade(fy)); - let a = g(ix, iy, fx, fy) + (g(ix + 1, iy, fx - 1.0, fy) - g(ix, iy, fx, fy)) * u; - let b = g(ix, iy + 1, fx, fy - 1.0) + (g(ix + 1, iy + 1, fx - 1.0, fy - 1.0) - g(ix, iy + 1, fx, fy - 1.0)) * u; - (a + (b - a) * v) * std::f32::consts::SQRT_2 -} - -/// Fractal sum of `f(level multiplier, octave)` (each 0..1): `octaves` layers, each twice as fine -/// and `gain` times weaker. Normalized to 0..1. -pub(crate) fn fractal(octaves: i32, gain: f32, f: impl Fn(f32, u32) -> f32) -> f32 { - let (mut sum, mut amp, mut norm, mut m) = (0.0, 1.0, 0.0, 1.0); - for o in 0..octaves.clamp(1, 10) as u32 { - sum += f(m, o) * amp; - norm += amp; - amp *= gain; - m *= 2.0; - } - sum / f32::max(norm, 1e-6) -} - -/// Stretched fractal Perlin noise in 0..1 with `sx` × `sy` base cells. -fn fbm_xy(u: f32, v: f32, sx: f32, sy: f32, octaves: i32, gain: f32, seed: u32) -> f32 { - fractal(octaves, gain, |m, o| { - let (px, py) = (sx * m, sy * m); - perlin_xy(u * px, v * py, px as i32, py as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5 - }) -} - -/// A thin bright line per stretched noise zero crossing (fibers, grain). -fn fiber(u: f32, v: f32, along: f32, across: f32, sharp: f32, seed: u32) -> f32 { - (1.0 - perlin_xy(u * along, v * across, along as i32, across as i32, seed).abs()).powf(sharp) -} - -fn whole(ctx: &Ctx, id: &str) -> f32 { - ctx.f(id).max(1.0).round() -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let n = |id, label| node(id, label, NOISES).generator(); - vec![ - n("value_noise", "Value Noise") - .desc("Fractal value noise: smooth blocks of random values.") - .float("scale", "Scale", 8.0, 1.0, 256.0) - .int("octaves", "Octaves", 1, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(value_noise), - n("ridged_fractal", "Ridged Fractal") - .desc("Ridged multi-octave noise: sharp crests like mountain ridges.") - .float("scale", "Scale", 4.0, 1.0, 64.0) - .int("octaves", "Octaves", 6, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("sharpness", "Sharpness", 2.0, 0.5, 8.0) - .gray_out() - .cook(ridged_fractal), - n("voronoi_fractal", "Voronoi Fractal") - .desc("Several octaves of cell bumps.") - .float("scale", "Scale", 4.0, 1.0, 64.0) - .int("octaves", "Octaves", 4, 1, 8) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(voronoi_fractal), - n("cells_fractal", "Cells Fractal") - .desc("Several octaves of cell borders: cracked, crystalline networks.") - .float("scale", "Scale", 4.0, 1.0, 64.0) - .int("octaves", "Octaves", 3, 1, 8) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(cells_fractal), - n("directional_noise", "Directional Noise") - .desc("Fractal noise stretched along one axis: streaks and brushed patterns.") - .float("scale", "Scale along", 2.0, 1.0, 64.0) - .float("scale_across", "Scale across", 24.0, 1.0, 256.0) - .int("octaves", "Octaves", 5, 1, 10) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(directional_noise), - n("fibers", "Fibers") - .desc("Thin, nearly parallel fibers.") - .float("density", "Density", 96.0, 4.0, 512.0) - .float("length", "Length", 2.0, 1.0, 32.0) - .float("sharpness", "Sharpness", 12.0, 1.0, 64.0) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(fibers), - n("messy_fibers", "Messy Fibers") - .desc("Tangled fibers in both directions, warped by clouds.") - .float("density", "Density", 64.0, 4.0, 512.0) - .float("warp", "Warp", 0.5, 0.0, 2.0) - .float("sharpness", "Sharpness", 10.0, 1.0, 64.0) - .gray_out() - .cook(messy_fibers), - n("leather", "Leather") - .desc("Leather grain: small bumpy cells split by creases, over soft clouds.") - .float("scale", "Scale", 24.0, 2.0, 128.0) - .float("crease", "Crease width", 0.25, 0.0, 1.0) - .float("warp", "Warp", 0.4, 0.0, 1.0) - .float("clouds", "Clouds", 0.3, 0.0, 1.0) - .gray_out() - .cook(leather), - n("microscope", "Microscope View") - .desc("Strongly warped cell walls, like tissue under a microscope.") - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("warp", "Warp", 0.6, 0.0, 2.0) - .float("width", "Wall width", 0.15, 0.01, 1.0) - .gray_out() - .cook(microscope), - n("gaussian_spots", "Gaussian Spots") - .desc("Scattered soft round spots of random size and intensity.") - .float("scale", "Scale", 8.0, 1.0, 64.0) - .float("size", "Size", 0.3, 0.01, 1.0) - .float("size_random", "Size random", 0.5, 0.0, 1.0) - .float("density", "Density", 0.8, 0.0, 1.0) - .gray_out() - .cook(gaussian_spots), - n("crackle", "Crackle") - .desc("Wiggly cracks along cell borders, with finer secondary cracks.") - .float("scale", "Scale", 5.0, 1.0, 64.0) - .float("width", "Width", 0.08, 0.005, 0.5) - .float("disorder", "Disorder", 0.5, 0.0, 2.0) - .float("amount", "Amount", 1.0, 0.0, 1.0) - .gray_out() - .cook(crackle), - n("sand_dunes", "Sand Dunes") - .desc("Wind-shaped dunes: gentle windward slopes, steep lee sides and fine ripples.") - .int("count", "Dunes", 6, 1, 64) - .float("warp", "Warp", 0.6, 0.0, 2.0) - .float("steepness", "Lee side", 0.3, 0.05, 0.95) - .float("ripples", "Ripples", 0.15, 0.0, 1.0) - .gray_out() - .cook(sand_dunes), - n("wood_grain", "Wood Grain") - .desc("Distorted growth rings and fibers of sawn wood (grain along X).") - .float("rings", "Rings", 16.0, 1.0, 128.0) - .float("stretch", "Stretch", 6.0, 1.0, 32.0) - .float("sharpness", "Ring sharpness", 3.0, 0.5, 16.0) - .float("fibers", "Fibers", 0.3, 0.0, 1.0) - .gray_out() - .cook(wood_grain), - n("marble", "Marble") - .desc("Thin veins from sine bands warped by fractal noise.") - .float("scale", "Bands", 2.0, 1.0, 32.0) - .float("turbulence", "Turbulence", 3.0, 0.0, 10.0) - .float("sharpness", "Vein sharpness", 4.0, 1.0, 64.0) - .choice("direction", "Direction", &["Horizontal", "Vertical", "Diagonal"], 2) - .gray_out() - .cook(marble), - n("stones", "Stones") - .desc("Packed rounded stones with gaps (height).") - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("gap", "Gap", 0.06, 0.0, 0.5) - .float("bevel", "Bevel", 0.25, 0.01, 1.0) - .float("height_random", "Height random", 0.4, 0.0, 1.0) - .float("detail", "Detail", 0.2, 0.0, 1.0) - .float("disorder", "Disorder", 1.0, 0.0, 1.0) - .gray_out() - .cook(stones), - n("ripples", "Ripples") - .desc("Interfering waves, like a water surface.") - .float("scale", "Scale", 8.0, 1.0, 32.0) - .int("waves", "Waves", 10, 1, 32) - .float("warp", "Warp", 0.3, 0.0, 2.0) - .gray_out() - .cook(ripples), - n("concrete", "Concrete") - .desc("Cement clouds with small air pits and fine grain.") - .float("scale", "Scale", 4.0, 1.0, 32.0) - .float("pits", "Pit density", 0.3, 0.0, 1.0) - .float("pit_size", "Pit size", 0.5, 0.0, 1.0) - .float("roughness", "Roughness", 0.6, 0.0, 1.0) - .gray_out() - .cook(concrete), - n("bark", "Bark") - .desc("Deep vertical bark furrows.") - .float("scale", "Furrows", 8.0, 1.0, 64.0) - .float("stretch", "Length", 1.0, 1.0, 16.0) - .float("warp", "Warp", 0.4, 0.0, 2.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .gray_out() - .cook(bark), - ] -} - -fn value_noise(ctx: &Ctx) -> CookResult { - let (sc, o, r, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fractal(o, r, |m, k| value(u * sc * m, v * sc * m, (sc * m) as i32, s.wrapping_add(k * 131))))]) -} - -fn ridged_fractal(ctx: &Ctx) -> CookResult { - let (sc, o, r, sh, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.f("sharpness").max(0.1), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - fractal(o, r, |m, k| (1.0 - perlin_xy(u * sc * m, v * sc * m, (sc * m) as i32, (sc * m) as i32, s.wrapping_add(k * 7919)).abs()).powf(sh)) - })]) -} - -fn cell_fractal(ctx: &Ctx, f: impl Fn(crate::noise::Cell) -> f32 + Sync) -> CookResult { - let (sc, o, r, d, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| fractal(o, r, |m, k| f(cellular(u * sc * m, v * sc * m, (sc * m) as i32, d, 0, s.wrapping_add(k * 311)))))]) -} - -fn voronoi_fractal(ctx: &Ctx) -> CookResult { - cell_fractal(ctx, |c| (1.0 - c.f1).clamp(0.0, 1.0)) -} - -fn cells_fractal(ctx: &Ctx) -> CookResult { - cell_fractal(ctx, |c| ((c.f2 - c.f1) * 2.0).min(1.0)) -} - -fn directional_noise(ctx: &Ctx) -> CookResult { - let (along, across, o, r, s) = (whole(ctx, "scale"), whole(ctx, "scale_across"), ctx.i("octaves"), ctx.f("roughness"), ctx.seed); - let vert = ctx.b("vertical"); - Ok(vec![ctx.gen_gray(|u, v| if vert { fbm_xy(u, v, across, along, o, r, s) } else { fbm_xy(u, v, along, across, o, r, s) })]) -} - -fn fibers(ctx: &Ctx) -> CookResult { - let (d, l, sh, s) = (whole(ctx, "density"), whole(ctx, "length"), ctx.f("sharpness").max(1.0), ctx.seed); - let vert = ctx.b("vertical"); - Ok(vec![ctx.gen_gray(|u, v| { - let (u, v) = if vert { (v, u) } else { (u, v) }; - let a = fiber(u, v, l, d, sh, s); - let b = fiber(u, v, l * 2.0, d * 2.0, sh, s ^ 0x51); - (a + b * 0.6).min(1.0) - })]) -} - -fn messy_fibers(ctx: &Ctx) -> CookResult { - let (d, w, sh, s) = (whole(ctx, "density"), ctx.f("warp") * 0.15, ctx.f("sharpness").max(1.0), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let wu = u + (fbm(u, v, 3.0, 4, 0.5, s ^ 1) - 0.5) * w; - let wv = v + (fbm(u, v, 3.0, 4, 0.5, s ^ 2) - 0.5) * w; - let h = fiber(wu, wv, 3.0, d, sh, s); - let vt = fiber(wv, wu, 3.0, d, sh, s ^ 0x77); - let fine = fiber(wv, wu, 6.0, d * 2.0, sh, s ^ 0x99); - (h + vt * 0.8 + fine * 0.4).min(1.0) - })]) -} - -fn leather(ctx: &Ctx) -> CookResult { - let (sc, cw, w, cl, s) = (whole(ctx, "scale"), ctx.f("crease").max(1e-3), ctx.f("warp"), ctx.f("clouds"), ctx.seed); - let lo = (sc / 6.0).round().max(1.0); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = (fbm(u, v, lo, 4, 0.5, s ^ 3) - 0.5) * w / sc * 2.0; - let qy = (fbm(u, v, lo, 4, 0.5, s ^ 4) - 0.5) * w / sc * 2.0; - let c = cellular((u + qx) * sc, (v + qy) * sc, sc as i32, 1.0, 0, s); - let crease = smoothstep(0.0, cw, c.f2 - c.f1); - let bump = (1.0 - c.f1 * 0.9).clamp(0.0, 1.0); - let clouds = fbm(u, v, lo, 5, 0.5, s ^ 7); - (crease * (0.55 + 0.45 * bump) * (1.0 - cl + cl * clouds)).clamp(0.0, 1.0) - })]) -} - -fn microscope(ctx: &Ctx) -> CookResult { - let (sc, w, wd, s) = (whole(ctx, "scale"), ctx.f("warp"), ctx.f("width").max(1e-3), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = (fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5) * w / sc * 3.0; - let qy = (fbm(u, v, sc, 4, 0.5, s ^ 6) - 0.5) * w / sc * 3.0; - let c = cellular((u + qx) * sc, (v + qy) * sc, sc as i32, 1.0, 0, s); - let wall = 1.0 - smoothstep(0.0, wd, c.f2 - c.f1); - let inner = fbm(u, v, sc * 2.0, 4, 0.5, s ^ 8) * 0.35 * (1.0 - c.f1).max(0.0); - (wall + inner).clamp(0.0, 1.0) - })]) -} - -fn gaussian_spots(ctx: &Ctx) -> CookResult { - let (sc, size, sr, dens, s) = (whole(ctx, "scale"), ctx.f("size").max(0.01), ctx.f("size_random"), ctx.f("density"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let mut sum = 0.0; - for layer in 0..2u32 { - let n = sc * (layer + 1) as f32; - let (x, y) = (u * n, v * n); - let (ix, iy) = (x.floor() as i32, y.floor() as i32); - let ls = s.wrapping_add(layer * 0x3c6e); - for j in -1..=1 { - for i in -1..=1 { - let (cx, cy) = (wrap(ix + i, n as i32), wrap(iy + j, n as i32)); - if rand2(cx, cy, ls ^ 9) > dens { - continue; - } - let px = (ix + i) as f32 + rand2(cx, cy, ls); - let py = (iy + j) as f32 + rand2(cx, cy, ls ^ 1); - let r = size * (1.0 - sr * rand2(cx, cy, ls ^ 2)) * 0.5; - let d2 = (px - x).powi(2) + (py - y).powi(2); - sum += (-d2 / (2.0 * r * r)).exp() * (0.4 + 0.6 * rand2(cx, cy, ls ^ 3)) / (layer + 1) as f32; - } - } - } - sum.min(1.0) - })]) -} - -fn crackle(ctx: &Ctx) -> CookResult { - let (sc, wd, dis, amt, s) = (whole(ctx, "scale"), ctx.f("width").max(1e-3), ctx.f("disorder"), ctx.f("amount"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let qx = (fbm(u, v, sc, 4, 0.5, s ^ 1) - 0.5) * dis / sc; - let qy = (fbm(u, v, sc, 4, 0.5, s ^ 2) - 0.5) * dis / sc; - let (wu, wv) = (u + qx, v + qy); - let c = cellular(wu * sc, wv * sc, sc as i32, 1.0, 0, s); - let main = 1.0 - smoothstep(0.0, wd, c.f2 - c.f1); - let n2 = sc * 3.0; - let c2 = cellular(wu * n2, wv * n2, n2 as i32, 1.0, 0, s ^ 5); - // Finer cracks only in some areas, so they break off instead of closing into cells. - let fine = (1.0 - smoothstep(0.0, wd * 1.5, c2.f2 - c2.f1)) * smoothstep(0.55, 0.65, fbm(u, v, sc * 2.0, 3, 0.5, s ^ 11)) * 0.6; - let vis = smoothstep(0.9 - amt, 1.1 - amt, fbm(u, v, 2.0, 3, 0.5, s ^ 3) * 0.999); - (main.max(fine) * if amt >= 1.0 { 1.0 } else { vis }).clamp(0.0, 1.0) - })]) -} - -fn sand_dunes(ctx: &Ctx) -> CookResult { - let (n, w, k, rp, s) = (ctx.i("count").max(1) as f32, ctx.f("warp"), ctx.f("steepness").clamp(0.05, 0.95), ctx.f("ripples"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = fbm(u, v, 3.0, 5, 0.5, s) - 0.5; - let t = (v * n + q * w * 2.0).rem_euclid(1.0); - let p = if t < 1.0 - k { t / (1.0 - k) } else { (1.0 - t) / k }; - let p = p * p * (3.0 - 2.0 * p); - let rip = (TAU * (v * n * 8.0 + q * 6.0 + u * 2.0)).sin() * 0.5 + 0.5; - p * (1.0 - rp) + rip * rp * (0.5 + 0.5 * p) - })]) -} - -fn wood_grain(ctx: &Ctx) -> CookResult { - let (rings, st, sh, fb, s) = (ctx.f("rings").max(1.0), whole(ctx, "stretch"), ctx.f("sharpness").max(0.1), ctx.f("fibers"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let n = fbm_xy(u, v, 1.0, st, 4, 0.45, s); - let t = (n * rings).rem_euclid(1.0); - let ring = t.powf(sh); - let f = fiber(u, v, 2.0, 160.0, 8.0, s ^ 0x3b); - ((1.0 - ring * 0.65) * (1.0 - f * fb * 0.35)).clamp(0.0, 1.0) - })]) -} - -fn marble(ctx: &Ctx) -> CookResult { - let (n, turb, sh, dir, s) = (whole(ctx, "scale"), ctx.f("turbulence"), ctx.f("sharpness").max(1.0), ctx.i("direction"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let base = match dir { - 0 => v, - 1 => u, - _ => u + v, - }; - let f = fbm(u, v, 3.0, 6, 0.55, s); - let vein = |k: f32, f: f32| (1.0 - (PI * (base * n * k + turb * f)).sin().abs()).powf(sh * k); - // Main veins plus a finer, fainter network. - let v2 = vein(2.0, fbm(u, v, 4.0, 6, 0.55, s ^ 9)); - (0.25 + 0.2 * fbm(u, v, 6.0, 5, 0.5, s ^ 4) + 0.6 * vein(1.0, f).max(v2 * 0.45)).clamp(0.0, 1.0) - })]) -} - -fn stones(ctx: &Ctx) -> CookResult { - let (sc, gap, bev, hr, det, dis, s) = - (whole(ctx, "scale"), ctx.f("gap"), ctx.f("bevel").max(1e-3), ctx.f("height_random"), ctx.f("detail"), ctx.f("disorder"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let c = cellular(u * sc, v * sc, sc as i32, dis, 0, s); - let e = (c.f2 - c.f1) * 0.5 - gap * 0.5; - if e <= 0.0 { - return 0.0; - } - let dome = smoothstep(0.0, bev, e).sqrt(); - let d = fbm(u, v, sc * 2.0, 4, 0.5, s ^ 3); - (dome * (1.0 - hr * c.id) * (1.0 - det + det * d)).clamp(0.0, 1.0) - })]) -} - -fn ripples(ctx: &Ctx) -> CookResult { - let (sc, n, w, s) = (whole(ctx, "scale"), ctx.i("waves").clamp(1, 32) as u32, ctx.f("warp"), ctx.seed); - // Whole-number wave vectors keep every wave periodic over the image. - let waves: Vec<(f32, f32, f32, f32)> = (0..n) - .map(|k| { - let (dy, dx) = (rand1(k * 4, s) * TAU).sin_cos(); - let mag = sc * (0.5 + 0.5 * rand1(k * 4 + 1, s)); - let (mut kx, ky) = ((dx * mag).round(), (dy * mag).round()); - if kx == 0.0 && ky == 0.0 { - kx = 1.0; - } - (kx, ky, rand1(k * 4 + 2, s), 1.0 / (1.0 + k as f32 * 0.3)) - }) - .collect(); - let norm: f32 = waves.iter().map(|w| w.3).sum(); - Ok(vec![ctx.gen_gray(|u, v| { - let q = (fbm(u, v, 2.0, 3, 0.5, s ^ 7) - 0.5) * w; - let sum: f32 = waves.iter().map(|(kx, ky, ph, a)| (TAU * (kx * u + ky * v + ph + q)).sin() * a).sum(); - (sum / norm.max(1e-6) * 0.5 + 0.5).clamp(0.0, 1.0) - })]) -} - -fn concrete(ctx: &Ctx) -> CookResult { - let (sc, pits, ps, r, s) = (whole(ctx, "scale"), ctx.f("pits"), ctx.f("pit_size"), ctx.f("roughness"), ctx.seed); - let pn = (sc * 12.0).round(); - Ok(vec![ctx.gen_gray(|u, v| { - let base = fbm(u, v, sc, 8, r, s); - let c = cellular(u * pn, v * pn, pn as i32, 1.0, 0, s ^ 5); - let rad = 0.08 + ps * 0.3; - let pit = if c.id < pits { 1.0 - smoothstep(rad * 0.6, rad, c.f1) } else { 0.0 }; - let grain = value(u * 192.0, v * 192.0, 192, s ^ 9); - (base * 0.75 + grain * 0.25 - pit * 0.45).clamp(0.0, 1.0) - })]) -} - -fn bark(ctx: &Ctx) -> CookResult { - let (sx, sy, w, r, s) = (whole(ctx, "scale"), whole(ctx, "stretch"), ctx.f("warp"), ctx.f("roughness"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let q = (fbm(u, v, 4.0, 4, 0.5, s ^ 3) - 0.5) * w / sx; - fractal(5, r, |m, k| { - let (px, py) = (sx * m, sy * m); - (1.0 - perlin_xy((u + q) * px, v * py, px as i32, py as i32, s.wrapping_add(k * 613)).abs()).powi(2) - }) - })]) -} diff --git a/_to_delete/nodes_patterns.rs b/_to_delete/nodes_patterns.rs deleted file mode 100644 index 78506e7..0000000 --- a/_to_delete/nodes_patterns.rs +++ /dev/null @@ -1,558 +0,0 @@ -//! Texture generators › Patterns: shapes, tilings, gradients and scattered elements. - -use std::f32::consts::{PI, TAU}; - -use materialcraft_image::{Image, Kind}; - -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::noise::{rand1, rand2}; - -pub const PATTERNS: &str = "Texture generators/Patterns"; - -pub const SHAPES: &[&str] = &[ - "Square", - "Disc", - "Paraboloid", - "Bell", - "Gaussian", - "Thorn", - "Pyramid", - "Brick", - "Gradation", - "Waves", - "Half bell", - "Ridged bell", - "Crescent", - "Capsule", - "Cone", - "Hexagon", -]; - -/// A shape's value at local coordinates `(x, y)` in -1..1 (1 at the center, 0 outside). -pub fn shape(kind: i32, x: f32, y: f32) -> f32 { - let r = (x * x + y * y).sqrt(); - let m = x.abs().max(y.abs()); - let v = match kind { - 0 => (m <= 1.0) as i32 as f32, - 1 => (r <= 1.0) as i32 as f32, - 2 => 1.0 - r * r, - 3 => { - let t = (1.0 - r).max(0.0); - t * t * (3.0 - 2.0 * t) - } - 4 => (-r * r * 4.0).exp() * (r <= 1.0) as i32 as f32, - 5 => (1.0 - r).max(0.0).powi(3), - 6 => 1.0 - m, - 7 => { - let bx = (1.0 - x.abs()) * 6.0; - let by = (1.0 - y.abs()) * 3.0; - bx.min(by).clamp(0.0, 1.0) - } - 8 => (x * 0.5 + 0.5) * (m <= 1.0) as i32 as f32, - 9 => (x * PI * 2.0).cos() * 0.5 + 0.5, - 10 => { - let t = (1.0 - r).max(0.0); - if y < 0.0 { 0.0 } else { t * t * (3.0 - 2.0 * t) } - } - 11 => { - let t = (1.0 - r).max(0.0); - (t * t * (3.0 - 2.0 * t)) * (1.0 - ((r * PI * 3.0).sin()).abs() * 0.4) - } - 12 => { - let r2 = ((x - 0.35) * (x - 0.35) + y * y).sqrt(); - ((r <= 1.0) && (r2 > 0.75)) as i32 as f32 - } - 13 => { - let dx = (x.abs() - 0.5).max(0.0); - let d = (dx * dx + y * y * 4.0).sqrt(); - (d <= 0.5) as i32 as f32 - } - 14 => (1.0 - r).max(0.0), - 15 => { - let (ax, ay) = (x.abs(), y.abs()); - ((ax * 0.866 + ay * 0.5).max(ay) <= 0.95) as i32 as f32 - } - _ => 0.0, - }; - v.clamp(0.0, 1.0) -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let p = |id, label| node(id, label, PATTERNS).generator(); - vec![ - p("brick_generator", "Brick Generator") - .desc("Rows of bricks with mortar gaps, bevels and random heights.") - .int("bricks_x", "Bricks X", 4, 1, 64) - .int("bricks_y", "Bricks Y", 8, 1, 64) - .float("offset", "Row offset", 0.5, 0.0, 1.0) - .float("gap", "Gap", 0.04, 0.0, 0.5) - .float("bevel", "Bevel", 0.12, 0.0, 1.0) - .float("height_random", "Height random", 0.3, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) - .gray_out() - .cook(bricks), - p("checker", "Checker").desc("A checkerboard.").int("tiling", "Tiling", 4, 1, 64).gray_out().cook(checker), - p("gradient_linear_1", "Gradient Linear 1") - .desc("A ramp from black to white.") - .int("tiling", "Tiling", 1, 1, 16) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(gradient_linear_1), - p("gradient_linear_2", "Gradient Linear 2") - .desc("A mirrored ramp (white in the middle).") - .int("tiling", "Tiling", 1, 1, 16) - .boolean("vertical", "Vertical", false) - .gray_out() - .cook(gradient_linear_2), - p("gradient_radial", "Gradient Radial") - .desc("White at the center fading outward.") - .float("radius", "Radius", 0.5, 0.0, 1.0) - .gray_out() - .cook(gradient_radial), - p("hexagons", "Hexagons") - .desc("A honeycomb of beveled hexagons.") - .int("tiling", "Tiling", 4, 1, 64) - .float("size", "Size", 0.9, 0.0, 1.0) - .float("bevel", "Bevel", 0.3, 0.0, 1.0) - .gray_out() - .cook(hexagons), - p("polygon", "Polygon") - .desc("A regular polygon.") - .int("sides", "Sides", 6, 3, 32) - .float("scale", "Scale", 0.8, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .float("gradient", "Gradient", 0.0, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(polygon), - p("scratches", "Scratches") - .desc("Random thin scratches.") - .int("count", "Count", 60, 0, 1000) - .float("length", "Length", 0.25, 0.0, 1.0) - .float("width", "Width", 1.0, 0.1, 8.0) - .angle("angle", "Angle", 0.1) - .float("angle_random", "Angle random", 0.2, 0.0, 1.0) - .gray_out() - .cook(scratches), - p("shape", "Shape") - .desc("A single shape, optionally tiled.") - .choice("pattern", "Pattern", SHAPES, 1) - .int("tiling", "Tiling", 1, 1, 64) - .float("size", "Size", 0.8, 0.0, 2.0) - .float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0) - .angle("angle", "Angle", 0.0) - .gray_out() - .cook(shape_node), - p("splatter", "Splatter") - .desc("Scattered shapes of random size and gray.") - .choice("pattern", "Pattern", SHAPES, 4) - .int("count", "Count", 64, 1, 2000) - .float("size", "Size", 0.08, 0.0, 1.0) - .float("size_random", "Size random", 0.6, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.5, 0.0, 1.0) - .gray_out() - .cook(splatter), - p("star", "Star") - .desc("A star shape.") - .int("points", "Points", 5, 2, 32) - .float("inner", "Inner radius", 0.45, 0.0, 1.0) - .float("scale", "Scale", 0.8, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(star), - p("stripes", "Stripes") - .desc("Parallel bands with soft edges.") - .int("count", "Count", 8, 1, 128) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .gray_out() - .cook(stripes), - p("tile_generator", "Tile Generator") - .desc("Places a shape on a grid with per-tile random size, position, rotation and luminance.") - .choice("pattern", "Pattern", SHAPES, 0) - .int("x_amount", "X amount", 8, 1, 128) - .int("y_amount", "Y amount", 8, 1, 128) - .float("scale", "Scale", 0.9, 0.0, 2.0) - .float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0) - .float("scale_random", "Scale random", 0.0, 0.0, 1.0) - .float("offset", "Row offset", 0.0, 0.0, 1.0) - .float("position_random", "Position random", 0.0, 0.0, 1.0) - .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) - .float("mask_random", "Mask random", 0.0, 0.0, 1.0) - .gray_out() - .cook(tile_generator), - p("tile_sampler", "Tile Sampler") - .desc("Like Tile Generator, but each tile shows the pattern input.") - .gray_in("pattern", "Pattern input") - .gray_in("scale_map", "Scale map") - .int("x_amount", "X amount", 8, 1, 128) - .int("y_amount", "Y amount", 8, 1, 128) - .float("scale", "Scale", 1.0, 0.0, 2.0) - .float("scale_random", "Scale random", 0.0, 0.0, 1.0) - .float("offset", "Row offset", 0.0, 0.0, 1.0) - .float("position_random", "Position random", 0.0, 0.0, 1.0) - .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) - .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) - .choice("blend", "Blending", &["Max", "Add"], 0) - .gray_out() - .cook(tile_sampler), - p("weave", "Weave") - .desc("Interlaced threads (height).") - .int("tiling", "Tiling", 6, 1, 64) - .float("width", "Thread width", 0.8, 0.0, 1.0) - .gray_out() - .cook(weave), - p("waveform", "Waveform") - .desc("Sine bands.") - .int("count", "Count", 8, 1, 128) - .float("amplitude", "Amplitude", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .gray_out() - .cook(waveform), - ] -} - -/// Rotate `(x, y)` by `turns`. -#[inline] -fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) { - let (s, c) = (turns * TAU).sin_cos(); - (x * c - y * s, x * s + y * c) -} - -fn bricks(ctx: &Ctx) -> CookResult { - let (bx, by) = (ctx.i("bricks_x").max(1) as f32, ctx.i("bricks_y").max(1) as f32); - let (off, gap, bevel, hr, lr, s) = (ctx.f("offset"), ctx.f("gap"), ctx.f("bevel").max(1e-4), ctx.f("height_random"), ctx.f("lum_random"), ctx.seed); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * by).floor(); - let x = u * bx + off * row; - let col = x.floor(); - let (fx, fy) = (x - col, v * by - row); - let colw = (col as i32).rem_euclid(bx as i32); - // Distance to the brick's edge, in brick-height units. - let ex = fx.min(1.0 - fx) * by / bx; - let ey = fy.min(1.0 - fy); - let e = ex.min(ey) - gap * 0.5; - if e <= 0.0 { - return 0.0; - } - let t = (e / (bevel * 0.5)).min(1.0); - let rnd = rand2(colw, row as i32, s); - let base = 1.0 - hr * rnd; - let lum = 1.0 - lr * rand2(colw, row as i32, s ^ 99); - (t * base * lum).clamp(0.0, 1.0) - })]) -} - -fn checker(ctx: &Ctx) -> CookResult { - let n = ctx.i("tiling").max(1) as f32; - Ok(vec![ctx.gen_gray(|u, v| (((u * n).floor() + (v * n).floor()) as i32 & 1) as f32)]) -} - -fn gradient_linear_1(ctx: &Ctx) -> CookResult { - let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical")); - Ok(vec![ctx.gen_gray(|u, v| ((if vert { v } else { u }) * n).fract())]) -} - -fn gradient_linear_2(ctx: &Ctx) -> CookResult { - let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical")); - Ok(vec![ctx.gen_gray(|u, v| 1.0 - ((((if vert { v } else { u }) * n).fract()) * 2.0 - 1.0).abs())]) -} - -fn gradient_radial(ctx: &Ctx) -> CookResult { - let r = ctx.f("radius").max(1e-3); - Ok(vec![ctx.gen_gray(|u, v| (1.0 - ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() / r).clamp(0.0, 1.0))]) -} - -fn hexagons(ctx: &Ctx) -> CookResult { - let n = ctx.i("tiling").max(1) as f32; - let (size, bevel) = (ctx.f("size"), ctx.f("bevel").max(1e-3)); - let sq3 = 3f32.sqrt(); - // Flat-top hexes of circumradius 1: two lattices, (3i, √3j) and (3i + 1.5, √3j + √3/2). The - // image holds n lattice periods across and the nearest whole number down, so it tiles. - let m = (n * 3.0 / sq3).round().max(1.0); - Ok(vec![ctx.gen_gray(|u, v| { - let (px, py) = (u * n * 3.0, v * m * sq3); - let a = ((px / 3.0).round() * 3.0, (py / sq3).round() * sq3); - let b = (((px - 1.5) / 3.0).round() * 3.0 + 1.5, ((py - sq3 * 0.5) / sq3).round() * sq3 + sq3 * 0.5); - let da = (px - a.0).powi(2) + (py - a.1).powi(2); - let db = (px - b.0).powi(2) + (py - b.1).powi(2); - let (cx, cy) = if da < db { a } else { b }; - let (dx, dy) = ((px - cx).abs(), (py - cy).abs()); - let inr = sq3 * 0.5; - let d = (dy / inr).max((dx * inr + dy * 0.5) / inr); - ((size - d) / bevel).clamp(0.0, 1.0) - })]) -} - -fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) { - (((u * n).fract() - 0.5) * 2.0, ((v * n).fract() - 0.5) * 2.0) -} - -fn polygon(ctx: &Ctx) -> CookResult { - let sides = ctx.i("sides").clamp(3, 64) as f32; - let (sc, ang, grad, n) = (ctx.f("scale").max(1e-3), ctx.f("angle"), ctx.f("gradient"), ctx.i("tiling").max(1) as f32); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, n); - let (x, y) = rot(x, y, ang); - let a = y.atan2(x); - let seg = TAU / sides; - let d = (x * x + y * y).sqrt() * ((a.rem_euclid(seg) - seg * 0.5).cos()) / (seg * 0.5).cos(); - let e = 1.0 - d / sc; - if grad <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / grad).clamp(0.0, 1.0) } - })]) -} - -fn scratches(ctx: &Ctx) -> CookResult { - let count = ctx.i("count").clamp(0, 5000) as u32; - let (len, width, ang, ar, s) = (ctx.f("length"), ctx.f("width") / ctx.w as f32, ctx.f("angle"), ctx.f("angle_random"), ctx.seed); - let segs: Vec<([f32; 2], [f32; 2], f32)> = (0..count) - .map(|i| { - let p = [rand1(i * 4, s), rand1(i * 4 + 1, s)]; - let a = (ang + (rand1(i * 4 + 2, s) - 0.5) * ar) * TAU; - let l = len * (0.5 + 0.5 * rand1(i * 4 + 3, s)); - ([p[0], p[1]], [a.cos() * l, -a.sin() * l], 0.4 + 0.6 * rand1(i * 7 + 5, s)) - }) - .collect(); - // Bin segments by their bounding boxes on a coarse grid so each pixel tests only nearby ones. - const G: usize = 16; - let mut bins: Vec<Vec<usize>> = vec![Vec::new(); G * G]; - for (k, (p, d, _)) in segs.iter().enumerate() { - let (x0, x1) = (p[0].min(p[0] + d[0]) - width, p[0].max(p[0] + d[0]) + width); - let (y0, y1) = (p[1].min(p[1] + d[1]) - width, p[1].max(p[1] + d[1]) + width); - // At most one full turn of bins per axis, so no segment lands twice in a bin. - let (gy0, gx0) = ((y0 * G as f32).floor() as i64, (x0 * G as f32).floor() as i64); - let gy1 = ((y1 * G as f32).floor() as i64).min(gy0.saturating_add(G as i64 - 1)); - let gx1 = ((x1 * G as f32).floor() as i64).min(gx0.saturating_add(G as i64 - 1)); - for gy in gy0..=gy1 { - for gx in gx0..=gx1 { - if let Some(b) = bins.get_mut(gy.rem_euclid(G as i64) as usize * G + gx.rem_euclid(G as i64) as usize) { - b.push(k); - } - } - } - } - Ok(vec![ctx.gen_gray(|u, v| { - let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)]; - let mut best: f32 = 0.0; - for k in bin { - let (p, d, lum) = segs[*k]; - for (ox, oy) in [(0.0, 0.0), (1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] { - let (qx, qy) = (u - p[0] + ox, v - p[1] + oy); - let t = ((qx * d[0] + qy * d[1]) / (d[0] * d[0] + d[1] * d[1]).max(1e-9)).clamp(0.0, 1.0); - let (ex, ey) = (qx - d[0] * t, qy - d[1] * t); - let dist = (ex * ex + ey * ey).sqrt(); - if dist < width { - best = best.max((1.0 - dist / width) * lum * (1.0 - (t * 2.0 - 1.0).abs().powi(4))); - } - } - } - best - })]) -} - -fn shape_node(ctx: &Ctx) -> CookResult { - let (k, n, size, sxy, ang) = (ctx.i("pattern"), ctx.i("tiling").max(1) as f32, ctx.f("size").max(1e-3), ctx.v2("size_xy"), ctx.f("angle")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, n); - let (x, y) = rot(x, y, ang); - shape(k, x / (size * sxy[0].max(1e-3)), y / (size * sxy[1].max(1e-3))) - })]) -} - -fn splatter(ctx: &Ctx) -> CookResult { - let count = ctx.i("count").clamp(1, 2000) as u32; - let (k, size, sr, lr, s) = (ctx.i("pattern"), ctx.f("size"), ctx.f("size_random"), ctx.f("lum_random"), ctx.seed); - let items: Vec<([f32; 2], f32, f32, f32)> = (0..count) - .map(|i| ([rand1(i * 5, s), rand1(i * 5 + 1, s)], size * (1.0 - sr * rand1(i * 5 + 2, s)), 1.0 - lr * rand1(i * 5 + 3, s), rand1(i * 5 + 4, s))) - .collect(); - let base = Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]); - Ok(vec![stamp(ctx, base, &items, |x, y, _| shape(k, x, y), |a, b| a.max(b))]) -} - -/// Splat `items` (center, radius, luminance, rotation turns) onto `base` with `f` combining. -fn stamp( - ctx: &Ctx, - base: Image, - items: &[([f32; 2], f32, f32, f32)], - sh: impl Fn(f32, f32, usize) -> f32 + Sync, - combine: impl Fn(f32, f32) -> f32 + Sync, -) -> Image { - const G: usize = 32; - let mut bins: Vec<Vec<usize>> = vec![Vec::new(); G * G]; - for (i, (c, r, _, _)) in items.iter().enumerate() { - let r = r * 1.42; - // At most one full turn of bins per axis, so no item lands twice in a bin. - let (gy0, gx0) = (((c[1] - r) * G as f32).floor() as i64, ((c[0] - r) * G as f32).floor() as i64); - let gy1 = (((c[1] + r) * G as f32).floor() as i64).min(gy0.saturating_add(G as i64 - 1)); - let gx1 = (((c[0] + r) * G as f32).floor() as i64).min(gx0.saturating_add(G as i64 - 1)); - for gy in gy0..=gy1 { - for gx in gx0..=gx1 { - if let Some(b) = bins.get_mut(gy.rem_euclid(G as i64) as usize * G + gx.rem_euclid(G as i64) as usize) { - b.push(i); - } - } - } - } - let tile = ctx.tile; - Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { - let mut acc = base.sample_nearest(u, v, false)[0]; - let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)]; - for i in bin { - let (c, r, lum, rt) = items[*i]; - if r <= 0.0 { - continue; - } - let mut dx = u - c[0]; - let mut dy = v - c[1]; - if tile { - dx -= dx.round(); - dy -= dy.round(); - } - let (x, y) = rot(dx / r, dy / r, rt); - if x.abs() <= 1.0 && y.abs() <= 1.0 { - acc = combine(acc, sh(x, y, *i) * lum); - } - } - [acc, 0.0, 0.0, 0.0] - }) -} - -fn star(ctx: &Ctx) -> CookResult { - let pts = ctx.i("points").clamp(2, 64) as f32; - let (inner, sc, n) = (ctx.f("inner"), ctx.f("scale").max(1e-3), ctx.i("tiling").max(1) as f32); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, n); - let a = y.atan2(x) + PI / 2.0; - let seg = TAU / pts; - let t = ((a.rem_euclid(seg) / seg) * 2.0 - 1.0).abs(); - let rad = sc * (inner + (1.0 - inner) * t); - ((x * x + y * y).sqrt() <= rad) as i32 as f32 - })]) -} - -fn stripes(ctx: &Ctx) -> CookResult { - let n = ctx.i("count").max(1) as f32; - let (w, soft, ang) = (ctx.f("width"), ctx.f("softness").max(1e-3), ctx.f("angle")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, _) = rot(u - 0.5, v - 0.5, ang); - let f = (x * n).rem_euclid(1.0); - let d = (f - 0.5).abs() * 2.0; - ((w - d) / soft + 0.5).clamp(0.0, 1.0) - })]) -} - -fn tile_params(ctx: &Ctx) -> (f32, f32, f32, f32, f32, f32, f32, f32, u32) { - ( - ctx.i("x_amount").max(1) as f32, - ctx.i("y_amount").max(1) as f32, - ctx.f("scale"), - ctx.f("scale_random"), - ctx.f("offset"), - ctx.f("position_random"), - ctx.f("rotation_random"), - ctx.f("lum_random"), - ctx.seed, - ) -} - -fn tile_generator(ctx: &Ctx) -> CookResult { - let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx); - let (k, sxy, mr) = (ctx.i("pattern"), ctx.v2("size_xy"), ctx.f("mask_random")); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * ny).floor(); - let mut best: f32 = 0.0; - // Shapes may reach into neighbouring cells (scale > 1, position jitter): check 3×3. - for dj in -1..=1 { - for di in -1..=1 { - let r = row + dj as f32; - let x = u * nx + off * r; - let col = x.floor() + di as f32; - let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32)); - if mr > 0.0 && rand2(ci, ri, s ^ 0x55) < mr { - continue; - } - let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr; - let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr; - let size = sc * (1.0 - sr * rand2(ci, ri, s ^ 3)); - if size <= 0.0 { - continue; - } - let (lx, ly) = ((x - col - 0.5 - jx) * 2.0, (v * ny - r - 0.5 - jy) * 2.0); - let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr); - let val = shape(k, lx / (size * sxy[0].max(1e-3)), ly / (size * sxy[1].max(1e-3))); - best = best.max(val * (1.0 - lr * rand2(ci, ri, s ^ 5))); - } - } - best - })]) -} - -fn tile_sampler(ctx: &Ctx) -> CookResult { - let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx); - let pattern = - ctx.input(0).map(|p| p.to_gray()).unwrap_or_else(|| Image::generate_uv(64, 64, Kind::Gray, |u, v| [shape(3, u * 2.0 - 1.0, v * 2.0 - 1.0); 4])); - let smap = ctx.input(1).map(|p| p.to_gray()); - let add = ctx.i("blend") == 1; - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * ny).floor(); - let mut acc: f32 = 0.0; - for dj in -1..=1 { - for di in -1..=1 { - let r = row + dj as f32; - let x = u * nx + off * r; - let col = x.floor() + di as f32; - let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32)); - let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr; - let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr; - let mapk = smap.as_ref().map_or(1.0, |m| m.sample_gray((col + 0.5) / nx, (r + 0.5) / ny, true)); - let size = sc * mapk * (1.0 - sr * rand2(ci, ri, s ^ 3)); - if size <= 0.0 { - continue; - } - let (lx, ly) = ((x - col - 0.5 - jx) / size, (v * ny - r - 0.5 - jy) / size); - let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr); - if lx.abs() > 0.5 || ly.abs() > 0.5 { - continue; - } - let val = pattern.sample_gray(lx + 0.5, ly + 0.5, false) * (1.0 - lr * rand2(ci, ri, s ^ 5)); - acc = if add { acc + val } else { acc.max(val) }; - } - } - acc.min(1.0) - })]) -} - -fn weave(ctx: &Ctx) -> CookResult { - let n = ctx.i("tiling").max(1) as f32; - let w = ctx.f("width").clamp(0.01, 1.0); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = (u * n, v * n); - let (cx, cy) = (x.floor() as i32, y.floor() as i32); - let (fx, fy) = (x.fract(), y.fract()); - // Horizontal thread across the cell row, vertical thread down the column; which is on - // top alternates in a checker. - let hthread = ((fy - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fy - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt(); - let vthread = ((fx - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fx - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt(); - let h_top = (cx + cy) & 1 == 0; - // The thread on top bulges along its length. - let hb = hthread * (0.6 + 0.4 * (fx * PI).sin()); - let vb = vthread * (0.6 + 0.4 * (fy * PI).sin()); - if h_top { hb.max(vb * 0.6) } else { vb.max(hb * 0.6) } - })]) -} - -fn waveform(ctx: &Ctx) -> CookResult { - let n = ctx.i("count").max(1) as f32; - let (amp, ang) = (ctx.f("amplitude"), ctx.f("angle")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = rot(u - 0.5, v - 0.5, ang); - let w = (y * TAU * 2.0).sin() * amp * 0.1; - ((x + w) * TAU * n).sin() * 0.5 + 0.5 - })]) -} - -#[cfg(test)] -#[path = "patterns.test.rs"] -mod tests; diff --git a/_to_delete/nodes_patterns.test.rs b/_to_delete/nodes_patterns.test.rs deleted file mode 100644 index 33290c1..0000000 --- a/_to_delete/nodes_patterns.test.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Hostile-parameter tests for the binned pattern generators in `patterns.rs`. - -use std::collections::BTreeMap; - -use materialcraft_core::Value; -use materialcraft_image::Image; - -use crate::{Ctx, find, resolve_params}; - -fn cook(id: &str, over: &[(&str, Value)]) -> Image { - let def = find(id).unwrap(); - let over: BTreeMap<String, Value> = over.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(); - let params = resolve_params(def, &over); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = vec![None; def.inputs.len()]; - let ctx = Ctx { w: 32, h: 32, seed: 3, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - (def.cook)(&ctx).unwrap().remove(0) -} - -fn assert_quick(id: &str, over: &[(&str, Value)]) { - let t = std::time::Instant::now(); - let img = cook(id, over); - assert!(img.data.iter().all(|v| v.is_finite()), "{id} produced non-finite values"); - assert!(t.elapsed().as_secs() < 20, "{id} took {:?}", t.elapsed()); -} - -#[test] -fn splatter_huge_size_is_bounded() { - assert_quick("splatter", &[("size", Value::Float(1e6)), ("count", Value::Int(2000))]); -} - -#[test] -fn scratches_huge_length_is_bounded() { - assert_quick("scratches", &[("length", Value::Float(1e6)), ("width", Value::Float(1e6)), ("count", Value::Int(5000))]); -} diff --git a/_to_delete/nodes_patterns_more.rs b/_to_delete/nodes_patterns_more.rs deleted file mode 100644 index f1178e9..0000000 --- a/_to_delete/nodes_patterns_more.rs +++ /dev/null @@ -1,532 +0,0 @@ -//! More Texture generators › Patterns: tilings (herringbone, basketweave, planks, scales, -//! triangles, octagons, tread plate), grids, shapes and gradients. Tile patterns share gap, bevel -//! and luminance-random parameters; every tiling repeats a whole number of times per image. - -use std::f32::consts::{SQRT_2, TAU}; - -use crate::catalog::{B, CookResult, Ctx, NodeDef, node}; -use crate::noise::rand2; -use crate::patterns::PATTERNS; - -/// Rotate `(x, y)` by `turns`. -#[inline] -fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) { - let (s, c) = (turns * TAU).sin_cos(); - (x * c - y * s, x * s + y * c) -} - -/// Coverage from a signed inside distance `e`: hard when `soft` is 0, else a ramp of width `soft`. -#[inline] -fn fill(e: f32, soft: f32) -> f32 { - if soft <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / soft).clamp(0.0, 1.0) } -} - -/// A beveled tile from the distance `e` to its edge: `gap` eats the edge, `bevel` ramps up. -#[inline] -fn tile_height(e: f32, t: &TileLook, rnd: f32) -> f32 { - let e = e - t.gap * 0.5; - if e <= 0.0 { 0.0 } else { (e / t.bevel).min(1.0) * (1.0 - t.lum_random * rnd) } -} - -/// Soft bands around integer + 0.5 of `t`: `width` 0..1 of each period, `soft` edge. -#[inline] -fn band(t: f32, width: f32, soft: f32) -> f32 { - let d = (t.rem_euclid(1.0) - 0.5).abs() * 2.0; - ((width - d) / soft.max(1e-3) + 0.5).clamp(0.0, 1.0) -} - -/// Local coordinates -1..1 in an `n`×`n` repetition. -#[inline] -fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) { - ((u * n).rem_euclid(1.0) * 2.0 - 1.0, (v * n).rem_euclid(1.0) * 2.0 - 1.0) -} - -struct TileLook { - gap: f32, - bevel: f32, - lum_random: f32, - seed: u32, -} - -fn look(ctx: &Ctx) -> TileLook { - TileLook { gap: ctx.f("gap"), bevel: ctx.f("bevel").max(1e-4), lum_random: ctx.f("lum_random"), seed: ctx.seed } -} - -/// The gap, bevel and luminance-random parameters of tile patterns. -fn with_look(b: B, gap: f32, bevel: f32) -> B { - b.float("gap", "Gap", gap, 0.0, 0.5).float("bevel", "Bevel", bevel, 0.0, 1.0).float("lum_random", "Luminance random", 0.3, 0.0, 1.0) -} - -fn n(ctx: &Ctx, id: &str) -> f32 { - ctx.i(id).max(1) as f32 -} - -pub(crate) fn defs() -> Vec<NodeDef> { - let p = |id, label| node(id, label, PATTERNS).generator(); - vec![ - p("grid_lines", "Grid Lines") - .desc("A grid of lines.") - .int("tiling", "Tiling", 8, 1, 128) - .float("width", "Line width", 0.06, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 0.5) - .gray_out() - .cook(grid_lines), - p("dots_grid", "Dots Grid") - .desc("Round dots on a grid (perforated metal, polka dots).") - .int("tiling", "Tiling", 8, 1, 128) - .float("radius", "Diameter", 0.6, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 0.5) - .boolean("staggered", "Staggered rows", true) - .gray_out() - .cook(dots_grid), - with_look(p("diamond_grid", "Diamond Grid").desc("Beveled diamond (45°) tiles.").int("tiling", "Tiling", 4, 1, 64), 0.05, 0.15) - .gray_out() - .cook(diamond_grid), - with_look( - p("herringbone", "Herringbone").desc("Planks laid in a herringbone pattern.").int("tiling", "Tiling", 2, 1, 32).int( - "length", - "Plank length", - 3, - 2, - 8, - ), - 0.08, - 0.2, - ) - .gray_out() - .cook(herringbone), - with_look( - p("basketweave", "Basketweave").desc("Squares of parallel planks alternating direction.").int("tiling", "Tiling", 4, 1, 64).int( - "strips", - "Planks per square", - 3, - 1, - 16, - ), - 0.08, - 0.2, - ) - .gray_out() - .cook(basketweave), - p("chevron", "Chevron") - .desc("Zigzag bands.") - .int("count", "Bands", 8, 1, 128) - .int("zigs", "Zigzags", 4, 1, 64) - .float("height", "Zig height", 1.0, 0.0, 8.0) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.1, 0.0, 1.0) - .gray_out() - .cook(chevron), - p("fish_scales", "Fish Scales") - .desc("Overlapping rows of round scales (height).") - .int("tiling", "Tiling", 6, 1, 64) - .float("radius", "Radius", 0.65, 0.5, 1.0) - .float("lum_random", "Luminance random", 0.2, 0.0, 1.0) - .gray_out() - .cook(fish_scales), - with_look(p("triangle_grid", "Triangle Grid").desc("Beveled triangle tiles.").int("tiling", "Tiling", 6, 1, 64), 0.04, 0.12) - .gray_out() - .cook(triangle_grid), - p("spiral", "Spiral") - .desc("An Archimedean spiral.") - .float("turns", "Turns", 6.0, 0.0, 64.0) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.3, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(spiral), - p("concentric_rings", "Concentric Rings") - .desc("Rings around the center.") - .float("count", "Rings", 8.0, 0.0, 64.0) - .float("width", "Width", 0.5, 0.0, 1.0) - .float("softness", "Softness", 0.3, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(concentric_rings), - p("gradient_axial", "Gradient Axial") - .desc("A ramp from point 1 (black) to point 2 (white).") - .float2("point_1", "Point 1", [0.2, 0.5], 0.0, 1.0) - .float2("point_2", "Point 2", [0.8, 0.5], 0.0, 1.0) - .gray_out() - .cook(gradient_axial), - p("gradient_circular", "Gradient Circular") - .desc("A ramp around the center (by angle).") - .angle("angle", "Start angle", 0.0) - .int("tiling", "Tiling", 1, 1, 16) - .gray_out() - .cook(gradient_circular), - p("cross", "Cross") - .desc("A plus-shaped cross.") - .float("length", "Arm length", 0.8, 0.0, 1.0) - .float("thickness", "Thickness", 0.25, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .int("tiling", "Tiling", 1, 1, 32) - .gray_out() - .cook(cross), - p("rounded_rectangle", "Rounded Rectangle") - .desc("A rectangle with rounded corners.") - .float2("size", "Size", [0.8, 0.6], 0.0, 1.0) - .float("radius", "Corner radius", 0.2, 0.0, 1.0) - .float("softness", "Softness", 0.0, 0.0, 1.0) - .angle("angle", "Angle", 0.0) - .int("tiling", "Tiling", 1, 1, 32) - .gray_out() - .cook(rounded_rectangle), - p("ring", "Ring") - .desc("A circular ring.") - .float("radius", "Radius", 0.6, 0.0, 1.0) - .float("width", "Width", 0.15, 0.0, 1.0) - .float("softness", "Softness", 0.05, 0.0, 1.0) - .int("tiling", "Tiling", 1, 1, 32) - .gray_out() - .cook(ring), - with_look( - p("arc_pavement", "Arc Pavement") - .desc("Cobblestones laid in overlapping fan-shaped arcs.") - .int("tiling", "Tiling", 3, 1, 32) - .int("bands", "Rows per arc", 4, 1, 16) - .int("stones", "Stones in outer row", 7, 1, 32), - 0.08, - 0.25, - ) - .gray_out() - .cook(arc_pavement), - with_look(p("octagon_tiles", "Octagon Tiles").desc("Octagons with small square tiles between them.").int("tiling", "Tiling", 4, 1, 64), 0.03, 0.08) - .gray_out() - .cook(octagon_tiles), - with_look( - p("planks", "Planks") - .desc("Rows of floor boards of random length, staggered.") - .int("rows", "Rows", 8, 1, 64) - .float("length", "Plank length", 0.33, 0.02, 1.0) - .float("length_random", "Length random", 0.5, 0.0, 1.0), - 0.06, - 0.15, - ) - .gray_out() - .cook(planks), - p("tread_plate", "Tread Plate") - .desc("Raised diagonal bars alternating direction, like metal floor plates (height).") - .int("tiling", "Tiling", 6, 1, 64) - .float("length", "Bar length", 1.0, 0.0, 1.4) - .float("width", "Bar width", 0.3, 0.01, 1.0) - .gray_out() - .cook(tread_plate), - ] -} - -fn grid_lines(ctx: &Ctx) -> CookResult { - let (t, w, soft) = (n(ctx, "tiling"), ctx.f("width"), ctx.f("softness")); - Ok(vec![ctx.gen_gray(|u, v| { - let d = |a: f32| { - let f = (a * t).rem_euclid(1.0); - f.min(1.0 - f) - }; - fill(w * 0.5 - d(u).min(d(v)), soft) - })]) -} - -fn dots_grid(ctx: &Ctx) -> CookResult { - let (t, r, soft, stag) = (n(ctx, "tiling"), ctx.f("radius"), ctx.f("softness"), ctx.b("staggered")); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * t).floor(); - // A parity shift (not row × offset) keeps the pattern seamless for any row count. - let shift = if stag && (row as i32) & 1 == 1 { 0.5 } else { 0.0 }; - let (x, y) = ((u * t + shift).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5); - fill(r * 0.5 - (x * x + y * y).sqrt(), soft * 0.5) - })]) -} - -fn diamond_grid(ctx: &Ctx) -> CookResult { - let (t, l) = (n(ctx, "tiling"), look(ctx)); - let ti = t as i32; - Ok(vec![ctx.gen_gray(|u, v| { - let (a, b) = ((u + v) * t, (u - v) * t); - let (fa, fb) = (a.rem_euclid(1.0), b.rem_euclid(1.0)); - let e = fa.min(1.0 - fa).min(fb).min(1.0 - fb); - // Canonical diamond index: (A, B) ~ (A + t, B ± t). - let (ia, ib) = (a.floor() as i32, b.floor() as i32); - let k = ib.div_euclid(ti); - tile_height(e, &l, rand2((ia - k * ti).rem_euclid(2 * ti), ib - k * ti, l.seed)) - })]) -} - -fn herringbone(ctx: &Ctx) -> CookResult { - let (t, len, lk) = (n(ctx, "tiling") as i32, ctx.i("length").clamp(2, 8), look(ctx)); - let lf = len as f32; - let span = (t * 2 * len) as f32; - // 1 × L planks: a horizontal plank [0, L)×[0, 1) and a vertical one [L, L+1)×[1-L, 1) repeat - // on the lattice m·(1, 1) + n·(L, -L), which has period 2L on both axes. - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = (u * span, v * span); - let (m0, n0) = (((x + y) * 0.5).floor() as i32, ((x - y) / (2.0 * lf)).floor() as i32); - for dm in -(len / 2 + 2)..=1 { - for dn in -2..=1 { - let (m, nn) = (m0 + dm, n0 + dn); - let (qx, qy) = (x - (m + nn * len) as f32, y - (m - nn * len) as f32); - let hit = if (0.0..lf).contains(&qx) && (0.0..1.0).contains(&qy) { - Some((qx.min(lf - qx).min(qy).min(1.0 - qy), 0)) - } else if (lf..lf + 1.0).contains(&qx) && (1.0 - lf..1.0).contains(&qy) { - Some(((qx - lf).min(lf + 1.0 - qx).min(qy - 1.0 + lf).min(1.0 - qy), 1)) - } else { - None - }; - if let Some((e, kind)) = hit { - let k = nn.div_euclid(t); - let (cm, cn) = ((m - k * len * t).rem_euclid(2 * len * t), nn - k * t); - return tile_height(e, &lk, rand2(cm * 2 + kind, cn, lk.seed)); - } - } - } - 0.0 - })]) -} - -fn basketweave(ctx: &Ctx) -> CookResult { - let (t, strips, l) = (n(ctx, "tiling"), n(ctx, "strips"), look(ctx)); - Ok(vec![ctx.gen_gray(|u, v| { - let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32); - let (fx, fy) = ((u * t).rem_euclid(1.0), (v * t).rem_euclid(1.0)); - let horizontal = (cx + cy) & 1 == 0; - let (across, along) = if horizontal { (fy * strips, fx * strips) } else { (fx * strips, fy * strips) }; - let fa = across.rem_euclid(1.0); - let e = fa.min(1.0 - fa).min(along).min(strips - along); - let id = (cy.rem_euclid(t as i32) * t as i32 + cx.rem_euclid(t as i32)) * 16 + across.floor() as i32; - tile_height(e, &l, rand2(id, 0, l.seed)) - })]) -} - -fn chevron(ctx: &Ctx) -> CookResult { - let (c, z, hgt, w, soft) = (n(ctx, "count"), n(ctx, "zigs"), ctx.f("height"), ctx.f("width"), ctx.f("softness")); - Ok(vec![ctx.gen_gray(|u, v| { - let zig = ((u * z).rem_euclid(1.0) - 0.5).abs() * 2.0; - band(v * c + zig * hgt, w, soft) - })]) -} - -/// The topmost scale over `(x, y)` (in cells) of a staggered scale layout: rows 0.5 apart, odd -/// rows shifted by half a cell, earlier rows on top. Returns (column, row, dx, dy, d / r). -fn scale_hit(x: f32, y: f32, r: f32) -> Option<(i32, i32, f32, f32, f32)> { - let j0 = ((y - r) * 2.0).floor() as i32; - let j1 = ((y + r) * 2.0).ceil() as i32; - for j in j0..=j1 { - let shift = if j & 1 == 1 { 0.5 } else { 0.0 }; - let i = (x - shift).round() as i32; - let (dx, dy) = (x - (i as f32 + shift), y - j as f32 * 0.5); - let d = (dx * dx + dy * dy).sqrt(); - if d < r { - return Some((i, j, dx, dy, d / r)); - } - } - None -} - -fn fish_scales(ctx: &Ctx) -> CookResult { - let (t, r, lr, s) = (n(ctx, "tiling"), ctx.f("radius").clamp(0.5, 1.0), ctx.f("lum_random"), ctx.seed); - let ti = t as i32; - Ok(vec![ctx.gen_gray(|u, v| { - let Some((i, j, _, _, d)) = scale_hit(u * t, v * t, r) else { - return 0.0; - }; - (1.0 - d * d).sqrt() * (1.0 - lr * rand2(i.rem_euclid(ti), j.rem_euclid(2 * ti), s)) - })]) -} - -fn triangle_grid(ctx: &Ctx) -> CookResult { - let (t, l) = (n(ctx, "tiling"), look(ctx)); - // Rows of near-equilateral triangles; an even row count keeps the half-cell row shift seamless. - let rows = (2.0 * (t * 0.577).round()).max(2.0); - let (ti, ri) = (t as i32, rows as i32); - let k = 2.0 / 5f32.sqrt(); - Ok(vec![ctx.gen_gray(|u, v| { - let row = (v * rows).floor() as i32; - let fy = (v * rows).rem_euclid(1.0); - let x = u * t + if row & 1 == 1 { 0.5 } else { 0.0 }; - let col = x.floor() as i32; - let dx = x.rem_euclid(1.0) - 0.5; - let (e, id) = if dx.abs() <= fy * 0.5 { - ((1.0 - fy).min((fy * 0.5 - dx.abs()) * k), col * 2) - } else { - // A down-pointing triangle centered on the nearer whole column. - let (c, ddx) = if dx < 0.0 { (col, dx + 0.5) } else { (col + 1, dx - 0.5) }; - (fy.min(((1.0 - fy) * 0.5 - ddx.abs()) * k), c * 2 + 1) - }; - tile_height(e, &l, rand2(id.rem_euclid(2 * ti), row.rem_euclid(ri), l.seed)) - })]) -} - -fn spiral(ctx: &Ctx) -> CookResult { - let (turns, w, soft, t) = (ctx.f("turns"), ctx.f("width"), ctx.f("softness"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - let r = (x * x + y * y).sqrt(); - if r > 1.0 { - return 0.0; - } - band(r * turns - y.atan2(x) / TAU, w, soft) - })]) -} - -fn concentric_rings(ctx: &Ctx) -> CookResult { - let (c, w, soft, t) = (ctx.f("count"), ctx.f("width"), ctx.f("softness"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - band((x * x + y * y).sqrt() * c, w, soft) - })]) -} - -fn gradient_axial(ctx: &Ctx) -> CookResult { - let (a, b) = (ctx.v2("point_1"), ctx.v2("point_2")); - let (dx, dy) = (b[0] - a[0], b[1] - a[1]); - let len2 = (dx * dx + dy * dy).max(1e-8); - Ok(vec![ctx.gen_gray(|u, v| (((u - a[0]) * dx + (v - a[1]) * dy) / len2).clamp(0.0, 1.0))]) -} - -fn gradient_circular(ctx: &Ctx) -> CookResult { - let (a, t) = (ctx.f("angle"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - ((-y).atan2(x) / TAU - a).rem_euclid(1.0) - })]) -} - -fn cross(ctx: &Ctx) -> CookResult { - let (len, th, soft, a, t) = (ctx.f("length"), ctx.f("thickness") * 0.5, ctx.f("softness"), ctx.f("angle"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - let (x, y) = rot(x, y, a); - let arm = |p: f32, q: f32| (len - p.abs()).min(th - q.abs()); - fill(arm(x, y).max(arm(y, x)), soft) - })]) -} - -fn rounded_rectangle(ctx: &Ctx) -> CookResult { - let (sz, rad, soft, a, t) = (ctx.v2("size"), ctx.f("radius"), ctx.f("softness"), ctx.f("angle"), n(ctx, "tiling")); - let r = rad.min(sz[0]).min(sz[1]).max(0.0); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - let (x, y) = rot(x, y, a); - // Signed distance to a rounded box (negative inside). - let (qx, qy) = (x.abs() - sz[0] + r, y.abs() - sz[1] + r); - let d = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r; - fill(-d, soft) - })]) -} - -fn ring(ctx: &Ctx) -> CookResult { - let (rad, w, soft, t) = (ctx.f("radius"), ctx.f("width") * 0.5, ctx.f("softness"), n(ctx, "tiling")); - Ok(vec![ctx.gen_gray(|u, v| { - let (x, y) = tiled(u, v, t); - fill(w - ((x * x + y * y).sqrt() - rad).abs(), soft) - })]) -} - -fn arc_pavement(ctx: &Ctx) -> CookResult { - let (t, bands, stones, l) = (n(ctx, "tiling"), n(ctx, "bands"), n(ctx, "stones"), look(ctx)); - let ti = t as i32; - let r = 0.75; - Ok(vec![ctx.gen_gray(|u, v| { - let Some((i, j, dx, dy, rr)) = scale_hit(u * t, v * t, r) else { - return 0.0; - }; - let band_f = rr * bands; - let k = band_f.floor(); - let count = (stones * (k + 0.5) / bands).round().max(1.0); - let a = (dy.atan2(dx) / TAU + 0.5) * count; - let fr = band_f.rem_euclid(1.0); - let fa = a.rem_euclid(1.0); - // Distances in band-width units: radial, and along the arc at this radius. - let e = fr.min(1.0 - fr).min(fa.min(1.0 - fa) * TAU * band_f.max(0.5) / count); - let id = ((j.rem_euclid(2 * ti) * ti + i.rem_euclid(ti)) * 32 + k as i32) * 64 + a.floor() as i32; - tile_height(e, &l, rand2(id, 7, l.seed)) - })]) -} - -fn octagon_tiles(ctx: &Ctx) -> CookResult { - let (t, l) = (n(ctx, "tiling"), look(ctx)); - let ti = t as i32; - // A regular octagon in a unit cell: its corner cuts lie on |x| + |y| = 0.5 + side / 2. - let cut = 0.5 + 0.5 / (1.0 + SQRT_2); - Ok(vec![ctx.gen_gray(|u, v| { - let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32); - let (x, y) = ((u * t).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5); - let (ax, ay) = (x.abs(), y.abs()); - if ax + ay <= cut { - let e = (0.5 - ax.max(ay)).min((cut - ax - ay) / SQRT_2); - tile_height(e, &l, rand2(cx.rem_euclid(ti), cy.rem_euclid(ti), l.seed)) - } else { - // The small square around the nearest cell corner. - let e = (ax + ay - cut) / SQRT_2; - let (kx, ky) = (cx + (x > 0.0) as i32, cy + (y > 0.0) as i32); - tile_height(e, &l, rand2(kx.rem_euclid(ti), ky.rem_euclid(ti), l.seed ^ 0x6d)) - } - })]) -} - -fn planks(ctx: &Ctx) -> CookResult { - let (rows, l) = (n(ctx, "rows"), look(ctx)); - let count = (1.0 / ctx.f("length").max(0.02)).round().clamp(1.0, 64.0); - let (ci, ri) = (count as i32, rows as i32); - let jit = ctx.f("length_random").clamp(0.0, 1.0) * 0.4; - let s = ctx.seed; - Ok(vec![ctx.gen_gray(|u, v| { - let row = ((v * rows).floor() as i32).rem_euclid(ri); - let fy = (v * rows).rem_euclid(1.0); - let t = u * count + rand2(row, 0, s ^ 0x11) * count; - // Plank ends: one per whole step of `t`, jittered; indices wrap so each row tiles. - let cut = |j: i32| j as f32 + (rand2(j.rem_euclid(ci), row, s) - 0.5) * 2.0 * jit; - let j = t.floor() as i32; - let j = if t < cut(j) { - j - 1 - } else if t >= cut(j + 1) { - j + 1 - } else { - j - }; - let along = (t - cut(j)).min(cut(j + 1) - t) / count * rows; - let e = along.min(fy).min(1.0 - fy); - tile_height(e, &l, rand2(j.rem_euclid(ci), row, s ^ 0x22)) - })]) -} - -fn tread_plate(ctx: &Ctx) -> CookResult { - let (t, len, w) = (n(ctx, "tiling"), ctx.f("length") * 0.5, ctx.f("width").max(0.01) * 0.5); - Ok(vec![ctx.gen_gray(|u, v| { - let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32); - let (x, y) = ((u * t).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5); - let turn = if (cx + cy) & 1 == 0 { 0.125 } else { -0.125 }; - let (x, y) = rot(x, y, turn); - // An elongated lens with a flat top and rounded flanks. - let d = ((x / len.max(1e-3)).powi(2) + (y / w).powi(2)).sqrt(); - (1.0 - d.powi(4)).max(0.0).sqrt() - })]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use crate::{Ctx, find, resolve_params}; - - #[test] - fn tilings_wrap_seamlessly() { - for id in ["herringbone", "planks", "triangle_grid", "fish_scales", "arc_pavement", "diamond_grid", "octagon_tiles"] { - let def = find(id).unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: 128, h: 128, seed: 5, tile: true, inputs: &[], params: ¶ms, resource: &no_res, vars: &vars }; - let img = &(def.cook)(&ctx).unwrap()[0]; - // Sampling the pattern one period further along either axis gives the same image: the - // last column/row continues into the first like any interior neighbour. - let (mut seam, mut inner) = (0.0f32, 0.0f32); - for k in 0..128 { - seam += (img.get(127, k, false)[0] - img.get(0, k, false)[0]).abs() + (img.get(k, 127, false)[0] - img.get(k, 0, false)[0]).abs(); - inner += (img.get(63, k, false)[0] - img.get(64, k, false)[0]).abs() + (img.get(k, 63, false)[0] - img.get(k, 64, false)[0]).abs(); - } - assert!(seam <= inner * 3.0 + 1.0, "{id}: seam {seam} vs inner {inner}"); - assert!(img.mean()[0] > 0.05, "{id} is empty"); - } - } -} diff --git a/_to_delete/nodes_svg.rs b/_to_delete/nodes_svg.rs deleted file mode 100644 index 564477b..0000000 --- a/_to_delete/nodes_svg.rs +++ /dev/null @@ -1,487 +0,0 @@ -//! Atomic › SVG: rasterizes SVG path data (the `d` attribute: M L H V C S Q T Z, absolute and -//! relative) with an even-odd or non-zero fill and an optional stroke. Fill coverage is exact -//! horizontally over four sub-scanlines per pixel. Also the shared capsule (thick line) -//! rasterizer used by the stroke, the Text node and the scratches. - -use materialcraft_image::{Image, Kind}; -use rayon::prelude::*; - -use crate::atomic::ATOMIC; -use crate::catalog::{CookResult, Ctx, NodeDef, node}; - -/// A leaf with a midrib slit, in 0..100 units. -const DEFAULT_PATH: &str = "M50 4 C80 20 94 55 52 96 L50 90 L48 96 C6 55 20 20 50 4 Z M49 22 Q46 55 50 84 Q54 55 51 22 Z"; - -/// Most points a path may flatten to (an allocation cap for hostile input). -const MAX_POINTS: usize = 400_000; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("svg", "SVG", ATOMIC) - .desc("Draws SVG path data (M L H V C S Q T Z, absolute and relative; y points down) filled and optionally stroked, anti-aliased.") - .atomic() - .generator() - .text("path", "Path data", DEFAULT_PATH) - .choice("units", "Units", &["0..1", "0..100"], 1) - .color("fill", "Fill color", [1.0, 1.0, 1.0, 1.0]) - .choice("fill_rule", "Fill rule", &["Even-odd", "Non-zero"], 1) - .float("stroke_width", "Stroke width", 0.0, 0.0, 64.0) - .color("stroke", "Stroke color", [0.5, 0.5, 0.5, 1.0]) - .color_out() - .cook(svg), - ] -} - -/// A flattened subpath in path units; `closed` after Z. -#[derive(Clone, Debug, PartialEq)] -pub struct Poly { - pub pts: Vec<[f32; 2]>, - pub closed: bool, -} - -struct Lexer<'a> { - s: &'a [u8], - i: usize, -} - -impl Lexer<'_> { - fn skip(&mut self) { - while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') { - self.i += 1; - } - } - - fn peek(&mut self) -> Option<u8> { - self.skip(); - self.s.get(self.i).copied() - } - - fn at_number(&mut self) -> bool { - self.peek().is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.')) - } - - fn number(&mut self) -> Result<f32, String> { - self.skip(); - let (start, s) = (self.i, self.s); - let digit = |j: usize| s.get(j).is_some_and(u8::is_ascii_digit); - let mut j = start + matches!(s.get(start), Some(b'+' | b'-')) as usize; - let mut digits = 0; - while digit(j) { - j += 1; - digits += 1; - } - if s.get(j) == Some(&b'.') { - j += 1; - while digit(j) { - j += 1; - digits += 1; - } - } - if digits == 0 { - return Err(format!("expected a number at byte {start}")); - } - if matches!(s.get(j), Some(b'e' | b'E')) { - let mut k = j + 1 + matches!(s.get(j + 1), Some(b'+' | b'-')) as usize; - let k0 = k; - while digit(k) { - k += 1; - } - if k > k0 { - j = k; - } - } - let txt = s.get(start..j).and_then(|b| std::str::from_utf8(b).ok()).unwrap_or(""); - let v: f32 = txt.parse().map_err(|_| format!("bad number '{txt}' at byte {start}"))?; - if !v.is_finite() { - return Err(format!("number out of range at byte {start}")); - } - self.i = j; - Ok(v) - } - - fn pair(&mut self) -> Result<[f32; 2], String> { - Ok([self.number()?, self.number()?]) - } -} - -/// Builds flattened subpaths while parsing. -struct Pen { - polys: Vec<Poly>, - cur: [f32; 2], - start: [f32; 2], - /// The previous segment's last control point and whether it was cubic (for S and T). - ctrl: Option<([f32; 2], bool)>, - steps_per_unit: f32, - points: usize, -} - -impl Pen { - fn push(&mut self, p: [f32; 2]) -> Result<(), String> { - self.points += 1; - if self.points > MAX_POINTS { - return Err(format!("path too complex (over {MAX_POINTS} points)")); - } - match self.polys.last_mut() { - Some(poly) if !poly.closed => poly.pts.push(p), - // Drawing after Z starts a new subpath at the closed one's start. - _ => self.polys.push(Poly { pts: vec![self.start, p], closed: false }), - } - self.cur = p; - Ok(()) - } - - fn move_to(&mut self, p: [f32; 2]) { - self.polys.push(Poly { pts: vec![p], closed: false }); - (self.cur, self.start) = (p, p); - } - - /// A Bézier through `ctrl` (2 or 3 points after the current one), flattened in steps of - /// about 1 / `steps_per_unit` along its control polygon. - fn curve(&mut self, ctrl: &[[f32; 2]]) -> Result<(), String> { - let mut pts = vec![self.cur]; - pts.extend_from_slice(ctrl); - let len: f32 = pts.windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum(); - let n = (len * self.steps_per_unit).ceil().clamp(2.0, 256.0) as usize; - for k in 1..=n { - let t = k as f32 / n as f32; - // De Casteljau. - let mut q = pts.clone(); - while q.len() > 1 { - q = q.windows(2).map(|w| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t]).collect(); - } - self.push(q.first().copied().unwrap_or(self.cur))?; - } - Ok(()) - } - - fn reflect(&self, cubic: bool) -> [f32; 2] { - match self.ctrl { - Some((c, was_cubic)) if was_cubic == cubic => [2.0 * self.cur[0] - c[0], 2.0 * self.cur[1] - c[1]], - _ => self.cur, - } - } -} - -/// Parses SVG path data into flattened subpaths. Curves get about `steps_per_unit` segments per -/// unit of control-polygon length (2..256 per curve). Bad input is an error, never a panic. -pub fn parse_path(d: &str, steps_per_unit: f32) -> Result<Vec<Poly>, String> { - let mut lx = Lexer { s: d.as_bytes(), i: 0 }; - let steps_per_unit = if steps_per_unit.is_finite() { steps_per_unit.max(0.0) } else { 0.0 }; - let mut pen = Pen { polys: Vec::new(), cur: [0.0; 2], start: [0.0; 2], ctrl: None, steps_per_unit, points: 0 }; - let mut prev: Option<u8> = None; - while let Some(c) = lx.peek() { - let op = if c.is_ascii_alphabetic() { - lx.i += 1; - c - } else if lx.at_number() { - // Repeated arguments repeat the command; extra pairs after a move are lines. - match prev { - Some(b'M') => b'L', - Some(b'm') => b'l', - Some(p) if !matches!(p, b'Z' | b'z') => p, - _ => return Err(format!("number without a command at byte {}", lx.i)), - } - } else { - return Err(format!("unexpected '{}' at byte {}", c as char, lx.i)); - }; - if prev.is_none() && !matches!(op, b'M' | b'm') { - return Err("path data must start with a move (M)".into()); - } - let rel = op.is_ascii_lowercase(); - let o = if rel { pen.cur } else { [0.0; 2] }; - let at = |p: [f32; 2]| [p[0] + o[0], p[1] + o[1]]; - let mut ctrl = None; - match op.to_ascii_uppercase() { - b'M' => pen.move_to(at(lx.pair()?)), - b'L' => pen.push(at(lx.pair()?))?, - b'H' => pen.push([lx.number()? + o[0], pen.cur[1]])?, - b'V' => pen.push([pen.cur[0], lx.number()? + o[1]])?, - b'C' => { - let (c1, c2, p) = (at(lx.pair()?), at(lx.pair()?), at(lx.pair()?)); - pen.curve(&[c1, c2, p])?; - ctrl = Some((c2, true)); - } - b'S' => { - let c1 = pen.reflect(true); - let (c2, p) = (at(lx.pair()?), at(lx.pair()?)); - pen.curve(&[c1, c2, p])?; - ctrl = Some((c2, true)); - } - b'Q' => { - let (c1, p) = (at(lx.pair()?), at(lx.pair()?)); - pen.curve(&[c1, p])?; - ctrl = Some((c1, false)); - } - b'T' => { - let c1 = pen.reflect(false); - pen.curve(&[c1, at(lx.pair()?)])?; - ctrl = Some((c1, false)); - } - b'Z' => { - if let Some(p) = pen.polys.last_mut() { - p.closed = true; - } - pen.cur = pen.start; - } - b'A' => return Err("arc commands (A) are not supported; use curves".into()), - _ => return Err(format!("unknown command '{}'", op as char)), - } - pen.ctrl = ctrl; - prev = Some(op); - } - Ok(pen.polys) -} - -/// Fill coverage (0..1 per pixel, row-major) of polygons in pixel coordinates (each implicitly -/// closed): exact horizontal span coverage on four sub-scanlines per pixel row. -pub(crate) fn fill(w: u32, h: u32, polys: &[Vec<[f32; 2]>], even_odd: bool) -> Vec<f32> { - // Edges as (x0, y0, x1, y1, winding) with y0 < y1. - let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new(); - for p in polys { - for (k, a) in p.iter().enumerate() { - let b = p.get(k + 1).or(p.first()).copied().unwrap_or(*a); - if a[1] < b[1] { - edges.push((a[0], a[1], b[0], b[1], 1)); - } else if b[1] < a[1] { - edges.push((b[0], b[1], a[0], a[1], -1)); - } - } - } - let wu = w as usize; - let rows: Vec<Vec<f32>> = (0..h) - .into_par_iter() - .map(|y| { - let mut row = vec![0.0f32; wu]; - let mut xs: Vec<(f32, i32)> = Vec::new(); - for s in 0..4 { - let sy = y as f32 + (s as f32 + 0.5) * 0.25; - xs.clear(); - xs.extend(edges.iter().filter(|e| e.1 <= sy && sy < e.3).map(|e| (e.0 + (sy - e.1) * (e.2 - e.0) / (e.3 - e.1), e.4))); - xs.sort_by(|a, b| a.0.total_cmp(&b.0)); - let mut wind = 0; - for k in 0..xs.len() { - wind += xs[k].1; - let inside = if even_odd { wind & 1 != 0 } else { wind != 0 }; - if let (true, Some(next)) = (inside, xs.get(k + 1)) { - add_span(&mut row, xs[k].0, next.0, 0.25); - } - } - } - row - }) - .collect(); - rows.concat() -} - -/// Adds `wt` × the overlap of `[a, b)` with each pixel of `row`. -fn add_span(row: &mut [f32], a: f32, b: f32, wt: f32) { - let n = row.len() as f32; - let (a, b) = (a.clamp(0.0, n), b.clamp(0.0, n)); - if b <= a { - return; - } - for px in a.floor() as usize..(b.ceil() as usize).min(row.len()) { - let ov = b.min(px as f32 + 1.0) - a.max(px as f32); - if let Some(v) = row.get_mut(px) { - *v += ov.max(0.0) * wt; - } - } -} - -/// A line segment with a weight (its peak coverage). -#[derive(Clone, Copy, Debug)] -pub(crate) struct Seg { - pub a: [f32; 2], - pub b: [f32; 2], - pub wt: f32, -} - -/// Thick line segments ("capsules") of radius `r` in pixel space, binned on a grid for fast -/// lookups. Coverage ramps over one pixel at the border (anti-aliased); with `tile` it wraps. -pub(crate) struct Capsules { - segs: Vec<Seg>, - r: f32, - g: usize, - cell: [f32; 2], - bins: Vec<Vec<u32>>, - size: [f32; 2], - tile: bool, -} - -impl Capsules { - pub fn new(segs: Vec<Seg>, r: f32, w: u32, h: u32, tile: bool) -> Capsules { - let r = if r.is_finite() { r.max(0.0) } else { 0.0 }; - let reach = r + 1.0; - let g = ((w.max(h) as f32 / (reach * 4.0).max(8.0)) as usize).clamp(1, 128); - let cell = [w as f32 / g as f32, h as f32 / g as f32]; - let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g]; - for (i, s) in segs.iter().enumerate() { - if !s.a.iter().chain(&s.b).all(|v| v.is_finite()) { - continue; - } - let span = |a: f32, b: f32, c: f32| { - let lo = ((a.min(b) - reach) / c).floor() as i64; - (lo, (((a.max(b) + reach) / c).floor() as i64).min(lo + g as i64 - 1)) - }; - let ((x0, x1), (y0, y1)) = (span(s.a[0], s.b[0], cell[0]), span(s.a[1], s.b[1], cell[1])); - for gy in y0..=y1 { - for gx in x0..=x1 { - if !tile && (gx < 0 || gy < 0 || gx >= g as i64 || gy >= g as i64) { - continue; - } - if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) { - b.push(i as u32); - } - } - } - } - Capsules { segs, r, g, cell, bins, size: [w as f32, h as f32], tile } - } - - /// Coverage (0..1, the strongest segment's weight) at pixel coordinates `(x, y)`. - pub fn coverage(&self, x: f32, y: f32) -> f32 { - let (gx, gy) = (((x / self.cell[0]) as usize).min(self.g - 1), ((y / self.cell[1]) as usize).min(self.g - 1)); - let mut best = 0.0f32; - for &i in self.bins.get(gy * self.g + gx).into_iter().flatten() { - let Some(s) = self.segs.get(i as usize) else { continue }; - let (mut px, mut py) = (x - s.a[0], y - s.a[1]); - if self.tile { - px -= (px / self.size[0]).round() * self.size[0]; - py -= (py / self.size[1]).round() * self.size[1]; - } - let (dx, dy) = (s.b[0] - s.a[0], s.b[1] - s.a[1]); - let t = ((px * dx + py * dy) / (dx * dx + dy * dy).max(1e-12)).clamp(0.0, 1.0); - let d = ((px - dx * t).powi(2) + (py - dy * t).powi(2)).sqrt(); - best = best.max((self.r - d + 0.5).clamp(0.0, 1.0) * s.wt); - } - best - } -} - -/// A color image from fill and stroke coverage over transparent black (premultiplied). -pub(crate) fn composite( - w: u32, - h: u32, - fill: [f32; 4], - cover: impl Fn(u32, u32) -> f32 + Sync, - stroke: [f32; 4], - stroke_cover: impl Fn(u32, u32) -> f32 + Sync, -) -> Image { - Image::generate(w, h, Kind::Color, |x, y| { - let f = cover(x, y).clamp(0.0, 1.0) * fill[3]; - let s = stroke_cover(x, y).clamp(0.0, 1.0) * stroke[3]; - let k = f * (1.0 - s); - [fill[0] * k + stroke[0] * s, fill[1] * k + stroke[1] * s, fill[2] * k + stroke[2] * s, k + s] - }) -} - -fn svg(ctx: &Ctx) -> CookResult { - let unit = if ctx.i("units") == 1 { 100.0 } else { 1.0 }; - let (sx, sy) = (ctx.w as f32 / unit, ctx.h as f32 / unit); - // About one curve segment per 3 pixels. - let polys = parse_path(ctx.text("path"), sx.max(sy) / 3.0)?; - let rings: Vec<Vec<[f32; 2]>> = polys.iter().map(|p| p.pts.iter().map(|q| [q[0] * sx, q[1] * sy]).collect()).collect(); - let cov = fill(ctx.w, ctx.h, &rings, ctx.i("fill_rule") == 0); - let sw = ctx.f("stroke_width").max(0.0) * ctx.w as f32 / 256.0; - let caps = (sw > 0.0).then(|| { - let mut segs = Vec::new(); - for (p, ring) in polys.iter().zip(&rings) { - segs.extend(ring.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 })); - if let (true, Some(a), Some(b)) = (p.closed, ring.last(), ring.first()) { - segs.push(Seg { a: *a, b: *b, wt: 1.0 }); - } - if ring.len() == 1 { - segs.extend(ring.first().map(|a| Seg { a: *a, b: *a, wt: 1.0 })); - } - } - Capsules::new(segs, sw * 0.5, ctx.w, ctx.h, false) - }); - let w = ctx.w as usize; - Ok(vec![composite( - ctx.w, - ctx.h, - ctx.v4("fill"), - |x, y| cov.get(y as usize * w + x as usize).copied().unwrap_or(0.0), - ctx.v4("stroke"), - |x, y| caps.as_ref().map_or(0.0, |c| c.coverage(x as f32 + 0.5, y as f32 + 0.5)), - )]) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn pts(d: &str) -> Vec<Vec<[f32; 2]>> { - parse_path(d, 1.0).unwrap().into_iter().map(|p| p.pts).collect() - } - - #[test] - fn parses_lines_absolute_and_relative() { - assert_eq!(pts("M0 0 L10 0 L10 10 Z"), vec![vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]]); - assert_eq!(pts("m1,1 l2,0 0,2 h-2 v-1"), vec![vec![[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0], [1.0, 2.0]]]); - // Extra pairs after M are lines; compact number syntax. - assert_eq!(pts("M0 0 1 1 2-2"), vec![vec![[0.0, 0.0], [1.0, 1.0], [2.0, -2.0]]]); - assert_eq!(pts("M.5.5L1e1-1E0"), vec![vec![[0.5, 0.5], [10.0, -1.0]]]); - assert_eq!(pts("M0 0H5V5H0z M8 8 L9 9").len(), 2); - } - - #[test] - fn parses_curves_to_their_endpoints() { - for d in - ["M0 0 C0 10 10 10 10 0", "M0 0 c0 10 10 10 10 0", "M0 0 Q5 10 10 0", "M0 0 q5 10 10 0", "M0 0 Q5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 S10 -5 10 0"] - { - let p = pts(d); - let last = *p[0].last().unwrap(); - assert!((last[0] - 10.0).abs() < 1e-4 && last[1].abs() < 1e-4, "{d}: {last:?}"); - assert!(p[0].len() > 3, "{d} is flattened"); - } - // The cubic's midpoint bulges to 7.5. - let p = parse_path("M0 0 C0 10 10 10 10 0", 0.0).unwrap(); - assert_eq!(p[0].pts.len(), 3); - assert!((p[0].pts[1][1] - 7.5).abs() < 1e-4); - } - - #[test] - fn bad_paths_are_errors() { - for d in ["L0 0", "M0", "M0 0 L1", "M0 0 X1 1", "M0 0 L1 1e99", "M0 0 A1 1 0 0 1 2 2", "5 5", "M0 0 Z 3 4", "M 0 0 L - 1"] { - assert!(parse_path(d, 1.0).is_err(), "{d}"); - } - assert!(parse_path("", 1.0).unwrap().is_empty()); - assert!(parse_path("M0 0 C1 1 2 2 3 3", f32::NAN).is_ok()); - } - - #[test] - fn fill_rules_and_coverage() { - let sq = |a: f32, b: f32, ccw: bool| { - let mut v = vec![[a, a], [b, a], [b, b], [a, b]]; - if ccw { - v.reverse(); - } - v - }; - // Square of 4..12 on a 16×16 grid: area 64; a half-pixel edge gives half coverage. - let c = fill(16, 16, &[sq(4.0, 12.0, false)], false); - assert!((c.iter().sum::<f32>() - 64.0).abs() < 1e-3); - let c = fill(16, 16, &[sq(4.5, 12.0, false)], false); - assert!((c[8 * 16 + 4] - 0.5).abs() < 1e-4); - // A hole: even-odd always; non-zero only with opposite winding. - let eo = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], true); - let nz_same = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], false); - let nz_opp = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, true)], false); - let center = 8 * 16 + 8; - assert_eq!((eo[center], nz_same[center], nz_opp[center]), (0.0, 1.0, 0.0)); - } - - #[test] - fn default_svg_draws_the_leaf() { - let def = crate::catalog::find("svg").unwrap(); - let p = crate::catalog::resolve_params(def, &Default::default()); - let no_res = |_: &str| None; - let vars = Default::default(); - let ctx = Ctx { w: 64, h: 64, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; - let img = &svg(&ctx).unwrap()[0]; - let a = img.mean()[3]; - assert!(a > 0.2 && a < 0.7, "{a}"); - assert!(img.get(20, 32, false)[3] > 0.9 && img.get(2, 2, false)[3] == 0.0); - } -} diff --git a/_to_delete/nodes_text.rs b/_to_delete/nodes_text.rs deleted file mode 100644 index c0903e4..0000000 --- a/_to_delete/nodes_text.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! Atomic › Text: renders a string with MaterialCraft's own single-stroke vector font, drawn as -//! anti-aliased capsules. The font is original data defined below. - -use std::f32::consts::TAU; - -use crate::atomic::ATOMIC; -use crate::catalog::{CookResult, Ctx, NodeDef, node}; -use crate::svg::{Capsules, Seg, composite}; - -/// The font: each glyph is strokes separated by spaces, each stroke a polyline of `xy` digit -/// pairs on a grid 4 wide where y = 0 is the cap height, 2 the x-height, 6 the baseline and 8 -/// the descender. A single pair is a dot. Original design for MaterialCraft. -const GLYPHS: &[(char, &str)] = &[ - ('A', "062046 1333"), - ('B', "06003041423303 3344453606"), - ('C', "4130100105163645"), - ('D', "06003041453606"), - ('E', "40000646 0333"), - ('F', "400006 0333"), - ('G', "41301001051636454323"), - ('H', "0006 4046 0343"), - ('I', "1030 2026 1636"), - ('J', "4045361605"), - ('K', "0006 4004 1346"), - ('L', "000646"), - ('M', "0600234046"), - ('N', "06004640"), - ('O', "103041453616050110"), - ('P', "06003041423303"), - ('Q', "103041453616050110 2446"), - ('R', "06003041423303 2346"), - ('S', "413010010213334445361605"), - ('T', "0040 2026"), - ('U', "000516364540"), - ('V', "002640"), - ('W', "0016233640"), - ('X', "0046 4006"), - ('Y', "002340 2326"), - ('Z', "00400646"), - ('a', "4246 4332120305163645"), - ('b', "0006 0312324345361605"), - ('c', "4332120305163645"), - ('d', "4046 4332120305163645"), - ('e', "04444332120305163645"), - ('f', "4130201116 0232"), - ('g', "4247381807 4332120305163645"), - ('h', "0006 0312324346"), - ('i', "2226 20"), - ('j', "3237281807 30"), - ('k', "0006 3205 1436"), - ('l', "10202536"), - ('m', "0206 03122326 23324346"), - ('n', "0206 0312324346"), - ('o', "123243453616050312"), - ('p', "0208 0312324345361605"), - ('q', "4248 4332120305163645"), - ('r', "0206 04223243"), - ('s', "43321203143445361605"), - ('t', "10152636 0232"), - ('u', "0205163645 4246"), - ('v', "022642"), - ('w', "0216243642"), - ('x', "0246 4206"), - ('y', "0226 4218"), - ('z', "02420646"), - ('0', "103041453616050110 3115"), - ('1', "112026 1636"), - ('2', "01103041420646"), - ('3', "01103041423313 334445361605"), - ('4', "36300444"), - ('5', "400003334445361605"), - ('6', "30100105163645443303"), - ('7', "004016"), - ('8', "13020110304142331304051636454433"), - ('9', "43130201103041453616"), - ('.', "26"), - (',', "2617"), - ('!', "2024 26"), - ('?', "0110304142332324 26"), - (':', "22 26"), - (';', "22 2617"), - ('-', "1333"), - ('+', "1333 2224"), - ('=', "1232 1434"), - ('*', "1135 3115 0333"), - ('/', "4006"), - ('\\', "0046"), - ('(', "30212536"), - (')', "10212516"), - ('[', "30202636"), - (']', "10202616"), - ('<', "410345"), - ('>', "014305"), - ('\'', "2021"), - ('"', "1011 3031"), - ('_', "0747"), - ('#', "1115 3135 0242 0444"), - ('%', "4006 01 45"), - (' ', ""), -]; - -/// A character's strokes; unknown characters show as `?`. -fn glyph(c: char) -> &'static str { - let find = |c: char| GLYPHS.iter().find(|(g, _)| *g == c).map(|(_, s)| *s); - find(c).or_else(|| find('?')).unwrap_or("") -} - -/// The strokes of `s` as polylines in grid units. -fn strokes(s: &str) -> impl Iterator<Item = Vec<[f32; 2]>> + '_ { - s.split(' ') - .filter(|t| !t.is_empty()) - .map(|t| t.as_bytes().chunks_exact(2).map(|p| [p[0].saturating_sub(b'0') as f32, p[1].saturating_sub(b'0') as f32]).collect()) -} - -/// Longest text drawn (an allocation cap). -const MAX_CHARS: usize = 10_000; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("text", "Text", ATOMIC) - .desc("Draws text with a built-in single-stroke font (A–Z, a–z, 0–9, punctuation). \\n starts a new line.") - .atomic() - .generator() - .text("text", "Text", "MaterialCraft") - .float("size", "Size", 0.09, 0.0, 1.0) - .float2("position", "Position", [0.5, 0.5], 0.0, 1.0) - .choice("alignment", "Alignment", &["Left", "Center", "Right"], 1) - .color("color", "Color", [1.0, 1.0, 1.0, 1.0]) - .float("weight", "Stroke weight", 0.7, 0.05, 3.0) - .float("letter_spacing", "Letter spacing", 1.0, 0.0, 5.0) - .float("line_spacing", "Line spacing", 1.0, 0.0, 5.0) - .angle("rotation", "Rotation", 0.0) - .boolean("tiling", "Tiling (wrap at edges)", true) - .color_out() - .cook(text), - ] -} - -/// The capsule segments of `txt` in pixel space. -fn layout(ctx: &Ctx, txt: &str) -> Vec<Seg> { - let unit = ctx.f("size").max(0.0) * ctx.h as f32 / 8.0; - let (adv, line_h) = (4.0 + 2.0 * ctx.f("letter_spacing"), 10.0 * ctx.f("line_spacing")); - let (align, pos) = (ctx.i("alignment"), ctx.v2("position")); - let (s, c) = (ctx.f("rotation") * TAU).sin_cos(); - let anchor = [pos[0] * ctx.w as f32, pos[1] * ctx.h as f32]; - let lines: Vec<&str> = txt.split('\n').collect(); - // The block is centered vertically on the anchor (cap height of the first line to baseline of the last). - let top = -((lines.len().max(1) - 1) as f32 * line_h + 6.0) * 0.5; - let mut segs = Vec::new(); - for (li, line) in lines.iter().enumerate() { - let n = line.chars().count() as f32; - let width = if n > 0.0 { (n - 1.0) * adv + 4.0 } else { 0.0 }; - let x0 = match align { - 0 => 0.0, - 1 => -width * 0.5, - _ => -width, - }; - let y0 = top + li as f32 * line_h; - for (ci, ch) in line.chars().enumerate() { - let gx = x0 + ci as f32 * adv; - for stroke in strokes(glyph(ch)) { - let px: Vec<[f32; 2]> = stroke - .iter() - .map(|p| { - let (x, y) = ((gx + p[0]) * unit, (y0 + p[1]) * unit); - [anchor[0] + x * c + y * s, anchor[1] - x * s + y * c] - }) - .collect(); - match px.as_slice() { - [a] => segs.push(Seg { a: *a, b: *a, wt: 1.0 }), - _ => segs.extend(px.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 })), - } - } - } - } - segs -} - -fn text(ctx: &Ctx) -> CookResult { - let txt: String = ctx.text("text").replace("\\n", "\n").chars().take(MAX_CHARS).collect(); - let r = ctx.f("weight").max(0.0) * ctx.f("size").max(0.0) * ctx.h as f32 / 16.0; - let caps = Capsules::new(layout(ctx, &txt), r, ctx.w, ctx.h, ctx.b("tiling")); - Ok(vec![composite(ctx.w, ctx.h, ctx.v4("color"), |x, y| caps.coverage(x as f32 + 0.5, y as f32 + 0.5), [0.0; 4], |_, _| 0.0)]) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - - use super::*; - use crate::catalog::{find, resolve_params}; - - #[test] - fn font_data_is_well_formed() { - for (c, s) in GLYPHS { - for t in s.split(' ').filter(|t| !t.is_empty()) { - assert!(t.len() % 2 == 0 && t.bytes().all(|b| b.is_ascii_digit()), "{c:?}: {t}"); - assert!(t.as_bytes().chunks(2).all(|p| p[0] <= b'4' && p[1] <= b'8'), "{c:?}: {t} leaves the grid"); - } - } - for c in ('A'..='Z').chain('a'..='z').chain('0'..='9') { - assert!(GLYPHS.iter().any(|(g, _)| *g == c), "{c} missing"); - } - } - - #[test] - fn renders_material_craft() { - let def = find("text").unwrap(); - let p = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let ctx = Ctx { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars }; - let img = &text(&ctx).unwrap()[0]; - let lit = img.data.chunks(4).filter(|p| p[3] > 0.5).count(); - assert!(lit > 300, "{lit} pixels"); - // Centered: nothing in the top and bottom quarters. - assert!((0..256).all(|x| img.get(x, 20, false)[3] == 0.0 && img.get(x, 236, false)[3] == 0.0)); - } -} diff --git a/_to_delete/nodes_weathering.rs b/_to_delete/nodes_weathering.rs deleted file mode 100644 index 6692543..0000000 --- a/_to_delete/nodes_weathering.rs +++ /dev/null @@ -1,300 +0,0 @@ -//! Wear and weathering: cracks, paint strokes, scratches along a direction field, rust, moss and -//! lichen, leaks (drips running down from a mask) and chipped edges. The generators tile. - -use std::f32::consts::{PI, TAU}; - -use materialcraft_image::{Image, Kind}; -use rayon::prelude::*; - -use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; -use crate::fx_map::{BLENDS, Inst, splat}; -use crate::generators::NOISES; -use crate::noise::{cellular, fbm, rand1, value, value_xy}; -use crate::noises_more::smoothstep; -use crate::ops; -use crate::patterns::PATTERNS; -use crate::svg::{Capsules, Seg}; - -const WEATHER: &str = "Material filters/Weathering"; - -pub(crate) fn defs() -> Vec<NodeDef> { - vec![ - node("cracks", "Cracks", NOISES) - .desc("A connected network of thin cracks along warped cell borders, with finer branching cracks. White = crack.") - .generator() - .float("scale", "Scale", 5.0, 1.0, 32.0) - .float("width", "Width", 1.5, 0.0, 16.0) - .float("warp", "Warp", 0.5, 0.0, 1.0) - .float("branches", "Branches", 0.5, 0.0, 1.0) - .gray_out() - .cook(cracks), - node("paint_strokes", "Paint Strokes", PATTERNS) - .desc("Overlapping brush strokes with bristle streaks and ragged ends.") - .generator() - .int("count", "Count", 150, 1, 5000) - .float("length", "Length", 0.35, 0.0, 1.0) - .float("width", "Width", 0.07, 0.0, 0.5) - .angle("angle", "Angle", 0.0) - .float("angle_random", "Angle random", 0.08, 0.0, 1.0) - .int("bristles", "Bristles", 20, 1, 256) - .float("luminance_random", "Luminance random", 0.5, 0.0, 1.0) - .choice("blending", "Blending", BLENDS, 2) - .gray_out() - .cook(paint_strokes), - node("scratches_generator", "Scratches Generator", PATTERNS) - .desc("Thin tapered scratches that bend along a direction field (gray = angle in turns) and land where the mask is bright.") - .generator() - .gray_in("direction", "Direction field") - .gray_in("mask", "Mask") - .int("count", "Count", 200, 0, 5000) - .float("length", "Length", 0.25, 0.0, 1.0) - .float("width", "Width", 1.0, 0.1, 16.0) - .angle("angle", "Angle", 0.0) - .float("angle_random", "Angle random", 0.15, 0.0, 1.0) - .float("curvature", "Curvature", 0.1, 0.0, 1.0) - .float("field_intensity", "Field intensity", 0.25, 0.0, 1.0) - .float("luminance_random", "Luminance random", 0.6, 0.0, 1.0) - .gray_out() - .cook(scratches_generator), - node("rust", "Rust", WEATHER) - .desc("A mask of rust blotches and pitting; with a mask input it grows out from the mask (edges, cavities).") - .generator() - .gray_in("mask", "Mask (optional)") - .float("amount", "Amount", 0.45, 0.0, 1.0) - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("spread", "Spread", 12.0, 0.0, 128.0) - .float("pitting", "Pitting", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.7, 0.0, 1.0) - .gray_out() - .cook(rust), - node("moss", "Moss / Lichen", WEATHER) - .desc("Fuzzy moss clumps (gathering in low areas) or round lichen rosettes (on high areas) of an optional height map.") - .generator() - .gray_in("height", "Height (optional)") - .choice("style", "Style", &["Moss", "Lichen"], 0) - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("scale", "Scale", 6.0, 1.0, 64.0) - .float("height_bias", "Height bias", 0.5, 0.0, 1.0) - .float("contrast", "Contrast", 0.6, 0.0, 1.0) - .gray_out() - .cook(moss), - node("leaks", "Leaks", WEATHER) - .desc("Streaky drips running down from a mask (unconnected: random stains), fading with length and meandering.") - .gray_in("mask", "Mask") - .float("length", "Length", 0.35, 0.0, 1.0) - .float("length_random", "Length random", 0.7, 0.0, 1.0) - .float("streaks", "Streaks", 32.0, 1.0, 256.0) - .float("wobble", "Wobble", 0.3, 0.0, 1.0) - .gray_out() - .cook(leaks), - node("edge_damage", "Edge Damage", WEATHER) - .desc("Chips the edges of a height mask (white = material) in chunky, ragged bites; also outputs the damage mask.") - .gray_in("height", "Height") - .float("width", "Width", 8.0, 0.0, 64.0) - .float("amount", "Amount", 0.5, 0.0, 1.0) - .float("scale", "Chip scale", 12.0, 1.0, 64.0) - .float("roughness", "Roughness", 0.5, 0.0, 1.0) - .float("depth", "Depth", 1.0, 0.0, 1.0) - .gray_out() - .output("mask", "Damage mask", PortKind::Gray) - .cook(edge_damage), - ] -} - -/// `v` pixels at 256 px, at the output size. -fn px(ctx: &Ctx, v: f32) -> f32 { - v * ctx.w as f32 / 256.0 -} - -fn whole(ctx: &Ctx, id: &str) -> f32 { - ctx.f(id).max(1.0).round() -} - -/// A soft threshold: 1 where `v` is above `1 - amount`; `contrast` 1 is hard, 0 soft. -fn thresh(v: f32, amount: f32, contrast: f32) -> f32 { - let soft = (1.0 - contrast.clamp(0.0, 1.0)) * 0.25 + 0.005; - smoothstep(1.0 - amount - soft, 1.0 - amount + soft, v) -} - -/// A gray image from `f(pixel index, u, v)`. -fn gen_px(ctx: &Ctx, f: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image { - let (w, h) = (ctx.w.max(1), ctx.h.max(1)); - Image::generate(w, h, Kind::Gray, |x, y| [f(y as usize * w as usize + x as usize, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32), 0.0, 0.0, 0.0]) -} - -fn cracks(ctx: &Ctx) -> CookResult { - let (s, wpx, warp, br, seed) = (whole(ctx, "scale"), px(ctx, ctx.f("width")), ctx.f("warp"), ctx.f("branches"), ctx.seed); - let cell_px = ctx.w as f32 / s; - Ok(vec![ctx.gen_gray(|u, v| { - // Broad bends plus fine jaggedness, both in cell units. - let k = warp / s; - let wu = u + (fbm(u, v, 4.0, 4, 0.5, seed ^ 11) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 14) - 0.5) * 0.3 * k; - let wv = v + (fbm(u, v, 4.0, 4, 0.5, seed ^ 12) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 15) - 0.5) * 0.3 * k; - let line = |m: f32, sd: u32, half: f32| { - let c = cellular(wu * s * m, wv * s * m, (s * m) as i32, 1.0, 0, sd); - 1.0 - smoothstep(half, half + 1.0, (c.f2 - c.f1) * 0.5 * cell_px / m) - }; - let main = line(1.0, seed, wpx * 0.5); - if br <= 0.0 { - return main; - } - let keep = smoothstep(1.0 - br, 1.0 - br + 0.2, fbm(u, v, s, 3, 0.5, seed ^ 13)); - main.max(line(3.0, seed ^ 7, wpx * 0.3) * keep * 0.8) - })]) -} - -fn paint_strokes(ctx: &Ctx) -> CookResult { - let (len, wid, ang, ar, lr, s) = (ctx.f("length"), ctx.f("width"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("luminance_random"), ctx.seed); - let bristles = ctx.i("bristles").clamp(1, 256) as f32; - let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 5000) as u32) - .map(|i| { - let r = |k: u32| rand1(i * 8 + k, s); - Inst { - c: [r(0), r(1)], - r: [len * 0.5 * (0.7 + 0.3 * r(2)), wid * 0.5 * (0.8 + 0.4 * r(3))], - rot: ang + (r(4) - 0.5) * ar, - lum: 1.0 - lr * r(5), - pat: 0, - } - }) - .collect(); - Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| { - let sd = s ^ (i as u32).wrapping_mul(0x9e37_79b9); - // Bristle density across the stroke; the ends are ragged per bristle. - let b = value(y * bristles + 0.5, 0.5, 0, sd); - let ragged = value(y * bristles * 0.5 + 3.1, x * 2.0, 0, sd ^ 1); - let end = 1.0 - smoothstep(0.55 + 0.4 * ragged, 1.0, x.abs()); - let edge = 1.0 - smoothstep(0.7, 1.0, y.abs()); - end * edge * (0.45 + 0.55 * b) - })]) -} - -fn scratches_generator(ctx: &Ctx) -> CookResult { - const STEPS: u32 = 12; - let (len, ang, ar, curv, fi, lr, s) = - (ctx.f("length"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("curvature"), ctx.f("field_intensity"), ctx.f("luminance_random"), ctx.seed); - let (field, mask) = (ctx.input(0), ctx.input(1)); - let (w, h) = (ctx.w as f32, ctx.h as f32); - let mut segs = Vec::new(); - for i in 0..ctx.i("count").clamp(0, 5000) as u32 { - let r = |k: u32| rand1(i * 8 + k, s); - let mut p = [r(0), r(1)]; - if mask.is_some_and(|m| r(2) >= m.sample_gray(p[0], p[1], ctx.tile)) { - continue; - } - let (base, bend, lum) = (ang + (r(3) - 0.5) * ar, (r(4) - 0.5) * curv, 1.0 - lr * r(6)); - let step = len * (0.4 + 0.6 * r(5)) / STEPS as f32; - for k in 0..STEPS { - let t = k as f32 / STEPS as f32; - let a = (base + bend * t + field.map_or(0.0, |f| f.sample_gray(p[0], p[1], ctx.tile) * fi)) * TAU; - let q = [p[0] + a.cos() * step, p[1] - a.sin() * step]; - let taper = ((t + 0.5 / STEPS as f32) * PI).sin().sqrt(); - segs.push(Seg { a: [p[0] * w, p[1] * h], b: [q[0] * w, q[1] * h], wt: lum * taper }); - p = q; - } - } - let caps = Capsules::new(segs, px(ctx, ctx.f("width")) * 0.5, ctx.w, ctx.h, ctx.tile); - Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| [caps.coverage(x as f32 + 0.5, y as f32 + 0.5), 0.0, 0.0, 0.0])]) -} - -fn rust(ctx: &Ctx) -> CookResult { - let (amt, s, pit, con, seed) = (ctx.f("amount"), whole(ctx, "scale"), ctx.f("pitting"), ctx.f("contrast"), ctx.seed); - let grow = ctx.sized(0).map(|m| ops::gaussian(&m.to_gray(), px(ctx, ctx.f("spread")), ctx.tile)); - Ok(vec![gen_px(ctx, |i, u, v| { - let blotch = fbm(u, v, s, 6, 0.55, seed); - let base = match &grow { - Some(g) => 0.5 * blotch + 0.6 * g.data.get(i).copied().unwrap_or(0.0), - None => blotch, - }; - let c = cellular(u * s * 8.0, v * s * 8.0, (s * 8.0) as i32, 1.0, 0, seed ^ 3); - let pits = (1.0 - smoothstep(0.05, 0.4, c.f1)) * (c.id < pit) as i32 as f32; - // Pits speckle the surroundings of the blotches only. - thresh(base + pits * 0.2 * smoothstep(0.3, 0.5, base), amt, con) * (0.7 + 0.3 * fbm(u, v, s * 16.0, 3, 0.6, seed ^ 5)) - })]) -} - -fn moss(ctx: &Ctx) -> CookResult { - let (lichen, amt, s, bias, con, seed) = (ctx.i("style") == 1, ctx.f("amount"), whole(ctx, "scale"), ctx.f("height_bias"), ctx.f("contrast"), ctx.seed); - let hgt = ctx.sized(0).map(|h| h.to_gray()); - Ok(vec![gen_px(ctx, |i, u, v| { - let hb = hgt.as_ref().map_or(0.0, |h| (h.data.get(i).copied().unwrap_or(0.5) - 0.5) * bias); - let fine = |m: f32, sd: u32| value(u * s * m, v * s * m, (s * m) as i32, seed ^ sd); - if !lichen { - // Fuzzy clumps, thicker in low areas. - let clump = fbm(u, v, s, 5, 0.6, seed) - hb + (fine(24.0, 9) - 0.5) * 0.25; - return thresh(clump, amt, con) * (0.55 + 0.45 * fine(48.0, 10)); - } - // Round rosettes with brighter rims, on high areas. - let c = cellular(u * s, v * s, s as i32, 0.9, 0, seed); - if c.id >= amt * 1.4 + hb { - return 0.0; - } - let rad = (0.25 + 0.35 * (c.id * 7.31).fract()) * (0.8 + 0.4 * fbm(u, v, s * 8.0, 3, 0.5, seed ^ 4)); - let soft = 0.01 + (1.0 - con) * 0.06; - (1.0 - smoothstep(rad - soft, rad, c.f1)) * (0.55 + 0.45 * smoothstep(rad * 0.4, rad, c.f1)) * (0.8 + 0.2 * fine(32.0, 6)) - })]) -} - -fn leaks(ctx: &Ctx) -> CookResult { - let (w, h, seed) = (ctx.w as usize, ctx.h as usize, ctx.seed); - let src = match ctx.sized(0) { - Some(m) => m.to_gray(), - None => ctx.gen_gray(|u, v| smoothstep(0.62, 0.7, fbm(u, v, 4.0, 4, 0.5, seed ^ 21))), - }; - let (len, lr, streaks, wob) = (ctx.f("length").max(0.0) * h as f32, ctx.f("length_random"), whole(ctx, "streaks"), ctx.f("wobble")); - // Each column carries its value down, fading over a length that varies across columns. - let cols: Vec<Vec<f32>> = (0..w) - .into_par_iter() - .map(|x| { - let u = (x as f32 + 0.5) / w as f32; - let r = 0.6 * value(u * streaks, 0.5, streaks as i32, seed ^ 23) + 0.4 * value(u * streaks * 4.0, 0.5, (streaks * 4.0) as i32, seed ^ 24); - let decay = (-3.0 / (len * (1.0 - lr * r)).max(1.0)).exp(); - let mut col = vec![0.0f32; h]; - let mut acc = 0.0f32; - // Tiling: a second pass carries drips over the bottom edge to the top. - let passes = if ctx.tile { 2 } else { 1 }; - for pass in 0..passes { - for (y, out) in col.iter_mut().enumerate() { - acc = src.data.get(y * w + x).copied().unwrap_or(0.0).max(acc * decay); - if pass + 1 == passes { - *out = acc; - } - } - } - col - }) - .collect(); - let run = Image::gray(ctx.w, ctx.h, |x, y| cols.get(x as usize).and_then(|c| c.get(y as usize)).copied().unwrap_or(0.0)); - Ok(vec![ctx.gen_gray(|u, v| { - let dx = (fbm(u, v, 8.0, 3, 0.5, seed ^ 22) - 0.5) * wob * 0.04; - run.sample_gray(u + dx, v, ctx.tile) * (0.75 + 0.25 * value_xy(u * streaks * 2.0, v * 3.0, (streaks * 2.0) as i32, 3, seed ^ 25)) - })]) -} - -fn edge_damage(ctx: &Ctx) -> CookResult { - let hgt = ctx.gray_or(0, 0.0); - let data = hgt.data.clone(); - let solid = |i: usize| data.get(i).is_some_and(|v| *v > 0.5); - let dist = ops::distance_sq(ctx.w, ctx.h, |i| !solid(i), ctx.tile); - let (wpx, amt, s, rough, depth, seed) = (px(ctx, ctx.f("width")), ctx.f("amount"), whole(ctx, "scale"), ctx.f("roughness"), ctx.f("depth"), ctx.seed); - let mask = gen_px(ctx, |i, u, v| { - if !solid(i) { - return 0.0; - } - let d = dist.get(i).map_or(0.0, |d| d.sqrt()); - // Chunky bites per cell, made ragged by noise. - let c = cellular(u * s, v * s, s as i32, 1.0, 0, seed); - let r = c.id * (1.0 - rough * 0.5) + (fbm(u, v, s * 2.0, 4, 0.5, seed ^ 3) - 0.5) * rough * 1.5; - let reach = wpx * 2.0 * amt * r.max(0.0); - 1.0 - smoothstep(reach - 0.75, reach + 0.75, d) - }); - let out = Image::gray(ctx.w, ctx.h, |x, y| { - let i = (y * ctx.w + x) as usize; - data.get(i).copied().unwrap_or(0.0) * (1.0 - depth * mask.data.get(i).copied().unwrap_or(0.0)) - }); - Ok(vec![out, mask]) -} - -#[cfg(test)] -#[path = "weathering.test.rs"] -mod tests; diff --git a/_to_delete/nodes_weathering.test.rs b/_to_delete/nodes_weathering.test.rs deleted file mode 100644 index 7381c1e..0000000 --- a/_to_delete/nodes_weathering.test.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! Tiling tests for the weathering nodes. - -use std::collections::BTreeMap; - -use crate::{Ctx, find, resolve_params}; - -/// Mean absolute difference across the wrap versus across every interior neighbour pair, per axis. -fn wrap_vs_interior(id: &str) -> [(f32, f32); 2] { - let def = find(id).unwrap(); - let params = resolve_params(def, &BTreeMap::new()); - let no_res = |_: &str| None; - let vars = BTreeMap::new(); - let inputs = vec![Some(materialcraft_image::Image::filled(64, 64, materialcraft_image::Kind::Gray, [1.0; 4])); def.inputs.len()]; - let ctx = Ctx { w: 64, h: 64, seed: 9, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; - let img = (def.cook)(&ctx).unwrap().remove(0); - let g = |x: i64, y: i64| img.get(x, y, false)[0]; - let (mut hw, mut hi, mut vw, mut vi) = (0.0f32, 0.0f32, 0.0f32, 0.0f32); - for k in 0..64 { - hw += (g(63, k) - g(0, k)).abs(); - vw += (g(k, 63) - g(k, 0)).abs(); - for j in 0..63 { - hi += (g(j, k) - g(j + 1, k)).abs() / 63.0; - vi += (g(k, j) - g(k, j + 1)).abs() / 63.0; - } - } - [(hw, hi), (vw, vi)] -} - -#[test] -fn leaks_tile_in_both_directions() { - for (axis, (wrap, interior)) in wrap_vs_interior("leaks").into_iter().enumerate() { - assert!(wrap <= interior * 3.0 + 0.5, "axis {axis}: wrap {wrap} vs interior {interior}"); - } -} diff --git a/_to_delete/ui-parity-main-port.zip b/_to_delete/ui-parity-main-port.zip deleted file mode 100644 index 3ff3f8e..0000000 Binary files a/_to_delete/ui-parity-main-port.zip and /dev/null differ diff --git a/_to_delete/ui_function_editor.rs b/_to_delete/ui_function_editor.rs deleted file mode 100644 index 9fa6b96..0000000 --- a/_to_delete/ui_function_editor.rs +++ /dev/null @@ -1,459 +0,0 @@ -//! The function graph editor: a window with a small node canvas for a pixel or value -//! processor's function. Right-click (or Space) adds operations by category, dragging from an -//! output to an input wires them, the starred node is the result. Each change commits the whole -//! function through `graph.node.param`. - -use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::NodeId; -use materialcraft_engine::core::Value; -use materialcraft_engine::core::function::{FnGraph, FnNode}; -use materialcraft_engine::nodes::function::FN_OPS; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -const W: f32 = 130.0; -const HEADER: f32 = 18.0; -const ROW: f32 = 18.0; - -/// The open editor: which node's parameter, and the canvas camera. -pub struct FnEditor { - pub node: NodeId, - pub param: String, - pan: Vec2, - zoom: f32, - drag: Option<FnDrag>, - menu_at: Pos2, - /// The camera has been fitted to the nodes. - framed: bool, -} - -enum FnDrag { - Node(u32, Vec2), - Wire(u32), - Pan, -} - -impl FnEditor { - pub fn new(node: NodeId, param: &str) -> FnEditor { - FnEditor { node, param: param.into(), pan: vec2(-40.0, -40.0), zoom: 1.0, drag: None, menu_at: Pos2::ZERO, framed: false } - } -} - -fn arity(op: &str) -> usize { - FN_OPS.iter().find(|o| o.0 == op).map_or(0, |o| o.2) -} - -fn label(op: &str) -> &'static str { - FN_OPS.iter().find(|o| o.0 == op).map_or("?", |o| o.1) -} - -fn category_color(op: &str) -> Color32 { - match FN_OPS.iter().find(|o| o.0 == op).map_or("", |o| o.3) { - "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), - "Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34), - "Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0), - "Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c), - "Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ => Color32::from_rgb(0x1e, 0x8a, 0xa0), - } -} - -/// The value a new node of `op` starts with. -fn default_value(op: &str) -> Option<Value> { - Some(match op { - "const_float" => Value::Float(0.5), - "const_float2" => Value::Float2([0.5, 0.5]), - "const_float3" => Value::Float3([0.5, 0.5, 0.5]), - "const_float4" => Value::Float4([0.5, 0.5, 0.5, 1.0]), - "const_int" => Value::Int(1), - "const_bool" => Value::Bool(true), - "get_var" => Value::Text(String::new()), - "sample_gray" | "sample_color" => Value::Int(0), - "swizzle" => Value::Text("x".into()), - _ => return None, - }) -} - -fn node_rect(n: &FnNode) -> Rect { - let rows = arity(&n.op).max(1) as f32 + if n.value.is_some() { 1.0 } else { 0.0 }; - Rect::from_min_size(pos2(n.pos[0], n.pos[1]), vec2(W, HEADER + rows * ROW + 6.0)) -} - -fn in_port(r: Rect, i: usize) -> Pos2 { - pos2(r.left(), r.top() + HEADER + ROW * (i as f32 + 0.5)) -} - -fn out_port(r: Rect) -> Pos2 { - pos2(r.right(), r.top() + HEADER + ROW * 0.5) -} - -/// The function currently stored on the node: a function parameter, or (`fn:<param>`) the -/// function driving a dynamic parameter. -fn current(app: &MaterialCraftApp, e: &FnEditor) -> Option<FnGraph> { - let n = app.session.graph().ok()?.node(e.node).ok()?; - if let Some(p) = e.param.strip_prefix("fn:") { - return n.functions.get(p).cloned(); - } - match n.params.get(&e.param) { - Some(Value::Function(f)) => Some((**f).clone()), - _ => materialcraft_engine::nodes::find(&n.def)?.param(&e.param).and_then(|p| match &p.default { - Value::Function(f) => Some((**f).clone()), - _ => None, - }), - } -} - -fn commit(app: &mut MaterialCraftApp, node: NodeId, param: &str, g: &FnGraph) { - if let Some(p) = param.strip_prefix("fn:") { - app.run("graph.node.function", json!({"id": node.0, "param": p, "function": g})); - return; - } - let v = serde_json::to_value(Value::Function(Box::new(g.clone()))).unwrap_or(serde_json::Value::Null); - app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v})); -} - -/// Add a function node of `op` to the open function editor (the library's Function nodes). -/// Returns false when no function graph is open. -pub fn add_op(app: &mut MaterialCraftApp, op: &str) -> bool { - let Some(e) = app.fn_editor.as_ref() else { return false }; - let (node, param) = (e.node, e.param.clone()); - let Some(mut g) = current(app, e) else { return false }; - if !FN_OPS.iter().any(|o| o.0 == op) || g.nodes.len() >= 10_000 { - return false; - } - let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1); - // Below the lowest node, so new nodes never stack on one another. - let bottom = g.nodes.iter().map(|n| n.pos[1]).fold(-ROW * 4.0, f32::max) + ROW * 4.0; - let left = g.nodes.iter().map(|n| n.pos[0]).fold(0.0, f32::min); - g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [left, bottom] }); - if g.output.is_none() { - g.output = Some(id); - } - commit(app, node, ¶m, &g); - true -} - -/// Draw the editor window when one is open. -pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let Some(mut e) = app.fn_editor.take() else { return }; - let Some(mut g) = current(app, &e) else { return }; - let title = app.session.graph().ok().and_then(|gr| gr.node(e.node).ok()).map(crate::graph_view::node_label).unwrap_or_default(); - let mut open = true; - let mut changed = false; - let what = e.param.strip_prefix("fn:").map_or_else(|| tr("Function graph").to_string(), |p| format!("{} {p}", tr("Function of"))); - egui::Window::new(format!("{title} - {what}")) - .id(egui::Id::unique(("fn-editor", e.node.0, e.param.as_str()))) - .open(&mut open) - .default_size(vec2(760.0, 460.0)) - .resizable(true) - .show(ctx, |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label( - egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.")) - .size(11.0) - .color(tk.text_dim), - ); - }); - changed = canvas(&mut e, &mut g, ui); - }); - if changed { - commit(app, e.node, &e.param, &g); - } - if open { - app.fn_editor = Some(e); - } -} - -fn canvas(e: &mut FnEditor, g: &mut FnGraph, ui: &mut Ui) -> bool { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Function graph"); - let p = ui.painter_at(rect); - p.rect_filled(rect, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c)); - if !e.framed { - e.framed = true; - let b = g.nodes.iter().map(node_rect).fold(Rect::NOTHING, |a, r| a.union(r)); - if b.is_finite() && b.width() > 0.0 { - let b = b.expand(30.0); - e.zoom = (rect.width() / b.width()).min(rect.height() / b.height()).clamp(0.3, 1.2); - e.pan = b.center().to_vec2() - rect.size() * 0.5 / e.zoom; - } - } - let to_s = |q: Pos2, e: &FnEditor| rect.min + (q.to_vec2() - e.pan) * e.zoom; - let to_g = |s: Pos2, e: &FnEditor| ((s - rect.min) / e.zoom + e.pan).to_pos2(); - let mut changed = false; - let pointer = ui.input(|i| i.pointer.hover_pos()); - - // Zoom and pan. - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); - if scroll.abs() > 0.0 - && let Some(ptr) = pointer - { - let before = to_g(ptr, e); - e.zoom = (e.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5); - e.pan = before.to_vec2() - (ptr - rect.min) / e.zoom; - } - } - - // Wires. - for n in &g.nodes { - let r = node_rect(n); - for (i, src) in n.inputs.iter().enumerate() { - if let Some(s) = src.and_then(|s| g.node(s)) { - let a = to_s(out_port(node_rect(s)), e); - let b = to_s(in_port(r, i), e); - let dx = ((b.x - a.x).abs() * 0.5).max(24.0); - p.add(egui::epaint::CubicBezierShape::from_points_stroke( - [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b], - false, - Color32::TRANSPARENT, - Stroke::new(2.0, Color32::from_gray(0xb4)), - )); - } - } - } - - // Nodes. - let font = FontId::proportional((11.0 * e.zoom).clamp(7.0, 16.0)); - let mut remove: Option<u32> = None; - let mut set_output: Option<u32> = None; - let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new(); - let ids: Vec<u32> = g.nodes.iter().map(|n| n.id).collect(); - for id in ids { - let Some(idx) = g.nodes.iter().position(|n| n.id == id) else { continue }; - let mut r = node_rect(&g.nodes[idx]); - if let Some(FnDrag::Node(d, delta)) = &e.drag - && *d == id - { - r = r.translate(*delta); - } - let sr = Rect::from_min_max(to_s(r.min, e), to_s(r.max, e)); - let n = &g.nodes[idx]; - let is_out = g.output == Some(id); - p.rect_filled(sr, 5.0, Color32::from_rgb(0x1e, 0x20, 0x24)); - let header = Rect::from_min_size(sr.min, vec2(sr.width(), HEADER * e.zoom)); - p.rect_filled(header, egui::CornerRadius { nw: 5, ne: 5, sw: 0, se: 0 }, category_color(&n.op)); - let star = if is_out { format!("{} ", icon::STAR) } else { String::new() }; - p.text(header.left_center() + vec2(5.0, 0.0), Align2::LEFT_CENTER, format!("{star}{}", label(&n.op)), font.clone(), Color32::WHITE); - p.rect_stroke(sr, 5.0, Stroke::new(if is_out { 2.0 } else { 1.0 }, if is_out { tk.accent } else { Color32::from_gray(0x10) }), StrokeKind::Outside); - for i in 0..arity(&n.op) { - let pos = to_s(in_port(r, i), e); - p.circle(pos, 4.5, Color32::from_gray(0xc8), Stroke::new(1.0, Color32::from_gray(0x18))); - ports.push((id, Some(i), pos)); - } - let op = to_s(out_port(r), e); - p.circle(op, 4.5, Color32::from_rgb(0xe8, 0xa9, 0x3c), Stroke::new(1.0, Color32::from_gray(0x18))); - ports.push((id, None, op)); - // Inline value editor. - if n.value.is_some() { - let row = Rect::from_min_size( - to_s(pos2(r.left() + 6.0, r.top() + HEADER + arity(&n.op).max(1) as f32 * ROW + 2.0), e), - vec2((W - 12.0) * e.zoom, (ROW - 2.0) * e.zoom), - ); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(row)); - if let Some(v) = g.nodes[idx].value.as_mut() { - changed |= value_editor(&mut child, v); - } - } - let body = ui.interact(sr, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag()); - crate::widgets::name(&body, egui::Role::Button, label(&g.nodes[idx].op)); - if body.drag_started() && e.drag.is_none() { - e.drag = Some(FnDrag::Node(id, Vec2::ZERO)); - } - body.context_menu(|ui| { - if ui.button(format!("{} {}", icon::STAR, tr("Use as result"))).clicked() { - set_output = Some(id); - ui.close(); - } - if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() { - remove = Some(id); - ui.close(); - } - }); - } - if let Some(id) = set_output { - g.output = Some(id); - changed = true; - } - if let Some(id) = remove { - g.nodes.retain(|n| n.id != id); - for n in &mut g.nodes { - for i in &mut n.inputs { - if *i == Some(id) { - *i = None; - } - } - } - if g.output == Some(id) { - g.output = None; - } - changed = true; - } - - // Gestures: wires from output dots, panning. - let near = |ptr: Pos2| ports.iter().filter(|(_, _, q)| q.distance(ptr) < 9.0).min_by(|a, b| a.2.distance(ptr).total_cmp(&b.2.distance(ptr))).cloned(); - if resp.drag_started_by(egui::PointerButton::Middle) || (resp.drag_started() && ui.input(|i| i.modifiers.alt)) { - e.drag = Some(FnDrag::Pan); - } else if ui.input(|i| i.pointer.primary_pressed()) - && e.drag.is_none() - && let Some(ptr) = pointer - && rect.contains(ptr) - && let Some((id, None, _)) = near(ptr) - { - e.drag = Some(FnDrag::Wire(id)); - } - let delta = ui.input(|i| i.pointer.delta()); - match &mut e.drag { - Some(FnDrag::Node(_, d)) => *d += delta / e.zoom, - Some(FnDrag::Pan) => e.pan -= delta / e.zoom, - Some(FnDrag::Wire(id)) => { - if let (Some(ptr), Some(src)) = (pointer, ports.iter().find(|(n, s, _)| n == id && s.is_none())) { - p.line_segment([src.2, ptr], Stroke::new(2.0, tk.accent)); - } - } - None => {} - } - if ui.input(|i| i.pointer.any_released()) { - match e.drag.take() { - Some(FnDrag::Node(id, d)) => { - if let Some(n) = g.nodes.iter_mut().find(|n| n.id == id) - && d.length() > 0.5 - { - n.pos = [n.pos[0] + d.x, n.pos[1] + d.y]; - changed = true; - } - } - Some(FnDrag::Wire(src)) => { - if let Some(ptr) = pointer - && let Some((dst, Some(slot), _)) = near(ptr) - && dst != src - && !reaches(g, dst, src) - && let Some(n) = g.nodes.iter_mut().find(|n| n.id == dst) - { - if n.inputs.len() <= slot { - n.inputs.resize(slot + 1, None); - } - n.inputs[slot] = Some(src); - changed = true; - } - } - _ => {} - } - } - - // Adding operations. - if resp.secondary_clicked() - && let Some(ptr) = pointer - { - e.menu_at = to_g(ptr, e); - } - if resp.hovered() - && ui.input(|i| i.key_pressed(egui::Key::Space)) - && let Some(ptr) = pointer - { - e.menu_at = to_g(ptr, e); - egui::Popup::open_id(ui.ctx(), resp.id.with("menu")); - } - let at = e.menu_at; - let mut add: Option<&'static str> = None; - resp.context_menu(|ui| { - let mut cats: Vec<&str> = FN_OPS.iter().map(|o| o.3).collect(); - cats.dedup(); - for c in cats { - ui.menu_button(tr(c), |ui| { - for o in FN_OPS.iter().filter(|o| o.3 == c) { - if ui.button(tr(o.1)).clicked() { - add = Some(o.0); - ui.close(); - } - } - }); - } - }); - if let Some(op) = add { - let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1); - g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [at.x, at.y] }); - if g.output.is_none() { - g.output = Some(id); - } - changed = true; - } - changed -} - -/// Whether `a` feeds `b` (directly or through other nodes, or is `b`): then `b` may not feed `a`. -fn reaches(g: &FnGraph, a: u32, b: u32) -> bool { - let mut stack = vec![b]; - let mut seen = std::collections::BTreeSet::new(); - while let Some(n) = stack.pop() { - if n == a { - return true; - } - if !seen.insert(n) { - continue; - } - if let Some(node) = g.node(n) { - stack.extend(node.inputs.iter().flatten()); - } - } - false -} - -/// A compact editor for a function node's value. Returns true when it changed. -fn value_editor(ui: &mut Ui, v: &mut Value) -> bool { - let drag = |ui: &mut Ui, f: &mut f32| ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(3)).changed(); - ui.horizontal(|ui| match v { - Value::Float(f) => drag(ui, f), - Value::Float2(a) => { - let x = drag(ui, &mut a[0]); - drag(ui, &mut a[1]) || x - } - Value::Float3(a) => { - let mut c = false; - for f in a.iter_mut() { - c |= drag(ui, f); - } - c - } - Value::Float4(a) | Value::Color(a) => { - let mut c = false; - for f in a.iter_mut() { - c |= ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(2)).changed(); - } - c - } - Value::Int(i) => ui.add(egui::DragValue::new(i).speed(0.1)).changed(), - Value::Bool(b) => ui.checkbox(b, "").changed(), - Value::Text(t) => { - let r = ui.add(egui::TextEdit::singleline(t).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, "Value"); - r.changed() - } - _ => false, - }) - .inner -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cycles_are_detected() { - let mut g = FnGraph::default(); - let a = g.add("get_pos", &[], None); - let b = g.add("swizzle", &[a], Some(Value::Text("x".into()))); - // a feeds b: wiring b into a would loop. - assert!(reaches(&g, a, b)); - assert!(!reaches(&g, b, a)); - assert_eq!(arity("add"), 2); - assert!(default_value("const_float").is_some()); - } -} diff --git a/_to_delete/ui_graph_view.rs b/_to_delete/ui_graph_view.rs deleted file mode 100644 index aed761e..0000000 --- a/_to_delete/ui_graph_view.rs +++ /dev/null @@ -1,2092 +0,0 @@ -//! The graph editor: a pannable, zoomable canvas of node cards (colored header, live thumbnail, -//! size label), bezier wires between typed ports, frames, comments and navigation pins. -//! -//! Gestures: left-drag a node to move it (the selection moves together), drag from an output to wire -//! it (dropping on empty canvas opens the node search, wired), drag from an unconnected input to an -//! output to wire it the other way, drag a connected input to unplug and re-route it, drag the empty -//! canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to zoom. -//! Click a node to show it in the 2D view (double-click a graph instance to open its graph). -//! Space, Tab or double-click the canvas for the node search, right-click for menus, drop library -//! items to add them. Click a wire to select it (Shift or Ctrl+click adds more; Delete removes them, -//! X swaps where they come from), drag a wire to pull a reroute dot out of it, double-click a wire -//! to drop a dot there, right-click a wire for its menu. Every edit is an engine command; the -//! gestures only draw previews until they commit. - -use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::{Node, NodeId, Value}; -use materialcraft_engine::nodes::PortKind; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// Node card metrics in graph units. -pub const NODE_W: f32 = 100.0; -const HEADER_H: f32 = 18.0; -const FOOTER_H: f32 = 14.0; -const PORT_GAP: f32 = 18.0; -const PORT_R: f32 = 4.5; -const DOT_R: f32 = 7.0; - -/// A library item being dragged onto the canvas. -#[derive(Clone, Debug)] -pub struct LibraryDrag(pub String); - -#[derive(Clone, Debug)] -enum Drag { - Nodes { - delta: Vec2, - }, - Box { - start: Pos2, - }, - Wire { - from: (NodeId, String), - detached: Option<(NodeId, String)>, - }, - /// Pressed on a wire: a click selects it, a drag pulls a reroute dot out of it. - WirePress { - wire: WireRef, - start: Pos2, - }, - WireFromInput { - to: (NodeId, String), - }, - - Pan, - Frame { - id: u64, - delta: Vec2, - resize: bool, - nodes: Vec<NodeId>, - }, - Comment { - id: u64, - delta: Vec2, - }, -} - -/// A wire, named by the input it feeds: (node, input port). -pub type WireRef = (NodeId, String); - -/// Pointer distance (points) within which a wire is hit. -const WIRE_HIT: f32 = 5.0; - -/// The node search popup (Space or Tab). -#[derive(Clone, Debug)] -struct Search { - at: Pos2, - text: String, - sel: usize, - connect: Option<(NodeId, String)>, - focus: bool, -} - -/// One port as drawn this frame. -#[derive(Clone, Debug)] -pub struct PortHit { - pub node: NodeId, - pub output: bool, - pub port: String, - pub label: String, - pub pos: Pos2, - pub kind: PortKind, -} - -pub struct GraphView { - pub(crate) keyboard_was_focused: bool, - drag: Option<Drag>, - search: Option<Search>, - /// Comment being edited: id and text. - editing: Option<(u64, String)>, - /// Node rectangles on screen last frame (for `ui.inspect` and scripted input). - pub rects: Vec<(NodeId, Rect)>, - pub ports: Vec<PortHit>, - /// The canvas rectangle last frame. - pub view: Rect, - /// Graph point of the last right-click (context menu actions add things there). - menu_at: Pos2, - /// The graph the camera last framed. - framed_graph: Option<usize>, - /// The selected wires, in the order they were picked (Delete removes them, X swaps them). - pub selected_wires: Vec<WireRef>, - /// The wire the context menu is for (right-clicked on a wire). - menu_wire: Option<WireRef>, - /// Wires on screen last frame: the wire and its bezier control points. - pub wires: Vec<(WireRef, [Pos2; 4])>, -} - -impl Default for GraphView { - fn default() -> Self { - GraphView { - keyboard_was_focused: false, - drag: None, - search: None, - editing: None, - rects: Vec::new(), - ports: Vec::new(), - view: Rect::NOTHING, - menu_at: Pos2::ZERO, - framed_graph: None, - selected_wires: Vec::new(), - menu_wire: None, - wires: Vec::new(), - } - } -} - -struct Cam { - origin: Pos2, - pan: Vec2, - zoom: f32, -} - -impl Cam { - fn to_screen(&self, p: Pos2) -> Pos2 { - self.origin + (p.to_vec2() - self.pan) * self.zoom - } - fn to_graph(&self, s: Pos2) -> Pos2 { - ((s - self.origin) / self.zoom + self.pan).to_pos2() - } -} - -/// Header strip color of a node by its library category. -pub fn header_color(def: &str) -> Color32 { - let cat = materialcraft_engine::nodes::find(def).map_or("", |d| d.category); - match def { - "output" => Color32::from_rgb(0x2c, 0x8f, 0x5e), - "input_color" | "input_grayscale" => Color32::from_rgb(0x6d, 0x52, 0xb5), - "graph_instance" => Color32::from_rgb(0x1e, 0x8a, 0xa0), - _ if cat.starts_with("Atomic") => Color32::from_rgb(0x5c, 0x62, 0x6e), - _ if cat.contains("Noises") => Color32::from_rgb(0xa8, 0x3c, 0x34), - _ if cat.contains("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c), - _ if cat.starts_with("Material") => Color32::from_rgb(0x3a, 0x66, 0xb0), - _ if cat.starts_with("Filters") => Color32::from_rgb(0x3b, 0x7f, 0x4c), - _ => Color32::from_rgb(0x5c, 0x62, 0x6e), - } -} - -pub fn port_color(kind: PortKind) -> Color32 { - match kind { - PortKind::Gray => Color32::from_rgb(0xc8, 0xc8, 0xc8), - PortKind::Color => Color32::from_rgb(0xe8, 0xa9, 0x3c), - PortKind::Any => Color32::from_rgb(0x8c, 0xb4, 0xe0), - } -} - -/// A node's display label. -pub fn node_label(n: &Node) -> String { - if !n.label.is_empty() { - return n.label.clone(); - } - match n.def.as_str() { - "graph_instance" => match n.params.get("graph") { - Some(Value::Text(g)) => g.clone(), - _ => tr("Graph instance").into(), - }, - "output" | "input_color" | "input_grayscale" => materialcraft_engine::eval::identifier(n), - d => materialcraft_engine::nodes::find(d).map_or(d, |d| d.label).to_string(), - } -} - -/// Graph-space rectangle of a node card. -pub fn node_rect(n: &Node, n_in: usize, n_out: usize, thumbs: bool) -> Rect { - if n.def == "dot" { - return Rect::from_center_size(pos2(n.pos[0], n.pos[1]), vec2(DOT_R * 2.0, DOT_R * 2.0)); - } - let ports = n_in.max(n_out) as f32 * PORT_GAP + 8.0; - let body = if thumbs { NODE_W.max(ports) } else { ports.max(26.0) }; - Rect::from_min_size(pos2(n.pos[0], n.pos[1]), vec2(NODE_W, HEADER_H + body + FOOTER_H)) -} - -/// Graph-space port positions along a card side. -fn port_pos(r: Rect, i: usize, n: usize, output: bool, dot: bool) -> Pos2 { - if dot { - return pos2(if output { r.right() } else { r.left() }, r.center().y); - } - let top = r.top() + HEADER_H; - let body = r.height() - HEADER_H - FOOTER_H; - let start = top + (body - n as f32 * PORT_GAP) * 0.5 + PORT_GAP * 0.5; - pos2(if output { r.right() } else { r.left() }, start + i as f32 * PORT_GAP) -} - -/// Control points of the wire from output `a` to input `b` (screen space). -fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { - if STRAIGHT_WIRES.load(std::sync::atomic::Ordering::Relaxed) { - let d = (b - a) / 3.0; - return [a, a + d, a + d * 2.0, b]; - } - let dx = ((b.x - a.x).abs() * 0.5).max(30.0); - [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b] -} - -fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { - p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke)); -} - -/// The point at `t` (0..1) along a cubic bezier. -fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 { - let u = 1.0 - t; - let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t]; - pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum()) -} - -/// Distance from `p` to a cubic bezier (sampled as a polyline). -fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { - const N: usize = 32; - let mut best = f32::INFINITY; - let mut prev = c[0]; - for i in 1..=N { - let q = bezier_at(c, i as f32 / N as f32); - let (seg, rel) = (q - prev, p - prev); - let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; - best = best.min((prev + seg * t).distance(p)); - prev = q; - } - best -} - -/// The wire nearest `p` within [`WIRE_HIT`] points. -fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { - wires - .iter() - .filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p)) - .map(|(w, c)| (w, bezier_distance(c, p))) - .filter(|(_, d)| *d <= WIRE_HIT) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(w, _)| w) -} - -/// The graph panel: toolbar row and canvas. -pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - toolbar(app, ui); - canvas(app, ui); -} - -/// Wires are drawn straight this frame (set from the preference before the canvas draws). -static STRAIGHT_WIRES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// The grid step nodes snap to. -const SNAP: f32 = 16.0; - -fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 2)).show(ui, |ui| { - // Row 1: view and display tools. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - let b = |ui: &mut Ui, ic: &str, tip: &str, on: bool| crate::widgets::icon_button(ui, ic, tip, on, 22.0).clicked(); - if b(ui, icon::CORNERS_OUT, tr("Frame all (F)"), false) { - app.ui.frame_all = true; - } - if b(ui, icon::FRAME_CORNERS, tr("Actual size (1:1)"), (app.ui.graph_camera.zoom - 1.0).abs() < 1e-3) { - zoom_to(app, 1.0); - } - if b(ui, icon::CAMERA, tr("Save a screenshot of the graph..."), false) { - screenshot(app, ui.ctx()); - } - let info = crate::widgets::icon_button(ui, icon::INFO, tr("Graph information"), false, 22.0); - egui::Popup::menu(&info).show(|ui| graph_info(app, ui)); - if b(ui, icon::MAGNIFYING_GLASS, tr("Find a node (Tab)"), app.graph.search.is_some()) { - let c = view_center(app); - open_search(app, c, None); - } - ui.separator(); - let thumbs = app.ui.prefs.thumbnails; - if b(ui, icon::IMAGE, tr("Show node thumbnails"), thumbs) { - app.ui.prefs.thumbnails = !thumbs; - } - let timings = app.ui.prefs.node_timings; - if b(ui, icon::TIMER, tr("Show cook times on nodes"), timings) { - app.ui.prefs.node_timings = !timings; - } - let straight = app.ui.prefs.straight_wires; - if b( - ui, - if straight { icon::LINE_SEGMENT } else { icon::WAVE_SINE }, - if straight { tr("Wires: straight (click for curved)") } else { tr("Wires: curved (click for straight)") }, - straight, - ) { - app.ui.prefs.straight_wires = !straight; - } - let grid_on = app.ui.prefs.show_grid; - if b(ui, icon::GRID_FOUR, tr("Show the grid"), grid_on) { - app.ui.prefs.show_grid = !grid_on; - } - let snap = app.ui.prefs.snap_grid; - if b(ui, icon::MAGNET, tr("Snap nodes to the grid"), snap) { - app.ui.prefs.snap_grid = !snap; - } - ui.separator(); - if b(ui, icon::ARROWS_CLOCKWISE, tr("Compute outputs"), false) { - app.cooker.hold = false; - app.session.dirty = true; - } - if b(ui, icon::BROOM, tr("Clean up: remove unconnected dots and disabled nodes with nothing attached"), false) { - clean_up(app); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - align_tools(app, ui); - ui.separator(); - parent_size(app, ui); - }); - }); - // Row 2: quick insert. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - let b = |ui: &mut Ui, ic: &str, tip: &str| crate::widgets::icon_button(ui, ic, tip, false, 22.0).clicked(); - for (ic, def) in [ - (icon::IMAGE, "bitmap"), - (icon::PALETTE, "uniform"), - (icon::STACK, "blend"), - (icon::DROP, "blur"), - (icon::SHUFFLE, "channels_shuffle"), - (icon::CHART_LINE, "curve"), - (icon::WIND, "directional_blur"), - (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), - (icon::RULER, "distance"), - (icon::MOUNTAINS, "emboss"), - (icon::GRADIENT, "gradient_map"), - (icon::CIRCLE_HALF, "grayscale_conversion"), - (icon::SWATCHES, "hsl"), - (icon::SLIDERS_HORIZONTAL, "levels"), - (icon::CUBE, "normal"), - (icon::CODE, "pixel_processor"), - (icon::DIAMOND, "sharpen"), - (icon::ARROWS_CLOCKWISE, "transformation"), - (icon::WAVES, "warp"), - (icon::DICE_FIVE, "fx_map"), - (icon::SIGN_IN, "input_grayscale"), - (icon::SIGN_OUT, "output"), - ] { - let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); - if b(ui, ic, label) { - add_node_near_selection(app, def); - } - } - ui.separator(); - if b(ui, icon::NOTE, tr("Add comment")) { - let c = view_center(app); - app.run("graph.comment.add", json!({"at": [c.x - 60.0, c.y - 20.0]})); - } - if b(ui, icon::DOT_OUTLINE, tr("Add dot (reroute)")) { - add_node_near_selection(app, "dot"); - } - if b(ui, icon::SELECTION, tr("Add frame around the selection")) { - let c = view_center(app); - let p = if app.session.selection.is_empty() { json!({"rect": [c.x - 160.0, c.y - 100.0, 320.0, 200.0]}) } else { json!({}) }; - app.run("graph.frame.add", p); - } - if b(ui, icon::MAP_PIN, tr("Add navigation pin")) { - let c = view_center(app); - app.run("graph.pin.add", json!({"at": [c.x, c.y]})); - } - }); - }); -} - -/// Zoom the graph camera to `zoom` around the view's center. -fn zoom_to(app: &mut MaterialCraftApp, zoom: f32) { - let c = view_center(app); - let v = app.graph.view; - let cam = &mut app.ui.graph_camera; - cam.zoom = zoom; - cam.pan = [c.x - v.width() * 0.5 / zoom, c.y - v.height() * 0.5 / zoom]; - *cam = cam.sanitized(); -} - -/// Save the graph panel as a PNG: a screenshot of the window, cropped to the canvas. -fn screenshot(app: &mut MaterialCraftApp, ctx: &egui::Context) { - #[cfg(not(target_arch = "wasm32"))] - { - let name = format!("{}_graph.png", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default())); - let Some(path) = rfd::FileDialog::new().set_file_name(name).add_filter("PNG", &["png"]).save_file() else { return }; - let view = app.graph.view; - let ppp = ctx.pixels_per_point(); - let repaint = ctx.clone(); - let callback = egui::ScreenshotCallback::new(move |img| { - let x0 = ((view.left() * ppp).max(0.0) as usize).min(img.size[0]); - let y0 = ((view.top() * ppp).max(0.0) as usize).min(img.size[1]); - let x1 = ((view.right() * ppp).max(0.0) as usize).clamp(x0, img.size[0]); - let y1 = ((view.bottom() * ppp).max(0.0) as usize).clamp(y0, img.size[1]); - let (w, h) = (x1 - x0, y1 - y0); - if w == 0 || h == 0 { - return; - } - let mut rgba = Vec::with_capacity(w * h * 4); - for y in y0..y1 { - for x in x0..x1 { - rgba.extend_from_slice(&img.pixels[y * img.size[0] + x].to_array()); - } - } - if let Some((_, _, png)) = crate::control::encode_png(w as u32, h as u32, rgba) - && let Err(e) = std::fs::write(&path, png) - { - log::warn!("could not save the graph screenshot {}: {e}", path.display()); - } - repaint.request_repaint(); - }); - ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); - app.toast(tr("Saving a screenshot of the graph"), false); - } - #[cfg(target_arch = "wasm32")] - { - let _ = ctx; - app.toast(tr("Screenshots are saved from the desktop app"), true); - } -} - -/// The ⓘ popup: what the graph is, how big and how long it takes. -fn graph_info(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let Ok(g) = app.session.graph() else { return }; - let [w, h] = g.size_px(); - let outputs = g.nodes.iter().filter(|n| n.def == "output").count(); - let errors = app.session.cooked.nodes.values().filter(|r| r.error.is_some()).count(); - let ms: f32 = app.session.cooked.nodes.values().map(|r| r.ms).sum(); - ui.set_min_width(220.0); - ui.label(egui::RichText::new(&g.name).strong()); - ui.label( - egui::RichText::new(format!("{} ({})", app.session.pkg.name, app.session.path.as_deref().unwrap_or(tr("not saved yet")))).small().color(tk.text_dim), - ); - ui.separator(); - egui::Grid::new("graph-info").num_columns(2).spacing([12.0, 2.0]).show(ui, |ui| { - ui.label(tr("Size")); - ui.label(format!("{w} x {h}")); - ui.end_row(); - ui.label(tr("Format")); - ui.label(format!("{} bits", g.format.bits())); - ui.end_row(); - ui.label(tr("Nodes")); - ui.label(format!("{} ({} {})", g.nodes.len(), outputs, tr("outputs"))); - ui.end_row(); - ui.label(tr("Wires")); - ui.label(g.connections.len().to_string()); - ui.end_row(); - ui.label(tr("Last cook")); - ui.label(if errors > 0 { format!("{ms:.0} ms, {errors} {}", tr("error(s)")) } else { format!("{ms:.0} ms") }); - ui.end_row(); - ui.label(tr("Exposed")); - ui.label(g.exposed.len().to_string()); - ui.end_row(); - }); - ui.separator(); - if ui.button(tr("Graph attributes...")).clicked() { - app.run("edit.selectNone", json!({})); - app.ui.dock.focus(crate::docking::Panel::Properties); - ui.close(); - } -} - -/// Remove reroute dots nothing uses and disabled nodes with no wires. -fn clean_up(app: &mut MaterialCraftApp) { - let Ok(g) = app.session.graph() else { return }; - let wired = |id: NodeId| g.connections.iter().any(|c| c.from == id || c.to == id); - let ids: Vec<u64> = - g.nodes.iter().filter(|n| (n.def == "dot" && !g.connections.iter().any(|c| c.from == n.id)) || (n.disabled && !wired(n.id))).map(|n| n.id.0).collect(); - if ids.is_empty() { - app.toast(tr("Nothing to clean up"), false); - return; - } - let n = ids.len(); - if app.run("graph.select", json!({"ids": ids})).is_some() && app.run("edit.delete", json!({})).is_some() { - app.toast(format!("{} {n}", tr("Removed nodes:")), false); - } -} - -/// Stack checkbox and the align buttons (right-to-left layout: declared in reverse). -fn align_tools(app: &mut MaterialCraftApp, ui: &mut Ui) { - let stack = app.ui.stack_align; - let two = app.session.selection.len() >= 2; - let run = |app: &mut MaterialCraftApp, modes: &[&str]| { - for m in modes { - app.run("graph.align", json!({"mode": m})); - } - }; - if crate::widgets::icon_button(ui, icon::ROWS, tr("Align vertically (stack under one another)"), false, 22.0).clicked() && two { - run(app, if stack { &["hcenter", "vdistribute"] } else { &["hcenter"] }); - } - if crate::widgets::icon_button(ui, icon::COLUMNS, tr("Align horizontally (stack side by side)"), false, 22.0).clicked() && two { - run(app, if stack { &["vcenter", "hdistribute"] } else { &["vcenter"] }); - } - for (ic, mode, tip) in [(icon::ALIGN_TOP, "top", "Align top edges"), (icon::ALIGN_LEFT, "left", "Align left edges")] { - if crate::widgets::icon_button(ui, ic, tr(tip), false, 22.0).clicked() && two { - run(app, &[mode]); - } - } - let r = ui.checkbox(&mut app.ui.stack_align, tr("Stack")); - crate::widgets::name(&r, egui::Role::CheckBox, "Stack"); - r.on_hover_text(tr("Aligning also closes the gaps between the nodes")); -} - -/// "Parent size: [1024 ▾] 🔗 [1024 ▾] ⟲" (right-to-left layout: declared in reverse). -fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Ok(g) = app.session.graph() else { return }; - let [w, h] = g.size; - let mut nw = w; - let mut nh = h; - let combo = |ui: &mut Ui, id: &str, v: &mut u32| { - let r = egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| { - for l in 4..=13u32 { - ui.selectable_value(v, l, format!("{}", 1u32 << l)); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); - }; - if crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset the parent size to 1024 x 1024"), false, 20.0).clicked() { - nw = 10; - nh = 10; - } - combo(ui, "parent-h", &mut nh); - let link = app.ui.parent_link; - if crate::widgets::icon_button(ui, if link { icon::LINK } else { icon::LINK_BREAK }, tr("Link width and height"), link, 20.0).clicked() { - app.ui.parent_link = !link; - } - combo(ui, "parent-w", &mut nw); - ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim)); - if app.ui.parent_link { - if nw != w { - nh = nw; - } else if nh != h { - nw = nh; - } - } - if (nw, nh) != (w, h) { - app.run("graph.size", json!({"log2": [nw, nh]})); - } -} - -pub fn view_center(app: &MaterialCraftApp) -> Pos2 { - let c = &app.ui.graph_camera.sanitized(); - let v = app.graph.view; - pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) -} - -/// Add `def` right of the last selected node (wired from it when it fits), else mid-view. -pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) { - let sel = app.session.selection.last().copied(); - let has_inputs = materialcraft_engine::nodes::find(def).is_some_and(|d| !d.inputs.is_empty()); - let params = match sel { - Some(id) if has_inputs && !app.session.output_ports(id).is_empty() => json!({"def": def, "connectFrom": {"node": id.0}}), - _ => { - let c = view_center(app); - json!({"def": def, "at": [c.x - NODE_W * 0.5, c.y - 60.0]}) - } - }; - app.run("graph.node.add", params); -} - -/// Add a Bitmap node (wired to the selection when that makes sense) showing `resource`. -pub fn add_bitmap_node(app: &mut MaterialCraftApp, resource: &str) { - add_node_near_selection(app, "bitmap"); - if let Some(id) = app.session.selection.last().copied() { - app.run("graph.node.param", json!({"id": id.0, "param": "resource", "value": resource})); - } -} - -/// File ▸ Import bitmap from a path: import, add the node and bind it, as one undo entry. -#[cfg(not(target_arch = "wasm32"))] -pub fn import_bitmap_file(app: &mut MaterialCraftApp, path: &str) { - app.session.begin_group("Import bitmap"); - if let Some(r) = app.run("file.importBitmap", json!({"path": path})) { - add_bitmap_node(app, r["name"].as_str().unwrap_or_default()); - } - app.session.end_group(); -} - -fn run_gesture(app: &mut MaterialCraftApp, label: &str, commands: &[(&str, serde_json::Value)]) { - let result = app.session.group(label, |session| { - // `"from": "last"` names the node the previous command added. - let mut last: Option<u64> = None; - for (id, params) in commands { - let mut params = params.clone(); - if params.get("from").and_then(serde_json::Value::as_str) == Some("last") { - params["from"] = json!(last.ok_or_else(|| materialcraft_engine::EngineError::Other("no node was added before".into()))?); - } - let r = crate::cook::execute_guarded(session, id, ¶ms).map_err(materialcraft_engine::EngineError::Other)?; - if let Some(n) = r.get("id").and_then(serde_json::Value::as_u64) { - last = Some(n); - } - } - Ok(()) - }); - if let Err(error) = result { - app.toast(error.to_string(), true); - } -} - -/// Finish dragging a wire onto input `to_port` of `to`: connect it, first removing the link it -/// was pulled off (`detached`). The gesture is one undo entry. -fn rewire(app: &mut MaterialCraftApp, from: &(NodeId, String), detached: Option<&(NodeId, String)>, to: NodeId, to_port: &str) { - let mut commands = Vec::new(); - if let Some((n, p)) = detached - && (*n != to || p != to_port) - { - commands.push(("graph.disconnect", json!({"to": n.0, "toPort": p}))); - } - if let Some(converter) = conversion_node(app, from, to, to_port) { - // Preferences ▸ Graph: a conversion node between a color output and a grayscale input (or the reverse). - let (x, y) = midpoint(app, from.0, to); - commands.push(("graph.node.add", json!({"def": converter, "at": [x, y], "connectFrom": {"node": from.0.0, "port": from.1}}))); - commands.push(("graph.connect", json!({"from": "last", "to": to.0, "toPort": to_port}))); - run_gesture(app, "Connect", &commands); - return; - } - commands.push(("graph.connect", json!({"from": from.0.0, "fromPort": from.1, "to": to.0, "toPort": to_port}))); - run_gesture(app, "Connect", &commands); -} - -/// Connect `from` to `to`'s input, inserting a conversion node when the preference asks for one. -pub fn connect(app: &mut MaterialCraftApp, from: &(NodeId, String), to: NodeId, to_port: &str) { - rewire(app, from, None, to, to_port); -} - -/// The node that converts the kinds between an output and an input (`None` = the kinds agree -/// or the preference is off): Grayscale Conversion for color → gray, Gradient Map for gray → color. -fn conversion_node(app: &MaterialCraftApp, from: &(NodeId, String), to: NodeId, to_port: &str) -> Option<&'static str> { - use materialcraft_engine::nodes::PortKind; - if !app.ui.prefs.auto_convert { - return None; - } - let g = app.session.graph().ok()?; - let out_kind = materialcraft_engine::eval::ports(&app.session.pkg, g.node(from.0).ok()?).1.into_iter().find(|p| p.id == from.1)?.kind; - let in_kind = materialcraft_engine::eval::ports(&app.session.pkg, g.node(to).ok()?).0.into_iter().find(|p| p.id == to_port)?.kind; - match (out_kind, in_kind) { - (PortKind::Color, PortKind::Gray) => Some("grayscale_conversion"), - (PortKind::Gray, PortKind::Color) => Some("gradient_map"), - _ => None, - } -} - -/// Halfway between two nodes (graph space), for a node inserted between them. -fn midpoint(app: &MaterialCraftApp, a: NodeId, b: NodeId) -> (f32, f32) { - let g = app.session.graph().ok(); - let pos = |id: NodeId| g.and_then(|g| g.node(id).ok()).map_or([0.0, 0.0], |n| n.pos); - let (pa, pb) = (pos(a), pos(b)); - ((pa[0] + pb[0]) * 0.5, (pa[1] + pb[1]) * 0.5) -} - -/// Finish dragging a frame: set its rectangle and move the nodes it carries, as one undo entry. -fn move_frame(app: &mut MaterialCraftApp, id: u64, rect: [f32; 4], nodes: &[NodeId], delta: Vec2) { - let mut commands = vec![("graph.frame.edit", json!({"id": id, "rect": rect}))]; - if !nodes.is_empty() { - commands.push(("graph.node.move", json!({"ids": nodes.iter().map(|n| n.0).collect::<Vec<_>>(), "by": [delta.x, delta.y]}))); - } - run_gesture(app, "Move frame", &commands); -} - -/// Frame the graph (or the selection) in the view. -fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool) { - let thumbs = app.ui.prefs.thumbnails; - let Ok(g) = app.session.graph() else { return }; - let mut r = Rect::NOTHING; - for n in &g.nodes { - if only_selection && !app.session.selection.contains(&n.id) { - continue; - } - let (i, o) = materialcraft_engine::eval::ports(&app.session.pkg, n); - r = r.union(node_rect(n, i.len(), o.len(), thumbs)); - } - for f in &g.frames { - if !only_selection { - r = r.union(Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2], f.rect[3]))); - } - } - if !r.is_finite() || r.width() <= 0.0 { - app.ui.graph_camera = crate::state::GraphCamera::default(); - return; - } - let r = r.expand(40.0); - let zoom = (view.width() / r.width()).min(view.height() / r.height()).clamp(0.1, 1.5); - let pan = r.center().to_vec2() - vec2(view.width(), view.height()) * 0.5 / zoom; - app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; -} - -fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let ctx = ui.ctx().clone(); - let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Node graph"); - app.graph.view = rect; - if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) { - app.ui.frame_all = false; - app.graph.framed_graph = Some(app.session.graph); - app.graph.selected_wires.clear(); - frame(app, rect, false); - } - let painter = ui.painter_at(rect); - // Background and grid. - painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31)); - app.ui.graph_camera = app.ui.graph_camera.sanitized(); - let cam = Cam { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; - STRAIGHT_WIRES.store(app.ui.prefs.straight_wires, std::sync::atomic::Ordering::Relaxed); - if app.ui.prefs.show_grid { - grid(&painter, &cam, rect); - } - - let pointer = ctx.input(|i| i.pointer.hover_pos()); - let hovered_canvas = pointer.is_some_and(|p| rect.contains(p)) && resp.hovered(); - - // Zoom around the pointer. - if hovered_canvas || ui.rect_contains_pointer(rect) { - let mut scroll = ctx.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0); - if app.ui.prefs.invert_zoom { - scroll = -scroll; - } - if scroll.abs() > 0.0 - && let Some(p) = pointer - && rect.contains(p) - { - let before = cam.to_graph(p); - let zoom = (cam.zoom * (scroll * 0.0025).exp()).clamp(0.08, 4.0); - let pan = before.to_vec2() - (p - rect.min) / zoom; - app.ui.graph_camera = crate::state::GraphCamera { pan: [pan.x, pan.y], zoom }; - } - } - let cam = Cam { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom.clamp(0.08, 4.0) }; - - let thumbs_on = app.ui.prefs.thumbnails; - let Ok(g) = app.session.graph() else { return }; - let g = g.clone(); - let selection = app.session.selection.clone(); - let node_delta = match &app.graph.drag { - Some(Drag::Nodes { delta }) => *delta, - _ => Vec2::ZERO, - }; - let frame_move = match &app.graph.drag { - Some(Drag::Frame { id, delta, resize: false, nodes }) => Some((*id, *delta, nodes.clone())), - _ => None, - }; - - // Layout every node and its ports. - struct Laid { - id: NodeId, - rect: Rect, - ins: Vec<(String, String, PortKind, Pos2)>, - outs: Vec<(String, String, PortKind, Pos2)>, - } - let mut laid: Vec<Laid> = Vec::with_capacity(g.nodes.len()); - for n in &g.nodes { - let (ins, outs) = materialcraft_engine::eval::ports(&app.session.pkg, n); - let mut r = node_rect(n, ins.len(), outs.len(), thumbs_on); - if selection.contains(&n.id) { - r = r.translate(node_delta); - } - if let Some((_, d, nodes)) = &frame_move - && nodes.contains(&n.id) - { - r = r.translate(*d); - } - let dot = n.def == "dot"; - let pi = |i: usize, output: bool, total: usize| port_pos(r, i, total, output, dot); - laid.push(Laid { - id: n.id, - rect: r, - ins: ins.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, false, ins.len()))).collect(), - outs: outs.iter().enumerate().map(|(i, p)| (p.id.clone(), p.label.clone(), p.kind, pi(i, true, outs.len()))).collect(), - }); - } - app.graph.rects = laid.iter().map(|l| (l.id, Rect::from_min_max(cam.to_screen(l.rect.min), cam.to_screen(l.rect.max)))).collect(); - app.graph.ports = laid - .iter() - .flat_map(|l| { - let ins = l.ins.iter().map(move |(id, label, kind, p)| PortHit { - node: l.id, - output: false, - port: id.clone(), - label: label.clone(), - pos: *p, - kind: *kind, - }); - let outs = l.outs.iter().map(move |(id, label, kind, p)| PortHit { - node: l.id, - output: true, - port: id.clone(), - label: label.clone(), - pos: *p, - kind: *kind, - }); - ins.chain(outs) - }) - .map(|mut h| { - h.pos = cam.to_screen(h.pos); - h - }) - .collect(); - - // Frames (behind everything). - let mut frame_hits: Vec<(u64, Rect, Rect)> = Vec::new(); - for f in &g.frames { - let mut r = Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2], f.rect[3])); - match &app.graph.drag { - Some(Drag::Frame { id, delta, resize: false, .. }) if *id == f.id => r = r.translate(*delta), - Some(Drag::Frame { id, delta, resize: true, .. }) if *id == f.id => r.max += *delta, - _ => {} - } - let sr = Rect::from_min_max(cam.to_screen(r.min), cam.to_screen(r.max)); - let c = f.color; - let fill = Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, (c[3].clamp(0.05, 0.9) * 255.0) as u8); - painter.rect_filled(sr, 4.0, fill); - let title = Rect::from_min_size(sr.min, vec2(sr.width(), (20.0 * cam.zoom).max(12.0))); - painter.rect_filled(title, CornerRadius { nw: 4, ne: 4, sw: 0, se: 0 }, fill.gamma_multiply(1.6)); - painter.text( - title.left_center() + vec2(6.0, 0.0), - Align2::LEFT_CENTER, - &f.title, - FontId::proportional((12.0 * cam.zoom).clamp(8.0, 18.0)), - tk.text_strong, - ); - let grip = Rect::from_min_size(sr.max - vec2(12.0, 12.0), vec2(12.0, 12.0)); - painter.line_segment([grip.left_bottom(), grip.right_top()], Stroke::new(1.0, tk.text_dim)); - frame_hits.push((f.id, title, grip)); - } - - // Wires. - let cooked = &app.session.cooked; - let detached = match &app.graph.drag { - Some(Drag::Wire { detached: Some(d), .. }) => Some(d.clone()), - _ => None, - }; - let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(g.connections.len()); - for c in &g.connections { - if detached.as_ref().is_some_and(|(n, p)| *n == c.to && *p == c.to_port) { - continue; - } - let a = laid.iter().find(|l| l.id == c.from).and_then(|l| l.outs.iter().find(|p| p.0 == c.from_port)); - let b = laid.iter().find(|l| l.id == c.to).and_then(|l| l.ins.iter().find(|p| p.0 == c.to_port)); - if let (Some(a), Some(b)) = (a, b) { - wires.push(((c.to, c.to_port.clone()), bezier_points(cam.to_screen(a.3), cam.to_screen(b.3)))); - } - } - // Hover: not where a node card or a port sits on top of the wire. - let over_card = |p: Pos2| app.graph.rects.iter().any(|(_, r)| r.contains(p)) || nearest_port(&app.graph.ports, p, 9.0).is_some(); - let wire_hover = match &app.graph.drag { - None => pointer.filter(|p| rect.contains(*p) && !over_card(*p)).and_then(|p| wire_at(&wires, p)).cloned(), - Some(Drag::WirePress { wire, .. }) => Some(wire.clone()), - Some(_) => None, - }; - for (w, ctrl) in &wires { - let Some(c) = g.input_of(w.0, &w.1) else { continue }; - let hot = selection.contains(&c.from) || selection.contains(&c.to); - let picked = app.graph.selected_wires.contains(w); - let hovered = wire_hover.as_ref() == Some(w); - let base = (2.0 * cam.zoom).clamp(1.0, 3.0); - let stroke = if picked { - Stroke::new(base + 2.0, tk.accent) - } else if hovered { - Stroke::new(base + 1.0, Color32::WHITE) - } else { - Stroke::new(base, if hot { tk.accent } else { Color32::from_gray(0xb4) }) - }; - painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke)); - } - app.graph.wires = wires; - - // Nodes. - let font = FontId::proportional((10.5 * cam.zoom).clamp(6.0, 16.0)); - let small = FontId::proportional((9.0 * cam.zoom).clamp(5.5, 13.0)); - let mut node_resps: Vec<(NodeId, egui::Response)> = Vec::new(); - for l in &laid { - let Ok(n) = g.node(l.id) else { continue }; - let sr = Rect::from_min_max(cam.to_screen(l.rect.min), cam.to_screen(l.rect.max)); - if !sr.intersects(rect) { - continue; - } - let selected = selection.contains(&n.id); - let result = cooked.nodes.get(&n.id); - let error = result.and_then(|r| r.error.clone()); - let resp = ui.interact(sr, ui.scope_id().with(("node", n.id.0)), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Button, &node_label(n)); - if n.def == "dot" { - painter.circle( - sr.center(), - DOT_R * cam.zoom, - Color32::from_gray(0x50), - Stroke::new(1.5, if selected { tk.accent } else { Color32::from_gray(0xb4) }), - ); - } else { - let header = Rect::from_min_size(sr.min, vec2(sr.width(), HEADER_H * cam.zoom)); - let r = (5.0 * cam.zoom).clamp(1.0, 6.0) as u8; - painter.rect_filled(sr, r, Color32::from_rgb(0x1e, 0x20, 0x24)); - painter.rect_filled(header, CornerRadius { nw: r, ne: r, sw: 0, se: 0 }, header_color(&n.def)); - let title = crate::widgets::elided(&painter, node_label(n), font.size, Color32::WHITE, header.width() - 8.0); - painter.galley(header.left_center() + vec2(4.0, -title.size().y * 0.5), title, Color32::WHITE); - // Thumbnail or compact body. - let body = Rect::from_min_max(pos2(sr.left(), header.bottom()), pos2(sr.right(), sr.bottom() - FOOTER_H * cam.zoom)); - if let Some(r0) = result - && let Some(img) = r0.outputs.first() - && thumbs_on - { - let side = body.width().min(body.height()) - 6.0 * cam.zoom; - let tr_ = Rect::from_center_size(body.center(), vec2(side, side)); - let tex = app.thumbs.node(&ctx, r0.key, 0, img); - painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if n.disabled { Color32::from_gray(90) } else { Color32::WHITE }); - } else if result.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), tk.text_dim); - } - // Footer: size and format. - let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max); - if let Some(img) = result.and_then(|r| r.outputs.first()) { - let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }; - let format = format!("{}{}", if img.is_gray() { "L" } else { "C" }, bits); - let txt = if let Some(limit) = app.session.preview_size { - if error.is_none() { - let [pw, ph] = g.size_px(); - resp.clone().on_hover_text(format!( - "{} x {} ({format}bpc)\n{}: {pw} x {ph}\n{}: {limit} px\n{}", - img.w, - img.h, - tr("Parent size"), - tr("Preview limit"), - tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.") - )); - } - format!("{}x{} {}", img.w, img.h, tr("Preview")) - } else { - format!("{}x{} - {format}", img.w, img.h) - }; - painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim); - } - if n.def == "output" { - painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE); - } - if app.ui.prefs.node_timings - && let Some(r0) = result - { - let txt = if r0.cached { format!("{:.1} ms ({})", r0.ms, tr("cached")) } else { format!("{:.1} ms", r0.ms) }; - painter.text(header.right_top() + vec2(-2.0, HEADER_H * cam.zoom + 2.0), Align2::RIGHT_TOP, txt, small.clone(), tk.warning); - } - let outline = if error.is_some() { - Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0)) - } else if selected { - Stroke::new(2.0, tk.accent) - } else if resp.hovered() { - Stroke::new(1.0, Color32::from_gray(0x90)) - } else { - Stroke::new(1.0, Color32::from_gray(0x10)) - }; - painter.rect_stroke(sr, r, outline, StrokeKind::Outside); - if n.disabled { - painter.line_segment([sr.left_top(), sr.right_bottom()], Stroke::new(1.5, tk.danger)); - } - if let Some(e) = &error { - resp.clone().on_hover_text(e); - } - } - node_resps.push((n.id, resp)); - } - - // Comments. - let mut comment_hits: Vec<(u64, Rect)> = Vec::new(); - for c in &g.comments { - let mut p = pos2(c.pos[0], c.pos[1]); - if let Some(Drag::Comment { id, delta }) = &app.graph.drag - && *id == c.id - { - p += *delta; - } - let r = Rect::from_min_size(cam.to_screen(p), vec2(c.size[0], c.size[1]) * cam.zoom); - painter.rect_filled(r, 4.0, Color32::from_rgba_unmultiplied(0x5a, 0x54, 0x2e, 230)); - painter.rect_stroke(r, 4.0, Stroke::new(1.0, Color32::from_rgb(0x9a, 0x8c, 0x40)), StrokeKind::Inside); - if app.graph.editing.as_ref().is_some_and(|(id, _)| *id == c.id) { - comment_hits.push((c.id, r)); - continue; - } - let galley = - painter.layout(c.text.clone(), FontId::proportional((11.0 * cam.zoom).clamp(6.0, 18.0)), Color32::from_rgb(0xf3, 0xec, 0xc8), r.width() - 10.0); - painter.galley(r.min + vec2(5.0, 4.0), galley, Color32::WHITE); - comment_hits.push((c.id, r)); - } - - // Pins. - for pin in &g.pins { - let p = cam.to_screen(pos2(pin.pos[0], pin.pos[1])); - painter.text(p, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), tk.accent); - painter.text(p + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), tk.text); - } - - // Ports (drawn last, interactable over the node cards). - let port_hover = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 9.0)).cloned(); - for h in &app.graph.ports { - if !rect.contains(h.pos) { - continue; - } - let hot = port_hover.as_ref().is_some_and(|x| x.node == h.node && x.port == h.port && x.output == h.output); - let r = (PORT_R * cam.zoom).clamp(2.5, 7.0) * if hot { 1.4 } else { 1.0 }; - painter.circle(h.pos, r, port_color(h.kind), Stroke::new(1.0, Color32::from_gray(0x18))); - } - if let Some(h) = &port_hover { - let anchor = if h.output { Align2::LEFT_CENTER } else { Align2::RIGHT_CENTER }; - let off = if h.output { vec2(10.0, 0.0) } else { vec2(-10.0, 0.0) }; - let g_ = painter.layout_no_wrap(h.label.clone(), FontId::proportional(11.0), tk.text_strong); - let bg = anchor.anchor_size(h.pos + off, g_.size()).expand(3.0); - painter.rect_filled(bg, 3.0, Color32::from_black_alpha(200)); - painter.galley(bg.min + vec2(3.0, 3.0), g_, tk.text_strong); - } - - // A wire under a comment is not hit. - let wire_hover = wire_hover.filter(|_| !pointer.is_some_and(|p| comment_hits.iter().any(|(_, r)| r.contains(p)))); - if wire_hover.is_some() { - ctx.set_cursor_icon(egui::CursorIcon::PointingHand); - } - handle_input( - app, - ui, - &resp, - rect, - &cam, - &node_resps, - &frame_hits, - &comment_hits, - port_hover, - wire_hover, - &laid.iter().map(|l| (l.id, l.rect)).collect::<Vec<_>>(), - ); - - // Drag previews. - match &app.graph.drag { - Some(Drag::Box { start }) => { - if let Some(p) = pointer { - let r = Rect::from_two_pos(*start, p); - painter.rect(r, 0.0, tk.accent.gamma_multiply(0.12), Stroke::new(1.0, tk.accent), StrokeKind::Inside); - } - } - Some(Drag::Wire { from, .. }) => { - if let (Some(p), Some(src)) = (pointer, app.graph.ports.iter().find(|h| h.output && h.node == from.0 && h.port == from.1)) { - bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent)); - } - } - Some(Drag::WireFromInput { to }) => { - if let (Some(p), Some(dst)) = (pointer, app.graph.ports.iter().find(|h| !h.output && h.node == to.0 && h.port == to.1)) { - bezier(&painter, p, dst.pos, Stroke::new(2.0, tk.accent)); - } - } - _ => {} - } - - search_popup(app, ui, &cam); - comment_editor(app, ui); - let (failed, placeholders) = app.session.cook_failures(); - let mut at = rect.right_bottom() - vec2(8.0, 8.0); - if !failed.is_empty() { - let text = format!("{} {} node(s) failed", icon::WARNING, failed.len()); - at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.danger).top() - 2.0; - } - // Placeholders for missing SBS nodes are a soft warning, not a failure - if placeholders > 0 { - let text = format!("{} {placeholders} missing node(s), see the Console", icon::WARNING); - painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.warning); - } -} - -fn grid(p: &egui::Painter, cam: &Cam, rect: Rect) { - for (step, alpha) in [(32.0f32, 10u8), (256.0, 22)] { - let s = step * cam.zoom; - if s < 8.0 { - continue; - } - let col = Color32::from_white_alpha(alpha); - let x0 = cam.pan.x - (cam.pan.x.rem_euclid(step)); - let mut x = x0; - while cam.to_screen(pos2(x, 0.0)).x < rect.right() { - let sx = cam.to_screen(pos2(x, 0.0)).x; - p.line_segment([pos2(sx, rect.top()), pos2(sx, rect.bottom())], Stroke::new(1.0, col)); - x += step; - } - let y0 = cam.pan.y - (cam.pan.y.rem_euclid(step)); - let mut y = y0; - while cam.to_screen(pos2(0.0, y)).y < rect.bottom() { - let sy = cam.to_screen(pos2(0.0, y)).y; - p.line_segment([pos2(rect.left(), sy), pos2(rect.right(), sy)], Stroke::new(1.0, col)); - y += step; - } - } -} - -fn nearest_port(ports: &[PortHit], p: Pos2, radius: f32) -> Option<&PortHit> { - ports.iter().filter(|h| h.pos.distance(p) <= radius).min_by(|a, b| a.pos.distance(p).total_cmp(&b.pos.distance(p))) -} - -#[allow(clippy::too_many_arguments)] -fn handle_input( - app: &mut MaterialCraftApp, - ui: &mut Ui, - canvas: &egui::Response, - rect: Rect, - cam: &Cam, - nodes: &[(NodeId, egui::Response)], - frames: &[(u64, Rect, Rect)], - comments: &[(u64, Rect)], - port_hover: Option<PortHit>, - wire_hover: Option<WireRef>, - graph_rects: &[(NodeId, Rect)], -) { - let ctx = ui.ctx().clone(); - let (pointer, mods, primary_pressed, primary_down, middle_down, released) = ctx.input(|i| { - (i.pointer.interact_pos(), i.modifiers, i.pointer.primary_pressed(), i.pointer.primary_down(), i.pointer.middle_down(), i.pointer.any_released()) - }); - let zoom = cam.zoom; - let motion = ctx.input(|i| i.pointer.delta()) / zoom; - - // Starting gestures (only on a press inside the canvas, with no gesture running). - if app.graph.drag.is_none() - && let Some(p) = pointer - && rect.contains(p) - && app.graph.search.is_none() - { - if middle_down || (primary_pressed && mods.alt) { - app.graph.drag = Some(Drag::Pan); - } else if primary_pressed { - let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); - let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); - // Any press other than on a wire drops the wire selection. - if wire.is_none() { - app.graph.selected_wires.clear(); - } - if let Some(w) = wire { - app.graph.drag = Some(Drag::WirePress { wire: w.clone(), start: p }); - } else if let Some(h) = &port_hover { - if h.output { - app.graph.drag = Some(Drag::Wire { from: (h.node, h.port.clone()), detached: None }); - } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { - app.graph.drag = Some(Drag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); - } else { - app.graph.drag = Some(Drag::WireFromInput { to: (h.node, h.port.clone()) }); - } - } else if let Some((id, title, grip)) = frames.iter().find(|(_, t, g)| t.contains(p) || g.contains(p)) { - let resize = grip.contains(p) && !title.contains(p); - // Moving a frame carries the nodes inside it. - let inside: Vec<NodeId> = app - .session - .graph() - .ok() - .and_then(|g| g.frames.iter().find(|f| f.id == *id)) - .map(|f| { - let fr = Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2], f.rect[3])); - graph_rects.iter().filter(|(_, r)| fr.contains_rect(*r)).map(|(n, _)| *n).collect() - }) - .unwrap_or_default(); - app.graph.drag = Some(Drag::Frame { id: *id, delta: Vec2::ZERO, resize, nodes: if resize { Vec::new() } else { inside } }); - } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { - app.graph.drag = Some(Drag::Comment { id: *id, delta: Vec2::ZERO }); - } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { - if !app.session.selection.contains(id) { - if mods.ctrl || mods.shift { - app.session.selection.push(*id); - } else { - app.session.selection = vec![*id]; - } - } else if mods.ctrl { - app.session.selection.retain(|s| s != id); - } - app.graph.drag = Some(Drag::Nodes { delta: Vec2::ZERO }); - } else { - app.graph.drag = Some(Drag::Box { start: p }); - } - } - } - - // Continuing gestures. - match &mut app.graph.drag { - Some(Drag::Pan) => { - let d = ctx.input(|i| i.pointer.delta()) / zoom; - app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; - } - Some(Drag::Nodes { delta }) | Some(Drag::Frame { delta, .. }) | Some(Drag::Comment { delta, .. }) => *delta += motion, - Some(Drag::WirePress { wire, start }) => { - // Dragged far enough: a reroute dot where the press was, carried by the pointer. - if let Some(p) = pointer - && p.distance(*start) > 4.0 - { - let (wire, start) = (wire.clone(), *start); - let at = cam.to_graph(start); - app.graph.drag = None; - if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() { - app.graph.drag = Some(Drag::Nodes { delta: (p - start) / zoom }); - } - } - } - _ => {} - } - - // Ending gestures. - let ended = released && !primary_down && !middle_down; - if ended && let Some(drag) = app.graph.drag.take() { - match drag { - Drag::Pan => {} - Drag::WirePress { wire, .. } => { - app.session.selection.clear(); - let sel = &mut app.graph.selected_wires; - if mods.ctrl && sel.contains(&wire) { - // Ctrl+click toggles a wire out of the selection. - sel.retain(|w| *w != wire); - } else if mods.ctrl || mods.shift { - if !sel.contains(&wire) { - sel.push(wire); - } - } else { - *sel = vec![wire]; - } - } - Drag::Nodes { delta } => { - let mut delta = delta; - // Snap: the last selected node lands on the grid, the others keep their offsets. - if app.ui.prefs.snap_grid - && let Some(id) = app.session.selection.last() - && let Some(n) = app.session.graph().ok().and_then(|g| g.node(*id).ok()) - { - let target = pos2(((n.pos[0] + delta.x) / SNAP).round() * SNAP, ((n.pos[1] + delta.y) / SNAP).round() * SNAP); - delta = target - pos2(n.pos[0], n.pos[1]); - } - if delta.length() > 0.5 { - app.run("graph.node.move", json!({"by": [delta.x, delta.y]})); - } - } - Drag::Box { start } => { - if let Some(p) = pointer { - let r = Rect::from_two_pos(start, p); - if r.width() > 3.0 || r.height() > 3.0 { - let hit: Vec<NodeId> = app.graph.rects.iter().filter(|(_, nr)| r.intersects(*nr)).map(|(id, _)| *id).collect(); - if mods.ctrl || mods.shift { - for id in hit { - if !app.session.selection.contains(&id) { - app.session.selection.push(id); - } - } - } else { - app.session.selection = hit; - } - } else if !mods.ctrl && !mods.shift { - app.session.selection.clear(); - } - } - } - Drag::Wire { from, detached } => { - let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); - match target { - Some(t) => rewire(app, &from, detached.as_ref(), t.node, &t.port), - None => { - if let Some((n, p)) = &detached { - app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); - } else if let Some(p) = pointer - && rect.contains(p) - && app.ui.prefs.drag_create - { - open_search(app, cam.to_graph(p), Some(from)); - } - } - } - } - Drag::WireFromInput { to } => { - let source = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| h.output).cloned(); - if let Some(s) = source { - connect(app, &(s.node, s.port.clone()), to.0, &to.1); - } - } - Drag::Frame { id, delta, resize, nodes } => { - if delta.length() > 0.5 - && let Some(f) = app.session.graph().ok().and_then(|g| g.frames.iter().find(|f| f.id == id)).cloned() - { - let r = if resize { - [f.rect[0], f.rect[1], f.rect[2] + delta.x, f.rect[3] + delta.y] - } else { - [f.rect[0] + delta.x, f.rect[1] + delta.y, f.rect[2], f.rect[3]] - }; - move_frame(app, id, r, &nodes, delta); - } - } - Drag::Comment { id, delta } => { - if delta.length() > 0.5 - && let Some(c) = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == id)).cloned() - { - app.run("graph.comment.edit", json!({"id": id, "at": [c.pos[0] + delta.x, c.pos[1] + delta.y]})); - } - } - } - } - - // Clicks. - for (id, r) in nodes { - if r.double_clicked() { - let def = app.session.graph().ok().and_then(|g| g.node(*id).ok()).map(|n| (n.def.clone(), n.params.get("graph").cloned())); - match def { - Some((d, Some(Value::Text(name)))) if d == "graph_instance" => { - app.run("graph.open", json!({"graph": name})); - } - Some((d, _)) if d == "pixel_processor" || d == "value_processor" => { - app.run("view.2d", json!({"node": id.0, "port": 0})); - app.fn_editor = Some(crate::function_editor::FnEditor::new(*id, "function")); - } - _ => { - app.run("view.2d", json!({"node": id.0, "port": 0})); - } - } - } else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) { - // A click that leaves the node selected shows it, replacing a node shown earlier (a - // Ctrl+click that deselects it does not; the shown node keeps its chosen port). - app.run("view.2d", json!({"node": id.0})); - } - r.context_menu(|ui| node_menu(app, ui, *id)); - } - if let Some(h) = &port_hover - && h.output - && ctx.input(|i| i.pointer.primary_clicked()) - { - let idx = app.session.output_ports(h.node).iter().position(|p| *p == h.port).unwrap_or(0); - app.run("view.2d", json!({"node": h.node.0, "port": idx})); - } - for (id, r) in comments { - if canvas.double_clicked() && pointer.is_some_and(|p| r.contains(p)) { - let text = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == *id)).map(|c| c.text.clone()).unwrap_or_default(); - app.graph.editing = Some((*id, text)); - } - } - let on_node = pointer.is_some_and(|p| nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p))); - if canvas.double_clicked() - && !on_node - && let Some(p) = pointer - { - match &wire_hover { - // Double-click a wire: a reroute dot there. - Some(w) => { - let at = cam.to_graph(p); - app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]})); - app.graph.selected_wires.clear(); - } - None => open_search(app, cam.to_graph(p), None), - } - } - if canvas.secondary_clicked() - && let Some(p) = pointer - { - app.graph.menu_at = cam.to_graph(p); - app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); - // Right-clicking a selected wire keeps the selection (to swap or delete them all). - if let Some(w) = &app.graph.menu_wire - && !app.graph.selected_wires.contains(w) - { - app.session.selection.clear(); - app.graph.selected_wires = vec![w.clone()]; - } - } - let at = app.graph.menu_at; - canvas.context_menu(|ui| match app.graph.menu_wire.clone() { - Some(w) => wire_menu(app, ui, w, at), - None => canvas_menu(app, ui, at), - }); - - // Library drops. - if let Some(payload) = canvas.dnd_release_payload::<LibraryDrag>() - && let Some(p) = pointer - { - let gp = cam.to_graph(p); - let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; - crate::library::add_key(app, &payload.0, at); - } - - // Keys over the canvas. - let hovered = pointer.is_some_and(|p| rect.contains(p)); - if hovered && app.graph.search.is_none() { - let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); - let tab = app.ui.prefs.tab_key_menu && !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); - if (space || tab) - && let Some(p) = pointer - { - open_search(app, cam.to_graph(p), None); - } - if !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::F) && i.modifiers.is_none()) { - let sel = !app.session.selection.is_empty(); - frame(app, rect, sel); - } - } -} - -fn open_search(app: &mut MaterialCraftApp, at: Pos2, connect: Option<(NodeId, String)>) { - app.graph.search = Some(Search { at, text: String::new(), sel: 0, connect, focus: true }); -} - -/// Catalog entries matching `text` (label or id contains every word). -fn matches(text: &str) -> Vec<&'static materialcraft_engine::nodes::NodeDef> { - let words: Vec<String> = text.split_whitespace().map(str::to_ascii_lowercase).collect(); - let mut v: Vec<_> = materialcraft_engine::nodes::catalog() - .iter() - .filter(|d| d.id != "graph_instance") - .filter(|d| { - let hay = format!("{} {} {}", d.label.to_ascii_lowercase(), d.id, d.category.to_ascii_lowercase()); - words.iter().all(|w| hay.contains(w.as_str())) - }) - .collect(); - if let Some(w) = words.first() { - v.sort_by_key(|d| !d.label.to_ascii_lowercase().starts_with(w.as_str())); - } - v -} - -fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) { - let Some(s) = app.graph.search.as_mut() else { return }; - let tk = Tokens::get(ui.ctx()); - let screen = cam.to_screen(s.at); - let mut close = false; - let mut pick: Option<&'static str> = None; - egui::Area::new(egui::Id::unique("node-search")).fixed_pos(screen).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { - ui.set_width(260.0); - let mut reveal_selection = s.focus; - ui.horizontal(|ui| { - ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - let r = ui.add(egui::TextEdit::singleline(&mut s.text).hint_text(tr("Search nodes...")).desired_width(220.0)); - crate::widgets::name(&r, egui::Role::SearchInput, "Search nodes"); - if s.focus { - r.request_focus(); - s.focus = false; - } - if r.changed() { - s.sel = 0; - reveal_selection = true; - } - }); - let list = matches(&s.text); - let (up, down, enter, esc) = ui.input(|i| { - (i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)) - }); - if down { - s.sel = (s.sel + 1).min(list.len().saturating_sub(1)); - } - if up { - s.sel = s.sel.saturating_sub(1); - } - if esc { - close = true; - } - if enter && let Some(d) = list.get(s.sel) { - pick = Some(d.id); - } - egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { - for (i, d) in list.iter().enumerate() { - let r = ui.add( - egui::Button::selectable(i == s.sel, format!("{} ", d.label)) - .min_size(vec2(ui.available_width(), 0.0)) - .right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)), - ); - if i == s.sel && (up || down || reveal_selection) { - r.scroll_to_me(None); - } - if r.clicked() { - pick = Some(d.id); - } - } - if list.is_empty() { - ui.label(egui::RichText::new(tr("No matching node")).color(tk.text_dim)); - } - }); - }); - }); - let clicked_out = ui.input(|i| i.pointer.any_pressed()) - && ui.ctx().pointer_interact_pos().is_some_and(|p| !ui.ctx().layer_id_at(p).is_some_and(|l| l.id == egui::Id::unique("node-search"))); - if let Some(def) = pick { - let s = app.graph.search.take(); - if let Some(s) = s { - let mut p = json!({"def": def, "at": [s.at.x, s.at.y - 20.0]}); - if let Some((n, port)) = s.connect { - p["connectFrom"] = json!({"node": n.0, "port": port}); - } - app.run("graph.node.add", p); - } - } else if close || clicked_out { - app.graph.search = None; - } -} - -fn comment_editor(app: &mut MaterialCraftApp, ui: &mut Ui) { - let Some((id, text)) = app.graph.editing.as_mut() else { return }; - let Some(r) = app.session.graph().ok().and_then(|g| g.comments.iter().find(|c| c.id == *id)).map(|c| (c.pos, c.size)) else { - app.graph.editing = None; - return; - }; - let cam = &app.ui.graph_camera; - let origin = app.graph.view.min; - let at = origin + (Vec2::from(r.0) - Vec2::from(cam.pan)) * cam.zoom; - let mut done = false; - egui::Area::new(egui::Id::unique("comment-edit")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { - let resp = ui.add(egui::TextEdit::multiline(text).desired_width(r.1[0] * cam.zoom).desired_rows(3)); - resp.request_focus(); - done = resp.lost_focus() || ui.input(|i| i.key_pressed(egui::Key::Escape)); - }); - if done && let Some((id, text)) = app.graph.editing.take() { - app.run("graph.comment.edit", json!({"id": id, "text": text})); - } -} - -fn node_menu(app: &mut MaterialCraftApp, ui: &mut Ui, id: NodeId) { - if !app.session.selection.contains(&id) { - app.session.selection = vec![id]; - } - let mut item = |ui: &mut Ui, label: &str, cmd: &str, params: serde_json::Value| { - if ui.button(tr(label)).clicked() { - app.run(cmd, params); - ui.close(); - } - }; - item(ui, "View in 2D view", "view.2d", json!({"node": id.0})); - ui.separator(); - item(ui, "Copy selection", "edit.copy", json!({})); - item(ui, "Duplicate selection", "edit.duplicate", json!({})); - item(ui, "Duplicate selection without link", "edit.duplicate", json!({"withoutLinks": true})); - item(ui, "Delete selection", "edit.delete", json!({})); - item(ui, "Delete and relink", "edit.deleteRelink", json!({})); - ui.separator(); - item(ui, "Select upstream nodes", "graph.selectUpstream", json!({})); - item(ui, "Select downstream nodes", "graph.selectDownstream", json!({})); - item(ui, "Disable selection", "graph.node.disable", json!({})); - item(ui, "Reset parameters", "graph.node.reset", json!({"id": id.0})); - ui.separator(); - item(ui, "Add frame around selection", "graph.frame.add", json!({})); - item(ui, "Create graph from selection", "graph.createFromSelection", json!({})); -} - -/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands. -fn wires_json(wires: &[WireRef]) -> serde_json::Value { - json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()}) -} - -/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none -/// is selected. -pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { - let wires = std::mem::take(&mut app.graph.selected_wires); - if wires.is_empty() { - return false; - } - app.run("graph.wire.delete", wires_json(&wires)); - true -} - -/// Swap where the selected wires come from (the X key): two wires trade sources, more reverse -/// them in input order. The wires stay selected, so X again swaps back. `false` when no wire is -/// selected. -pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { - if app.graph.selected_wires.is_empty() { - return false; - } - let params = wires_json(&app.graph.selected_wires); - app.run("graph.wire.swap", params); - true -} - -fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) { - let n = app.graph.selected_wires.len(); - if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() { - app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]})); - app.graph.selected_wires.clear(); - ui.close(); - } - if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() { - swap_selected_wires(app); - ui.close(); - } - let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") }; - if ui.button(format!("{} {label}", icon::TRASH)).clicked() { - if n < 2 { - app.graph.selected_wires = vec![(to, port)]; - } - delete_selected_wires(app); - ui.close(); - } -} - -fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) { - ui.menu_button(tr("Add node"), |ui| { - for (cat, ids) in materialcraft_engine::nodes::categories() { - ui.menu_button(cat, |ui| { - egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| { - for id in ids { - let label = materialcraft_engine::nodes::find(id).map_or(id, |d| d.label); - if ui.button(label).clicked() { - app.run("graph.node.add", json!({"def": id, "at": [at.x, at.y]})); - ui.close(); - } - } - }); - }); - } - let others: Vec<String> = app.session.pkg.graphs.iter().enumerate().filter(|(i, _)| *i != app.session.graph).map(|(_, g)| g.name.clone()).collect(); - if !others.is_empty() { - ui.menu_button(tr("Graphs in this package"), |ui| { - for name in others { - if ui.button(&name).clicked() { - app.run("graph.node.add", json!({"def": "graph_instance", "at": [at.x, at.y], "params": {"graph": name}})); - ui.close(); - } - } - }); - } - }); - let mut item = |ui: &mut Ui, label: &str, cmd: &str, params: serde_json::Value| { - if ui.button(tr(label)).clicked() { - app.run(cmd, params); - ui.close(); - } - }; - item(ui, "Add Comment", "graph.comment.add", json!({"at": [at.x, at.y]})); - item(ui, "Add Frame", "graph.frame.add", json!({"rect": [at.x, at.y, 400.0, 260.0]})); - item(ui, "Add Navigation pin", "graph.pin.add", json!({"at": [at.x, at.y]})); - item(ui, "Add Dot node", "graph.node.add", json!({"def": "dot", "at": [at.x, at.y]})); - ui.separator(); - item(ui, "Compute graph", "graph.cook", json!({})); - item(ui, "Paste", "edit.paste", json!({"at": [at.x, at.y]})); - item(ui, "Select all", "edit.selectAll", json!({})); - ui.separator(); - let pins: Vec<(String, [f32; 2])> = app.session.graph().map(|g| g.pins.iter().map(|p| (p.name.clone(), p.pos)).collect()).unwrap_or_default(); - if !pins.is_empty() { - ui.menu_button(tr("Go to pin"), |ui| { - for (name, pos) in pins { - if ui.button(&name).clicked() { - let v = app.graph.view; - let z = app.ui.graph_camera.zoom; - app.ui.graph_camera.pan = [pos[0] - v.width() * 0.5 / z, pos[1] - v.height() * 0.5 / z]; - ui.close(); - } - } - }); - } - if ui.button(tr("Frame all")).clicked() { - app.ui.frame_all = true; - ui.close(); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_failed_rewire_keeps_the_original_connection_and_history() { - let mut app = empty_app(); - let source = app.run("graph.node.add", json!({"def": "uniform"})).unwrap()["id"].as_u64().unwrap(); - let target = app.run("graph.node.add", json!({"def": "levels"})).unwrap()["id"].as_u64().unwrap(); - app.run("graph.connect", json!({"from": source, "to": target, "toPort": "input"})).unwrap(); - let before = app.session.graph().unwrap().connections.clone(); - let history = app.session.history(); - rewire(&mut app, &(NodeId(source), "output".into()), Some(&(NodeId(target), "input".into())), NodeId(target), "missing"); - assert_eq!(app.session.graph().unwrap().connections, before); - assert_eq!(app.session.history(), history); - assert!(app.toasts.iter().any(|t| t.error)); - } - - fn empty_app() -> MaterialCraftApp { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - app.run("file.new", json!({"template": "empty"})); - app - } - - fn add(app: &mut MaterialCraftApp, def: &str) -> NodeId { - NodeId(app.run("graph.node.add", json!({"def": def})).and_then(|v| v["id"].as_u64()).unwrap()) - } - - #[test] - fn rewiring_a_dragged_link_is_one_undo_entry() { - let mut app = empty_app(); - let (a, b, c) = (add(&mut app, "clouds_1"), add(&mut app, "levels"), add(&mut app, "levels")); - app.run("graph.connect", json!({"from": a.0, "fromPort": "output", "to": b.0, "toPort": "input"})); - let base = app.session.history().len(); - rewire(&mut app, &(a, "output".to_string()), Some(&(b, "input".to_string())), c, "input"); - assert_eq!(app.session.history().len(), base + 1, "{:?}", app.session.history()); - let conns = &app.session.graph().unwrap().connections; - assert_eq!(conns.len(), 1); - assert_eq!(conns[0].to, c); - app.session.undo(); - assert_eq!(app.session.graph().unwrap().connections[0].to, b, "one undo restores the old link"); - } - - #[test] - fn dragging_a_frame_with_its_nodes_is_one_undo_entry() { - let mut app = empty_app(); - let n = add(&mut app, "levels"); - let id = app.run("graph.frame.add", json!({"rect": [0, 0, 300, 200]})).and_then(|v| v["id"].as_u64()).unwrap(); - let base = app.session.history().len(); - move_frame(&mut app, id, [10.0, 10.0, 300.0, 200.0], &[n], vec2(10.0, 10.0)); - assert_eq!(app.session.history().len(), base + 1, "{:?}", app.session.history()); - app.session.undo(); - assert_eq!(app.session.graph().unwrap().frames[0].rect, [0.0, 0.0, 300.0, 200.0]); - } - - /// The whole app in an offscreen egui context, driven one frame at a time. - struct Frames { - ctx: egui::Context, - app: MaterialCraftApp, - time: f64, - } - - impl Frames { - /// `session` after a few frames, so the canvas is laid out. - fn new(session: materialcraft_engine::Session) -> Frames { - let mut f = Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0 }; - for _ in 0..3 { - f.run(Vec::new(), egui::Modifiers::NONE); - } - f - } - - /// One frame with `events` while `modifiers` are held, in a desktop-sized window (egui's - /// default screen is so large that the 3D view's frame would exceed the texture limit). - fn run(&mut self, events: Vec<egui::Event>, modifiers: egui::Modifiers) { - self.time += 0.05; - let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); - let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))); - let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() }; - let app = &mut self.app; - self.ctx - .run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - } - - /// Press and release the primary button at `pos`, a second after any earlier click so - /// the two never pair into a double-click. - fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) { - self.time += 1.0; - self.run(vec![egui::Event::PointerMoved(pos)], modifiers); - for pressed in [true, false] { - self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers); - } - } - - /// The center of node `id` on screen last frame. - fn center(&self, id: NodeId) -> Pos2 { - self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen")) - } - - /// The node the 2D view shows once the graph has cooked. - fn shown(&mut self) -> Option<NodeId> { - self.app.session.cook(); - self.app.session.view2d_image().map(|(id, _)| id) - } - } - - /// A graph with a Perlin noise, a checker and an RGBA split side by side, framed on screen. - fn three_nodes() -> (Frames, [NodeId; 3]) { - let mut s = materialcraft_engine::sample_session(); - materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap(); - let ids = ["perlin_noise", "checker", "rgba_split"].iter().enumerate().map(|(i, def)| { - let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap(); - NodeId(added["id"].as_u64().unwrap()) - }); - let ids: [NodeId; 3] = ids.collect::<Vec<_>>().try_into().unwrap(); - s.selection.clear(); - (Frames::new(s), ids) - } - - #[test] - fn clicking_a_node_shows_it_in_the_2d_view() { - let (mut f, [noise, checker, _]) = three_nodes(); - // Shown explicitly first (a double-click, an output port or "View in 2D view"). - f.app.run("view.2d", json!({"node": noise.0})); - assert_eq!(f.shown(), Some(noise)); - let at = f.center(checker); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.app.session.view2d.node, Some(checker)); - assert_eq!(f.shown(), Some(checker)); - // And back. - let at = f.center(noise); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.view2d.node, Some(noise)); - assert_eq!(f.shown(), Some(noise)); - // Ctrl+click adds a node to the selection and shows it too. - let at = f.center(checker); - f.click(at, egui::Modifiers::CTRL); - assert_eq!(f.app.session.selection, vec![noise, checker]); - assert_eq!(f.shown(), Some(checker)); - } - - #[test] - fn ctrl_click_that_deselects_a_node_does_not_show_it() { - let (mut f, [noise, checker, _]) = three_nodes(); - f.app.session.selection = vec![noise, checker]; - f.app.run("view.2d", json!({"node": checker.0})); - let at = f.center(noise); - f.click(at, egui::Modifiers::CTRL); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.shown(), Some(checker)); - } - - #[test] - fn dragging_a_node_keeps_the_2d_view() { - let (mut f, [noise, checker, _]) = three_nodes(); - f.app.run("view.2d", json!({"node": noise.0})); - let before = f.app.session.graph().unwrap().node(checker).unwrap().pos; - let from = f.center(checker); - let none = egui::Modifiers::NONE; - f.run(vec![egui::Event::PointerMoved(from)], none); - f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none); - for step in 1..=8 { - f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none); - } - let to = from + vec2(40.0, 0.0); - f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none); - let after = f.app.session.graph().unwrap().node(checker).unwrap().pos; - let moved = 40.0 / f.app.ui.graph_camera.zoom; - assert!((after[0] - before[0] - moved).abs() < 1e-3 && after[1] == before[1], "the checker moved {before:?} -> {after:?}, not {moved} right"); - assert_eq!(f.app.session.selection, vec![checker]); - assert_eq!(f.shown(), Some(noise)); - } - - #[test] - fn clicking_the_shown_node_keeps_its_port() { - let (mut f, [_, _, split]) = three_nodes(); - f.app.run("view.2d", json!({"node": split.0, "port": 2})); - let at = f.center(split); - f.click(at, egui::Modifiers::NONE); - assert_eq!(f.app.session.selection, vec![split]); - assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2)); - } - - #[test] - fn tab_opens_search_in_the_full_workspace() { - let mut f = Frames::new(materialcraft_engine::sample_session()); - let pointer = f.app.graph.view.center(); - let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE); - assert!(f.app.graph.search.is_some()); - } - - #[test] - fn clicked_wires_swap_with_x_and_delete_together() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - app.run("file.new", json!({"template": "empty"})); - let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap(); - let a = id(app.run("graph.node.add", json!({"def": "clouds_1", "at": [0, -150]}))); - let b = id(app.run("graph.node.add", json!({"def": "checker", "at": [0, 150]}))); - let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); - app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); - app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); - let ctx = egui::Context::default(); - let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| { - events.insert(0, egui::Event::ModifiersChanged(modifiers)); - let input = egui::RawInput { events, ..Default::default() }; - ctx.run_ui(input, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - }; - for _ in 0..3 { - frame(&mut app, Vec::new(), egui::Modifiers::NONE); - } - let mid = - |app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap(); - let click = - |app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec<egui::Event>, egui::Modifiers), port: &str, m: egui::Modifiers| { - let p = mid(app, port); - let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m }; - frame(app, vec![egui::Event::PointerMoved(p)], m); - frame(app, vec![button(true)], m); - frame(app, vec![button(false)], m); - }; - click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE); - click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT); - assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires); - let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; - frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); - assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a)); - // Still selected: X again swaps back. - frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE); - assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b)); - frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE); - assert!(app.session.graph().unwrap().connections.is_empty()); - assert!(app.graph.selected_wires.is_empty()); - } - - #[test] - fn wires_connect_when_dragged_from_either_end() { - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - app.run("file.new", json!({"template": "empty"})); - let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap(); - let noise = id(app.run("graph.node.add", json!({"def": "perlin_noise", "at": [0, 0]}))); - let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]}))); - let ctx = egui::Context::default(); - let frame = |app: &mut MaterialCraftApp, events: Vec<egui::Event>| { - ctx.run_ui(egui::RawInput { events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))), ..Default::default() }, |ui| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }) - .textures_delta - .clear(); - }; - for _ in 0..3 { - frame(&mut app, Vec::new()); - } - let port = |app: &MaterialCraftApp, node: u64, output: bool, name: &str| { - app.graph.ports.iter().find(|h| h.node.0 == node && h.output == output && h.port == name).map(|h| h.pos).unwrap() - }; - let output = port(&app, noise, true, "output"); - let foreground = port(&app, blend, false, "foreground"); - let background = port(&app, blend, false, "background"); - let empty = app.graph.view.left_top() + vec2(5.0, 5.0); - let drag = |app: &mut MaterialCraftApp, from: Pos2, to: Pos2| { - let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(app, vec![egui::Event::PointerMoved(from)]); - frame(app, vec![button(from, true)]); - frame(app, vec![egui::Event::PointerMoved(to)]); - frame(app, vec![button(to, false)]); - }; - let source = |app: &MaterialCraftApp| app.session.graph().unwrap().input_of(NodeId(blend), "foreground").map(|c| (c.from.0, c.from_port.clone())); - - // From the input: only an output finishes the wire, and a miss changes nothing. - drag(&mut app, foreground, empty); - assert_eq!(source(&app), None); - assert!(app.graph.search.is_none()); - drag(&mut app, foreground, background); - assert_eq!(source(&app), None); - drag(&mut app, foreground, output); - assert_eq!(source(&app), Some((noise, "output".to_string()))); - - // From the output, as before. - app.run("graph.disconnect", json!({"to": blend, "toPort": "foreground"})); - drag(&mut app, output, foreground); - assert_eq!(source(&app), Some((noise, "output".to_string()))); - } - - #[test] - fn node_search_shortcuts_respect_hover_and_keyboard_focus() { - for key in [egui::Key::Space, egui::Key::Tab] { - for (hovered, editing) in [(true, false), (false, false), (true, true)] { - let ctx = egui::Context::default(); - let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); - let mut text = String::new(); - let mut draw = |ui: &mut Ui| { - if editing { - ui.text_edit_singleline(&mut text).request_focus(); - } - app.graph.keyboard_was_focused = ui.ctx().egui_wants_keyboard_input(); - show(&mut app, ui); - }; - ctx.run_ui(egui::RawInput::default(), &mut draw).textures_delta.clear(); - let pointer = if hovered { pos2(200.0, 200.0) } else { pos2(-10.0, -10.0) }; - let input = egui::RawInput { - events: vec![ - egui::Event::PointerMoved(pointer), - egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }, - ], - ..Default::default() - }; - ctx.run_ui(input, &mut draw).textures_delta.clear(); - assert_eq!(app.graph.search.is_some(), hovered && !editing, "{key:?}: hovered={hovered}, editing={editing}"); - if let Some(search) = &app.graph.search { - let cam = Cam { origin: app.graph.view.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; - assert_eq!(search.at, cam.to_graph(pointer)); - assert!(search.text.is_empty()); - } - } - } - } - - #[test] - fn search_finds_by_label_and_category() { - assert!(matches("perlin").iter().any(|d| d.id == "perlin_noise")); - assert!(matches("blur").first().is_some_and(|d| d.label.to_ascii_lowercase().starts_with("blur"))); - assert!(matches("noises cells").iter().all(|d| d.category.contains("Noises"))); - assert!(matches("zzzz").is_empty()); - } - - #[test] - fn wires_are_hit_near_their_curve_only() { - let a = (NodeId(1), "input".to_string()); - let b = (NodeId(2), "input".to_string()); - let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))]; - // The midpoint of a symmetric wire lies on the line between its ends. - let mid = bezier_at(&wires[0].1, 0.5); - assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}"); - assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a)); - assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b)); - assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None); - assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None); - // The ends are on the wire. - assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3); - assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3); - } - - #[test] - fn port_positions_stay_on_the_card() { - let n = Node::new(NodeId(1), "blend", [0.0, 0.0]); - let r = node_rect(&n, 3, 1, true); - for i in 0..3 { - let p = port_pos(r, i, 3, false, false); - assert!(r.contains(p) || (p.x - r.left()).abs() < 1e-3); - assert!(p.y > r.top() + HEADER_H && p.y < r.bottom() - FOOTER_H); - } - } - fn search_harness(render: bool) -> egui_kittest::Harness<'static, MaterialCraftApp> { - let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); - let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); - let builder = if render { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state( - |ui, app: &mut MaterialCraftApp| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }, - app, - ); - h.run_steps(10); - let pointer = h.state().graph.view.center(); - h.event(egui::Event::PointerMoved(pointer)); - h.step(); - h.key_press(egui::Key::Tab); - h.step(); - assert!(h.state().graph.search.is_some()); - h - } - - fn select_result_after_cutoff(h: &mut egui_kittest::Harness<'static, MaterialCraftApp>) -> &'static str { - for _ in 0..60 { - h.key_press(egui::Key::ArrowDown); - h.step(); - } - h.run_steps(3); // Let scroll_to_me bring the selected row into view. - let selected = h.state().graph.search.as_ref().unwrap().sel; - assert_eq!(selected, 60); - let def = matches("")[selected]; - let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); - fn visible(shape: &egui::epaint::Shape, clip: Rect, popup: Rect, label: &str) -> bool { - match shape { - egui::epaint::Shape::Text(t) => popup.contains(t.pos) && clip.contains(t.pos) && t.galley.text().trim_start().starts_with(label), - egui::epaint::Shape::Vec(v) => v.iter().any(|s| visible(s, clip, popup, label)), - _ => false, - } - } - assert!( - h.output().shapes.iter().any(|s| visible(&s.shape, s.clip_rect, popup, def.label)), - "keyboard-selected result {selected} ({}) is not visible in the popup", - def.label - ); - def.id - } - - #[test] - fn keyboard_search_selection_after_sixty_results_is_visible_and_inserts() { - let mut h = search_harness(false); - let expected = select_result_after_cutoff(&mut h); - h.key_press(egui::Key::Enter); - h.step(); - assert!(h.state().graph.search.is_none()); - let graph = h.state().session.graph().unwrap(); - assert_eq!(graph.nodes.len(), 1); - assert_eq!(graph.nodes[0].def, expected); - } - - #[test] - #[ignore = "requires an offscreen GPU"] - fn search_result_after_sixty_screenshot() { - let mut h = search_harness(true); - select_result_after_cutoff(&mut h); - let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("search-result-61.png")).unwrap(); - } -} diff --git a/_to_delete/ui_lib.test.rs b/_to_delete/ui_lib.test.rs deleted file mode 100644 index 7f30c1b..0000000 --- a/_to_delete/ui_lib.test.rs +++ /dev/null @@ -1,95 +0,0 @@ -#[cfg(test)] -mod lib_tests { - use crate::MaterialCraftApp; - use crate::cook::execute_guarded; - use crate::state::UiState; - use materialcraft_engine::sample_session; - use serde_json::json; - - #[test] - fn run_reports_errors_as_toasts_and_keeps_the_session() { - let mut app = MaterialCraftApp::headless(sample_session(), UiState::default()); - assert!(app.run("no.such.command", json!({})).is_none()); - assert!(app.toasts.iter().any(|t| t.error)); - assert!(app.run("graph.node.add", json!({"def": "levels"})).is_some()); - } - - #[test] - fn guarded_execute_returns_command_errors_as_strings() { - let mut s = sample_session(); - let e = execute_guarded(&mut s, "no.such.command", &json!({})).unwrap_err(); - assert!(!e.is_empty()); - assert!(execute_guarded(&mut s, "graph.node.add", &json!({"def": "levels"})).is_ok()); - } -} - -#[cfg(test)] -mod unsaved_state_tests { - use crate::unsaved::{Choice, Guarded, guard}; - use crate::{MaterialCraftApp, state::UiState}; - - fn app(modified: bool) -> MaterialCraftApp { - let mut s = materialcraft_engine::sample_session(); - s.modified = modified; - MaterialCraftApp::headless(s, UiState::default()) - } - - #[test] - fn closing_all_over_unsaved_work_waits_for_an_answer() { - let mut a = app(true); - let before = a.session.pkg.name.clone(); - guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); - assert!(a.ui.windows.unsaved.is_some()); - assert_eq!(a.session.pkg.name, before, "nothing was replaced yet"); - // The held action is visible as serde state (control channel `ui.inspect`). - let v = serde_json::to_value(&a.ui).unwrap(); - assert_eq!(v["windows"]["unsaved"]["kind"], "menu"); - } - - #[test] - fn closing_all_over_a_clean_package_just_happens() { - let mut a = app(false); - guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); - assert!(a.ui.windows.unsaved.is_none()); - assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("Material_Graph"), "the empty package replaced it"); - } - - #[test] - fn discard_runs_the_held_action_and_cancel_keeps_the_work() { - let mut a = app(true); - guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); - let step = crate::unsaved::answer(&mut a.ui.windows.unsaved, Choice::Cancel); - assert_eq!(step, crate::unsaved::Step::Stop); - assert!(a.session.modified); - } - - #[test] - fn a_pending_dialog_is_not_restored_from_saved_state() { - let mut a = app(true); - guard(&mut a, Guarded::Quit); - let saved = serde_json::to_string(&a.ui).unwrap(); - let back: UiState = serde_json::from_str(&saved).unwrap(); - assert!(back.windows.unsaved.is_none()); - } -} - -#[cfg(test)] -mod gesture_tests { - use crate::end_gesture_if_released; - - #[test] - fn pointer_release_ends_the_merge_run() { - let mut s = materialcraft_engine::sample_session(); - let base = s.history().len(); - let set = |s: &mut materialcraft_engine::Session| { - s.edit_merged("k", "Set parameter", |_| Ok(())).unwrap(); - }; - set(&mut s); - end_gesture_if_released(&mut s, false); - set(&mut s); - assert_eq!(s.history().len(), base + 1, "still dragging: merged"); - end_gesture_if_released(&mut s, true); - set(&mut s); - assert_eq!(s.history().len(), base + 2, "released: a new step"); - } -} diff --git a/_to_delete/ui_properties.rs b/_to_delete/ui_properties.rs deleted file mode 100644 index fc5b65c..0000000 --- a/_to_delete/ui_properties.rs +++ /dev/null @@ -1,776 +0,0 @@ -//! Properties: the selected node's base and specific parameters, or the graph's own settings, -//! inputs and outputs when no node is selected. Every change is an engine command (slider drags -//! merge into one undo step). - -use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; -use egui_phosphor::regular as icon; -use materialcraft_engine::core::{Curve, Gradient, NodeId, OutputFormat, SizeMode, Value}; -use materialcraft_engine::nodes::ParamDef; -use serde_json::{Value as J, json}; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// The panel title: "<node> - Properties" or "<graph> - Properties". -pub fn title(app: &MaterialCraftApp) -> String { - if let Some((page, _)) = &app.props3d { - return crate::view3d_props::title(*page); - } - let sel = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().map(crate::graph_view::node_label)); - let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default(); - format!("{name} - {}", tr("Properties")) -} - -fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); - let id = ui.make_persistent_id(id); - let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); - crate::widgets::name(&resp, egui::Role::Button, title); - ui.painter().rect_filled(r, 3.0, tk.row); - let chev = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT }; - ui.painter().text(r.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chev, egui::FontId::proportional(10.0), tk.text_dim); - ui.painter().text(r.left_center() + vec2(20.0, 0.0), egui::Align2::LEFT_CENTER, title.to_uppercase(), egui::FontId::proportional(10.5), tk.text_strong); - if resp.clicked() { - state.toggle(ui); - } - state.show_body_unindented(ui, |ui| { - ui.add_space(3.0); - body(ui); - ui.add_space(6.0); - }); -} - -pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - // A 3D view page stays until the user selects something else in the graph. - if let Some((page, sel)) = app.props3d.clone() { - if sel != app.session.selection { - app.props3d = None; - } else { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.push_id(("props3d", page.title()), |ui| crate::view3d_props::show(app, ui, page)); - }); - return; - } - } - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.set_width(ui.available_width()); - let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned()); - ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node { - Some(n) => node_props(app, ui, &n), - None => graph_props(app, ui), - }); - }); -} - -fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let tk = Tokens::get(ui.ctx()); - let def = materialcraft_engine::nodes::find(&n.def); - // Header: label (renamable) and description. - ui.horizontal(|ui| { - ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph_view::header_color(&n.def)); - ui.add_space(8.0); - let mut label = if n.label.is_empty() { crate::graph_view::node_label(n) } else { n.label.clone() }; - let r = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)); - crate::widgets::name(&r, egui::Role::TextInput, "Node label"); - if r.changed() { - app.run("graph.node.rename", json!({"id": n.id.0, "label": label})); - } - }); - if let Some(d) = def - && !d.description.is_empty() - { - ui.label(RichText::new(d.description).size(11.0).color(tk.text_dim)); - } - if let Some(r) = app.session.cooked.nodes.get(&n.id) - && let Some(e) = &r.error - { - ui.label(RichText::new(format!("{} {e}", icon::WARNING)).color(tk.danger)); - } - ui.add_space(4.0); - section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, n)); - if n.def == "graph_instance" { - section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, n)); - return; - } - let Some(def) = def else { return }; - if def.params.is_empty() { - return; - } - section(ui, "specific", tr("Specific parameters"), |ui| { - if n.def == "levels" { - crate::levels_editor::show(app, ui, n); - ui.add_space(6.0); - } - let exposed: Vec<(String, String)> = - app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default(); - for p in &def.params { - let cur = n.params.get(p.id).cloned().unwrap_or_else(|| p.default.clone()); - if n.functions.contains_key(p.id) { - function_row(app, ui, n.id, p.id, p.label); - continue; - } - let bound = n.bindings.get(p.id).cloned(); - param_row(app, ui, n.id, p, cur, bound, &exposed); - } - }); -} - -fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let b = &n.base; - let id = n.id.0; - let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")]; - let cur = modes.iter().find(|m| m.0 == b.size_mode).map_or("", |m| m.1); - crate::widgets::combo(ui, tr("Output size"), tr(cur), |ui| { - for (m, label) in modes { - if ui.selectable_label(b.size_mode == m, tr(label)).clicked() { - let key = match m { - SizeMode::RelativeToInput => "relativeToInput", - SizeMode::RelativeToParent => "relativeToParent", - SizeMode::Absolute => "absolute", - }; - let size = if m == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; - app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); - } - } - }); - let (lo, hi) = if b.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) }; - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut v = b.size[axis] as f32; - let caption = if b.size_mode == SizeMode::Absolute { - format!("{label} {} px", 1u32 << b.size[axis].clamp(4, 13)) - } else { - format!("{label} x {}", 2f32.powi(b.size[axis])) - }; - if crate::widgets::slider(ui, &caption, &mut v, lo..=hi, 0).changed() { - let mut size = b.size; - size[axis] = v.round() as i32; - app.run("graph.node.base", json!({"id": id, "size": size})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(b.format.label()), |ui| { - for f in OutputFormat::ALL { - if ui.selectable_label(b.format == f, tr(f.label())).clicked() { - let key = match f { - OutputFormat::Inherit => "inherit", - OutputFormat::U8 => "u8", - OutputFormat::U16 => "u16", - OutputFormat::F16 => "f16", - OutputFormat::F32 => "f32", - }; - app.run("graph.node.base", json!({"id": id, "format": key})); - } - } - }); - let mut seed = b.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64})); - } - if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { - let s = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000; - app.run("graph.node.base", json!({"id": id, "seed": s})); - } - let mut tiling = b.tiling[0] && b.tiling[1]; - if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() { - app.run("graph.node.base", json!({"id": id, "tiling": tiling})); - } -} - -fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: J) { - app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value})); -} - -fn typed(v: &Value) -> J { - serde_json::to_value(v).unwrap_or(J::Null) -} - -/// One parameter: its editor, plus the expose/bind menu. -fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef, cur: Value, bound: Option<String>, exposed: &[(String, String)]) { - let tk = Tokens::get(ui.ctx()); - if let Some(input) = &bound { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tk.accent)); - if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": J::Null})); - } - }); - return; - } - let resp_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| { - resp.context_menu(|ui| { - if ui.button(tr("Reset to default")).clicked() { - app.run("graph.node.reset", json!({"id": node.0, "param": p.id})); - ui.close(); - } - let dynamic = !matches!(p.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_)); - if dynamic && ui.button(tr("Set function...")).clicked() { - if app.run("graph.node.function", json!({"id": node.0, "param": p.id})).is_some() { - app.fn_editor = Some(crate::function_editor::FnEditor::new(node, &format!("fn:{}", p.id))); - } - ui.close(); - } - if ui.button(tr("Expose as graph input")).clicked() { - app.run("graph.exposed.add", json!({"id": p.id, "label": p.label, "bind": {"node": node.0, "param": p.id}})); - ui.close(); - } - if !exposed.is_empty() { - ui.menu_button(tr("Bind to input"), |ui| { - for (id, label) in exposed { - if ui.button(label).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": id})); - ui.close(); - } - } - }); - } - }); - }; - match cur { - Value::Float(mut v) => { - if p.angle { - let mut deg = v * 360.0; - let r = crate::widgets::slider(ui, tr(p.label), &mut deg, -360.0..=360.0, 1); - if r.changed() { - v = deg / 360.0; - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } else { - let (lo, hi) = (p.min.min(v), p.max.max(v)); - let r = crate::widgets::slider(ui, tr(p.label), &mut v, lo..=hi, if hi - lo > 20.0 { 1 } else { 3 }); - if r.changed() { - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } - } - Value::Int(i) => { - let mut v = i as f32; - let range = p.min.min(v)..=p.max.max(v); - let r = crate::widgets::slider(ui, tr(p.label), &mut v, range, 0); - if r.changed() && v.round() as i32 != i { - set(app, node, p.id, json!(v.round() as i32)); - } - resp_menu(app, &r); - } - Value::Float2(v) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - let mut nv = v; - for (k, axis) in ["X", "Y"].iter().enumerate() { - let range = p.min.min(nv[k])..=p.max.max(nv[k]); - let r = crate::widgets::slider(ui, axis, &mut nv[k], range, 3); - if r.changed() { - set(app, node, p.id, json!(nv)); - } - resp_menu(app, &r); - } - } - Value::Int2(v) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - for k in 0..2 { - let mut f = v[k] as f32; - if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, p.min..=p.max, 0).changed() { - let mut nv = v; - nv[k] = f.round() as i32; - set(app, node, p.id, json!(nv)); - } - } - } - Value::Bool(b) => { - let mut v = b; - let r = ui.checkbox(&mut v, tr(p.label)); - if r.changed() { - set(app, node, p.id, json!(v)); - } - resp_menu(app, &r); - } - Value::Color(c) | Value::Float4(c) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut rgb = [c[0], c[1], c[2]]; - if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, p.id), &mut rgb, 90.0) { - set(app, node, p.id, json!([rgb[0], rgb[1], rgb[2], c[3]])); - } - }); - }); - } - Value::Enum(i) => { - let cur = p.options.get(i as usize).copied().unwrap_or("?"); - crate::widgets::combo(ui, tr(p.label), tr(cur), |ui| { - for (k, o) in p.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, tr(o)).clicked() { - set(app, node, p.id, json!(k)); - } - } - }); - } - Value::Text(t) if p.resource => { - let names: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect(); - crate::widgets::combo(ui, tr(p.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| { - for n in &names { - if ui.selectable_label(*n == t, n).clicked() { - set(app, node, p.id, json!(n)); - } - } - }); - if ui.button(format!("{} {}", icon::IMAGE, tr("Import bitmap..."))).clicked() { - crate::menus::invoke(app, ui.ctx(), "file.importBitmap"); - } - } - Value::Text(t) => { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - let mut s = t.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, p.label); - if r.changed() { - set(app, node, p.id, json!(s)); - } - }); - } - Value::Curve(c) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, p.id), &c) { - set(app, node, p.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>())); - } - } - Value::Gradient(g) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, p.id), &g) { - set(app, node, p.id, typed(&Value::Gradient(ng))); - } - } - Value::Function(f) => { - ui.label(RichText::new(tr(p.label)).color(tk.text)); - crate::windows::function_summary(app, ui, node, p.id, &f); - } - other => { - ui.label(format!("{}: {}", p.label, other.type_name())); - } - } -} - -/// A parameter driven by a function: its label, Edit and Remove. -fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr(label)).color(tk.text)); - ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tk.accent)); - if ui.small_button(tr("Edit")).clicked() { - app.fn_editor = Some(crate::function_editor::FnEditor::new(node, &format!("fn:{param}"))); - } - if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { - app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); - } - }); -} - -fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) { - let tk = Tokens::get(ui.ctx()); - let Some((gi, sub)) = materialcraft_engine::eval::instance_graph(&app.session.pkg, n) else { - ui.label(RichText::new(tr("The instanced graph is missing")).color(tk.danger)); - return; - }; - let exposed = sub.exposed.clone(); - if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() { - app.run("graph.open", json!({"graph": gi})); - return; - } - if exposed.is_empty() { - ui.label(RichText::new(tr("This graph exposes no inputs")).color(tk.text_dim)); - } - for e in exposed { - let cur = n.params.get(&e.id).cloned().unwrap_or_else(|| e.default.clone()); - if let Some(v) = input_editor(ui, &e, &cur) { - app.run("graph.node.param", json!({"id": n.id.0, "param": e.id, "value": v})); - } - } -} - -/// The editor for one exposed input's value; returns the new value as JSON when it changed. -fn input_editor(ui: &mut Ui, e: &materialcraft_engine::core::ExposedParam, cur: &Value) -> Option<J> { - match *cur { - Value::Float(mut f) => { - let v0 = f; - crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 3).changed().then(|| json!(f)) - } - Value::Int(i) => { - let mut f = i as f32; - let v0 = f; - crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 0).changed().then(|| json!(f.round())) - } - Value::Bool(mut b) => ui.checkbox(&mut b, &e.label).changed().then(|| json!(b)), - Value::Enum(i) => { - let mut out = None; - crate::widgets::combo(ui, &e.label, e.options.get(i as usize).cloned().unwrap_or_default(), |ui| { - for (k, o) in e.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, o).clicked() { - out = Some(json!(k)); - } - } - }); - out - } - Value::Color(c) => { - let mut rgb = [c[0], c[1], c[2]]; - let mut out = None; - ui.horizontal(|ui| { - ui.label(&e.label); - if crate::widgets::color_swatch(ui, &format!("exp-{}", e.id), &mut rgb, 80.0) { - out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]])); - } - }); - out - } - ref other => { - ui.label(format!("{}: {}", e.label, other.type_name())); - None - } - } -} - -fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let Ok(g) = app.session.graph() else { - ui.label(tr("No graph is open")); - return; - }; - let g = g.clone(); - section(ui, "graph-base", tr("Base parameters"), |ui| { - ui.horizontal(|ui| { - ui.label(tr("Name")); - let mut name = g.name.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, "Graph name"); - if r.lost_focus() && name != g.name { - app.run("graph.rename", json!({"name": name})); - } - }); - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut v = g.size[axis] as f32; - if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << g.size[axis]), &mut v, 4.0..=13.0, 0).changed() { - let mut s = g.size; - s[axis] = v.round() as u32; - app.run("graph.size", json!({"log2": s})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(g.format.label()), |ui| { - for (f, key) in [(OutputFormat::U8, "u8"), (OutputFormat::U16, "u16"), (OutputFormat::F16, "f16"), (OutputFormat::F32, "f32")] { - if ui.selectable_label(g.format == f, tr(f.label())).clicked() { - app.run("graph.format", json!({"format": key})); - } - } - }); - let mut seed = g.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.seed", json!({"seed": seed.round() as i64})); - } - }); - section(ui, "graph-attr", tr("Attributes"), |ui| { - for (key, label, cur) in [ - ("category", "Category", &g.attributes.category), - ("description", "Description", &g.attributes.description), - ("author", "Author", &g.attributes.author), - ("tags", "Tags", &g.attributes.tags), - ] { - ui.horizontal(|ui| { - ui.label(tr(label)); - let mut s = cur.clone(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); - crate::widgets::name(&r, egui::Role::TextInput, label); - if r.lost_focus() && s != *cur { - app.run("graph.attributes", json!({key: s})); - } - }); - } - }); - section(ui, "graph-inputs", tr("Input parameters"), |ui| { - if g.exposed.is_empty() { - ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tk.text_dim)); - } else { - presets_bar(app, ui, &g); - } - let mut groups: Vec<&str> = Vec::new(); - for e in &g.exposed { - if !groups.contains(&e.group.as_str()) { - groups.push(&e.group); - } - } - let mut last_group: Option<&str> = None; - let mut order: Vec<&materialcraft_engine::core::ExposedParam> = Vec::new(); - for grp in &groups { - order.extend(g.exposed.iter().filter(|e| e.group == *grp)); - } - for e in order { - if last_group != Some(e.group.as_str()) && !e.group.is_empty() { - ui.label(RichText::new(e.group.to_uppercase()).size(10.5).strong().color(tk.text_dim)); - } - last_group = Some(e.group.as_str()); - let cur = g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()); - ui.horizontal(|ui| { - if crate::widgets::icon_button(ui, icon::X, tr("Delete input"), false, 18.0).clicked() { - app.run("graph.exposed.delete", json!({"id": e.id})); - } - ui.vertical(|ui| { - if let Some(v) = input_editor(ui, e, &cur) { - app.run("graph.exposed.set", json!({"id": e.id, "value": v})); - } - }); - }); - } - }); - input_previews(app, ui, &g); - section(ui, "graph-outputs", tr("Outputs"), |ui| { - for n in g.nodes.iter().filter(|n| n.def == "output") { - let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize; - let label = format!( - "{} {} | {}", - icon::SIGN_OUT, - materialcraft_engine::nodes::atomic::USAGES.get(usage).copied().unwrap_or("Any"), - materialcraft_engine::eval::identifier(n) - ); - if ui.add(egui::Button::selectable(app.session.view2d.node == Some(n.id), label)).clicked() { - app.run("view.2d", json!({"node": n.id.0})); - } - } - }); -} - -/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such -/// as a mesh map baked in TextureCraft. -fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { - let inputs = materialcraft_engine::material_cmds::image_inputs(g); - if inputs.is_empty() { - return; - } - let resources: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect(); - section(ui, "graph-input-images", tr("Input previews"), |ui| { - for i in &inputs { - let id = &i.identifier; - let bound = g.input_images.get(id); - ui.horizontal(|ui| { - ui.label(id); - egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| { - if ui.selectable_label(bound.is_none(), tr("None")).clicked() { - app.run("graph.input.unbind", json!({"identifier": id})); - } - for r in &resources { - if ui.selectable_label(bound == Some(r), r).clicked() { - app.run("graph.input.bind", json!({"identifier": id, "resource": r})); - } - } - }); - #[cfg(not(target_arch = "wasm32"))] - if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() - && let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - { - app.run("graph.input.bind", json!({"identifier": id, "path": p.display().to_string()})); - } - }); - } - }); -} - -/// Presets: apply one, save the current inputs under a name, delete one. -fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) { - let name_id = ui.make_persistent_id("preset-name"); - let mut name: String = ui.data(|d| d.get_temp(name_id)).unwrap_or_default(); - ui.horizontal(|ui| { - let names: Vec<String> = g.presets.iter().map(|p| p.name.clone()).collect(); - let r = egui::ComboBox::from_id_salt("presets").width(110.0).selected_text(tr("Presets")).show_ui(ui, |ui| { - for n in &names { - if ui.button(n).clicked() { - app.run("graph.preset.apply", json!({"name": n})); - } - } - if names.is_empty() { - ui.label(tr("No presets yet")); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Presets"); - let t = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tr("Preset name")).desired_width(90.0)); - crate::widgets::name(&t, egui::Role::TextInput, "Preset name"); - if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save preset"), false, 20.0).clicked() && !name.trim().is_empty() { - app.run("graph.preset.save", json!({"name": name})); - } - if crate::widgets::icon_button(ui, icon::X, tr("Delete preset"), false, 20.0).clicked() && !name.trim().is_empty() { - app.run("graph.preset.delete", json!({"name": name})); - } - }); - ui.data_mut(|d| d.insert_temp(name_id, name)); -} - -/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it. -/// Returns the new curve when it changed. -pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> { - let tk = Tokens::get(ui.ctx()); - let w = ui.available_width().min(240.0); - let (rect, resp) = ui.allocate_exact_size(vec2(w, w * 0.75), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Curve editor"); - let p = ui.painter_at(rect); - p.rect_filled(rect, 4.0, tk.field); - for i in 1..4 { - let t = i as f32 / 4.0; - p.line_segment([pos2(rect.left() + rect.width() * t, rect.top()), pos2(rect.left() + rect.width() * t, rect.bottom())], Stroke::new(1.0, tk.separator)); - p.line_segment([pos2(rect.left(), rect.top() + rect.height() * t), pos2(rect.right(), rect.top() + rect.height() * t)], Stroke::new(1.0, tk.separator)); - } - let to_s = |x: f32, y: f32| pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height()); - let from_s = |s: Pos2| (((s.x - rect.left()) / rect.width()).clamp(0.0, 1.0), ((rect.bottom() - s.y) / rect.height()).clamp(0.0, 1.0)); - let pts: Vec<Pos2> = (0..=64).map(|i| i as f32 / 64.0).map(|x| to_s(x, c.eval(x).clamp(0.0, 1.0))).collect(); - p.add(egui::Shape::line(pts, Stroke::new(2.0, tk.accent))); - let drag_id = ui.make_persistent_id(id).with("drag"); - let mut dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id)); - let pointer = resp.interact_pointer_pos().or(resp.hover_pos()); - let nearest = pointer.and_then(|q| { - c.points - .iter() - .enumerate() - .map(|(i, pt)| (i, to_s(pt.x, pt.y).distance(q))) - .filter(|(_, d)| *d < 10.0) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(i, _)| i) - }); - for (i, pt) in c.points.iter().enumerate() { - let hot = Some(i) == nearest || Some(i) == dragging; - p.circle(to_s(pt.x, pt.y), if hot { 5.0 } else { 4.0 }, tk.panel, Stroke::new(1.5, if hot { tk.text_strong } else { tk.text })); - } - let mut out: Option<Curve> = None; - if resp.drag_started() { - dragging = nearest; - } - if resp.dragged() - && let (Some(i), Some(q)) = (dragging, pointer) - { - let (x, y) = from_s(q); - let mut nc = c.clone(); - let last = nc.points.len().saturating_sub(1); - if let Some(pt) = nc.points.get_mut(i) { - // End points keep their x. - if i != 0 && i != last { - pt.x = x; - } - pt.y = y; - } - nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); - out = Some(nc); - } - if resp.drag_stopped() { - dragging = None; - } - ui.data_mut(|d| d.insert_temp(drag_id, dragging)); - if resp.double_clicked() - && let Some(q) = pointer - { - let (x, _) = from_s(q); - let mut nc = c.clone(); - nc.points.push(materialcraft_engine::core::CurvePoint { x, y: c.eval(x) }); - nc.points.sort_by(|a, b| a.x.total_cmp(&b.x)); - out = Some(nc); - } - if resp.secondary_clicked() - && let Some(i) = nearest - && i != 0 - && i + 1 != c.points.len() - { - let mut nc = c.clone(); - nc.points.remove(i); - out = Some(nc); - } - out -} - -/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a -/// key's color, right-click a key to remove it. -pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option<Gradient> { - let tk = Tokens::get(ui.ctx()); - let w = ui.available_width().min(260.0); - let (rect, resp) = ui.allocate_exact_size(vec2(w, 30.0), Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Canvas, "Gradient editor"); - let p = ui.painter_at(rect.expand(6.0)); - let bar = Rect::from_min_size(rect.min, vec2(w, 18.0)); - let n = 64; - for i in 0..n { - let t0 = i as f32 / n as f32; - let c = g.eval(t0 + 0.5 / n as f32); - let q = |v: f32| (materialcraft_engine::image::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0) as u8; - let r = Rect::from_min_max(pos2(bar.left() + bar.width() * t0, bar.top()), pos2(bar.left() + bar.width() * (t0 + 1.0 / n as f32) + 0.5, bar.bottom())); - p.rect_filled(r, 0.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); - } - p.rect_stroke(bar, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let sel_id = ui.make_persistent_id(id).with("sel"); - let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0); - let key_x = |pos: f32| bar.left() + pos * bar.width(); - let pointer = resp.interact_pointer_pos().or(resp.hover_pos()); - let nearest = pointer.and_then(|q| { - g.keys.iter().enumerate().map(|(i, k)| (i, (key_x(k.pos) - q.x).abs())).filter(|(_, d)| *d < 7.0).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) - }); - for (i, k) in g.keys.iter().enumerate() { - let x = key_x(k.pos); - let tri = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 10.0), pos2(x + 5.0, bar.bottom() + 10.0)]; - p.add(egui::Shape::convex_polygon(tri, if i == sel { tk.accent } else { tk.text }, Stroke::NONE)); - } - let mut out: Option<Gradient> = None; - if resp.drag_started() - && let Some(i) = nearest - { - sel = i; - } - if resp.dragged() - && let Some(q) = pointer - && nearest.is_some() - { - let mut ng = g.clone(); - if let Some(k) = ng.keys.get_mut(sel) { - k.pos = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); - } - let moved = ng.keys.get(sel).copied(); - ng.sort(); - if let Some(m) = moved { - sel = ng.keys.iter().position(|k| k.pos == m.pos && k.color == m.color).unwrap_or(sel); - } - out = Some(ng); - } - if resp.clicked() - && let Some(q) = pointer - { - match nearest { - Some(i) => sel = i, - None => { - let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0); - let mut ng = g.clone(); - ng.keys.push(materialcraft_engine::core::GradientKey { pos: t, color: g.eval(t) }); - ng.sort(); - sel = ng.keys.iter().position(|k| k.pos == t).unwrap_or(0); - out = Some(ng); - } - } - } - if resp.secondary_clicked() - && let Some(i) = nearest - && g.keys.len() > 1 - { - let mut ng = g.clone(); - ng.keys.remove(i); - sel = 0; - out = Some(ng); - } - ui.data_mut(|d| d.insert_temp(sel_id, sel)); - if let Some(k) = g.keys.get(sel) { - ui.horizontal(|ui| { - ui.label(RichText::new(format!("{} {:.2}", tr("Key at"), k.pos)).size(11.0).color(tk.text_dim)); - let mut rgb = [k.color[0], k.color[1], k.color[2]]; - if crate::widgets::color_swatch(ui, &format!("{id}-key"), &mut rgb, 60.0) { - let mut ng = out.clone().unwrap_or_else(|| g.clone()); - if let Some(kk) = ng.keys.get_mut(sel) { - kk.color = [rgb[0], rgb[1], rgb[2], kk.color[3]]; - } - out = Some(ng); - } - }); - } - out -} diff --git a/_to_delete/ui_state.rs b/_to_delete/ui_state.rs deleted file mode 100644 index b6be94a..0000000 --- a/_to_delete/ui_state.rs +++ /dev/null @@ -1,330 +0,0 @@ -//! UI state: serde data, so the control channel can read and drive it and eframe persists it. - -use serde::{Deserialize, Serialize}; - -use materialcraft_engine::CameraPrefs; - -use crate::docking::Dock; -use crate::theme::{Accent, Brightness}; - -/// Preferences (Edit ▸ Preferences). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Prefs { - /// UI language code (`i18n::LANGUAGES`). - pub language: String, - pub brightness: Brightness, - pub accent: Accent, - pub ui_scale: f32, - /// Largest node output while editing (0 = full size). - pub preview_size: u32, - /// Minutes between autosaves of a modified package (0 = off). - pub autosave_minutes: u32, - /// Show node thumbnails in the graph. - pub thumbnails: bool, - /// Library tiles: large icons or a list. - pub library_list: bool, - /// Library tile size (icons view), 56..160 px. - pub library_tile: f32, - /// Open the home screen when the app starts. - pub show_home: bool, - /// 3D view camera: pan limit and speed. - pub camera: CameraPrefs, - /// Show the main toolbar under the menu bar (Windows ▸ Main toolbar). - pub show_main_toolbar: bool, - /// Worker threads the cook may use (Tools ▸ Switch engine; 0 = every core). - pub cook_threads: usize, - /// Graph toolbar: show each node's cook time. - pub node_timings: bool, - /// Graph toolbar: straight wires instead of curves. - pub straight_wires: bool, - /// Graph toolbar: dropped nodes land on the grid. - pub snap_grid: bool, - /// Graph toolbar: draw the background grid. - pub show_grid: bool, - /// General: how many recent packages the File menu keeps. - pub recent_count: u32, - /// General: undo steps kept. - pub history_size: u32, - /// General: wheel zooms the other way in every view. - pub invert_zoom: bool, - /// General: where file dialogs open: `last`, `package` or `custom` (`save_path`). - pub save_path_mode: String, - pub save_path: String, - /// General: the auto-backup folder (empty = Documents/MaterialCraft/autosave). - pub temp_dir: String, - /// General: the cooked image cache's size in MB (0 = automatic). - pub cache_mb: u32, - /// General: auto-backup versions kept per package. - pub backup_versions: u32, - /// General: cap on every cook's larger side in px (0 = none). - pub cook_limit: u32, - /// Projects: lights on in a new session when no default 3D state is saved (ambient, point 1, point 2). - pub default_lights: [bool; 3], - /// Graph: Tab opens the node search. - pub tab_key_menu: bool, - /// Graph: dragging a wire into empty space opens the node search. - pub drag_create: bool, - /// Graph: show the 3D view when a graph opens. - pub view_3d_on_open: bool, - /// Graph: show the graph's output in the 2D view when it opens. - pub view_2d_on_open: bool, - /// Graph: show a newly added node in the 2D view. - pub auto_display_new_node: bool, - /// Graph: insert a conversion node when a color wire meets a grayscale input (or the reverse). - pub auto_convert: bool, - /// 3D view: the environment is hidden behind the mesh by default. - pub env_hidden: bool, - /// 3D view: default viewport render scale (0 = auto). - pub viewport_scale: f32, - /// 3D view: default samples per pixel of the resting frame (n × n). - pub sample_count: u32, - /// Bakers: worker threads (0 = every core). - pub bake_threads: u32, -} - -impl Default for Prefs { - fn default() -> Self { - Prefs { - language: crate::i18n::os_language().into(), - brightness: Brightness::default(), - accent: Accent::default(), - ui_scale: 1.0, - preview_size: 512, - autosave_minutes: 5, - thumbnails: true, - library_list: false, - library_tile: 78.0, - show_home: true, - camera: CameraPrefs::default(), - show_main_toolbar: true, - cook_threads: 0, - node_timings: false, - straight_wires: false, - snap_grid: false, - show_grid: true, - recent_count: 12, - history_size: 200, - invert_zoom: false, - save_path_mode: "last".into(), - save_path: String::new(), - temp_dir: String::new(), - cache_mb: 0, - backup_versions: 6, - cook_limit: 8192, - default_lights: [true, false, false], - tab_key_menu: true, - drag_create: true, - view_3d_on_open: true, - view_2d_on_open: true, - auto_display_new_node: true, - auto_convert: false, - env_hidden: true, - viewport_scale: 0.0, - sample_count: 2, - bake_threads: 0, - } - } -} - -/// Which dialogs are open. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Windows { - pub new_graph: bool, - pub export: bool, - pub about: bool, - pub preferences: bool, - pub shortcuts: bool, - pub home: bool, - pub plugin_manager: bool, - pub switch_engine: bool, - /// The Dependency Manager window (Windows menu). - pub dependencies: bool, - /// The action waiting on the "unsaved changes" dialog (readable over the control channel; - /// never restored from a saved layout). - #[serde(skip_deserializing)] - pub unsaved: Option<crate::unsaved::Guarded>, -} - -/// The graph view's camera: the graph point at the view's top-left corner, and the zoom. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct GraphCamera { - pub pan: [f32; 2], - pub zoom: f32, -} - -impl GraphCamera { - pub const ZOOM: (f32, f32) = (0.08, 4.0); - - /// The camera with a finite pan and a zoom inside [`Self::ZOOM`] (state set from outside can - /// hold a zoom of 0 or NaN, which the view divides by). - pub fn sanitized(self) -> GraphCamera { - let d = GraphCamera::default(); - let pan = |v: f32, d: f32| if v.is_finite() { v.clamp(-1.0e9, 1.0e9) } else { d }; - let zoom = if self.zoom.is_finite() { self.zoom.clamp(Self::ZOOM.0, Self::ZOOM.1) } else { d.zoom }; - GraphCamera { pan: [pan(self.pan[0], d.pan[0]), pan(self.pan[1], d.pan[1])], zoom } - } -} - -impl Default for GraphCamera { - fn default() -> Self { - GraphCamera { pan: [-60.0, -60.0], zoom: 0.8 } - } -} - -/// The 2D view's camera: image zoom (1 = one image pixel per point) and center offset. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImageCamera { - pub zoom: f32, - pub offset: [f32; 2], - /// Fit the image to the view (until the user zooms). - pub fit: bool, -} - -impl ImageCamera { - pub const ZOOM: (f32, f32) = (0.02, 64.0); - - /// The camera with a finite offset and a zoom inside [`Self::ZOOM`]. - pub fn sanitized(self) -> ImageCamera { - let off = |v: f32| if v.is_finite() { v.clamp(-1.0e9, 1.0e9) } else { 0.0 }; - let zoom = if self.zoom.is_finite() { self.zoom.clamp(Self::ZOOM.0, Self::ZOOM.1) } else { 1.0 }; - ImageCamera { zoom, offset: [off(self.offset[0]), off(self.offset[1])], fit: self.fit } - } -} - -impl Default for ImageCamera { - fn default() -> Self { - ImageCamera { zoom: 1.0, offset: [0.0, 0.0], fit: true } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct UiState { - pub dock: Dock, - pub prefs: Prefs, - pub windows: Windows, - pub graph_camera: GraphCamera, - pub image_camera: ImageCamera, - /// Library: the selected category path ("" = all) and the search text. - pub library_category: String, - pub library_search: String, - /// Library entries starred by the user (node ids, `@graph`, `fn:op`). - pub library_favorites: Vec<String>, - /// Library tree groups that are folded shut. - pub library_collapsed: Vec<String>, - /// Recently opened or saved packages, newest first. - pub recent: Vec<String>, - /// Plugins (file or folder paths in the plugins folder) whose graphs the library offers. - pub plugins_loaded: Vec<String>, - /// 3D view ▸ Scene ▸ Save Current State As Default: the state new sessions and Reset Scene use. - pub view3d_default: Option<serde_json::Value>, - /// The folder the last file dialog ended in (Preferences ▸ Save/Export path: Last path). - pub last_dir: String, - /// Preferences ▸ Shortcuts: node creation shortcuts, def id → shortcut ("Ctrl+Shift+B"). - pub node_shortcuts: Vec<(String, String)>, - /// New graph dialog fields. - pub new_graph_template: String, - pub new_graph_name: String, - pub new_graph_size: u32, - /// New graph height when the two sizes are unlinked (0 = same as the width). - pub new_graph_height: u32, - /// Keep width and height the same in the new graph dialog. - pub new_graph_link: bool, - /// Template category shown in the new graph dialog (empty = all). - pub new_graph_category: String, - /// Graph toolbar: the parent size's width and height change together. - pub parent_link: bool, - /// Graph toolbar: the align buttons also stack the nodes (no gaps). - pub stack_align: bool, - /// Export dialog fields. - pub export_dir: String, - pub export_format: String, - pub export_depth: u32, - /// Export size in pixels; 0 = the graph's own size. - pub export_size: u32, - pub export_pattern: String, - /// Frame the whole graph on the next frame. - #[serde(skip)] - pub frame_all: bool, -} - -impl Default for UiState { - fn default() -> Self { - UiState { - dock: Dock::default(), - prefs: Prefs::default(), - windows: Windows::default(), - graph_camera: GraphCamera::default(), - image_camera: ImageCamera::default(), - library_category: String::new(), - library_search: String::new(), - library_favorites: Vec::new(), - library_collapsed: Vec::new(), - recent: Vec::new(), - plugins_loaded: Vec::new(), - view3d_default: None, - last_dir: String::new(), - node_shortcuts: Vec::new(), - new_graph_template: "pbr".into(), - new_graph_name: "Material_Graph".into(), - new_graph_size: 1024, - new_graph_height: 0, - new_graph_link: true, - new_graph_category: String::new(), - parent_link: true, - stack_align: true, - export_dir: String::new(), - export_format: "png".into(), - export_depth: 0, - export_size: 0, - export_pattern: "$(graph)_$(identifier)".into(), - frame_all: true, - } - } -} - -impl UiState { - /// Remember `path` at the top of the recent list. - pub fn add_recent(&mut self, path: &str) { - self.recent.retain(|p| p != path); - self.recent.insert(0, path.to_string()); - self.recent.truncate(self.prefs.recent_count.clamp(1, 50) as usize); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn cameras_bound_huge_finite_offsets_before_screen_math() { - let g = GraphCamera { pan: [f32::MAX, f32::MIN], zoom: 4.0 }.sanitized(); - assert!(g.pan.iter().all(|v| (v * g.zoom).is_finite() && v.abs() <= 1.0e9)); - let i = ImageCamera { offset: [f32::MAX, f32::MIN], zoom: 64.0, fit: false }.sanitized(); - assert!(i.offset.iter().all(|v| (v * i.zoom).is_finite() && v.abs() <= 1.0e9)); - } - - #[test] - fn cameras_sanitize_zero_and_non_finite_zoom() { - let g = GraphCamera { pan: [f32::NAN, 5.0], zoom: 0.0 }.sanitized(); - assert_eq!(g.zoom, GraphCamera::ZOOM.0); - assert!(g.pan[0].is_finite() && g.pan[1] == 5.0); - assert_eq!(GraphCamera { pan: [0.0; 2], zoom: f32::NAN }.sanitized().zoom, GraphCamera::default().zoom); - assert_eq!(ImageCamera { zoom: -3.0, offset: [f32::INFINITY, 1.0], fit: false }.sanitized().zoom, ImageCamera::ZOOM.0); - assert_eq!(ImageCamera { zoom: 1e9, offset: [0.0; 2], fit: false }.sanitized().zoom, ImageCamera::ZOOM.1); - } - - #[test] - fn camera_prefs_persist_and_default_when_missing() { - // Preferences saved before the camera settings existed still load, with the defaults. - let old: Prefs = serde_json::from_value(serde_json::json!({"uiScale": 1.25})).unwrap(); - assert_eq!(old.camera, CameraPrefs::default()); - assert_eq!(old.ui_scale, 1.25); - let p = Prefs { camera: CameraPrefs { pan_limit: 8.0, pan_speed: 0.5 }, ..Prefs::default() }; - let v = serde_json::to_value(&p).unwrap(); - assert_eq!(v["camera"], serde_json::json!({"panLimit": 8.0, "panSpeed": 0.5})); - assert_eq!(serde_json::from_value::<Prefs>(v).unwrap(), p); - } -} diff --git a/_to_delete/ui_tests_common_search.rs b/_to_delete/ui_tests_common_search.rs deleted file mode 100644 index 63735d7..0000000 --- a/_to_delete/ui_tests_common_search.rs +++ /dev/null @@ -1,40 +0,0 @@ -use egui::{Event, Pos2, Rect, epaint::Shape, vec2}; -use egui_kittest::Harness; -use materialcraft_ui_egui::{MaterialCraftApp, UiState}; - -pub fn harness(render: bool) -> Harness<'static, MaterialCraftApp> { - let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); - let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); - let builder = if render { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state( - |ui, app: &mut MaterialCraftApp| { - app.step(&ui.ctx().clone()); - app.draw(ui); - }, - app, - ); - h.run_steps(8); - let pointer = h.state().graph.view.center(); - h.event(Event::PointerMoved(pointer)); - h.step(); - h.key_press(egui::Key::Tab); - h.step(); - h.run_steps(3); - assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).is_some()); - assert!(label_position(&h, "Bitmap").is_some(), "fresh search must show its first result"); - h -} - -pub fn label_position(h: &Harness<'static, MaterialCraftApp>, label: &str) -> Option<Pos2> { - let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); - fn find(shape: &Shape, clip: Rect, popup: Rect, label: &str) -> Option<Pos2> { - match shape { - Shape::Text(t) if clip.contains(t.pos) && popup.contains(t.pos) && t.galley.text().trim() == label => { - Some(t.pos + vec2(0.0, t.galley.size().y * 0.5)) - } - Shape::Vec(v) => v.iter().find_map(|s| find(s, clip, popup, label)), - _ => None, - } - } - h.output().shapes.iter().find_map(|s| find(&s.shape, s.clip_rect, popup, label)) -} diff --git a/_to_delete/ui_tests_search_query.rs b/_to_delete/ui_tests_search_query.rs deleted file mode 100644 index 3e9ea10..0000000 --- a/_to_delete/ui_tests_search_query.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! Resetting the search selection must also reveal it in a previously scrolled list. -#[path = "common/search.rs"] -mod search; -use egui::{Event, Key, Modifiers}; -use egui_kittest::{Harness, kittest::Queryable}; -use materialcraft_ui_egui::MaterialCraftApp; - -fn scroll(h: &mut Harness<'static, MaterialCraftApp>, rows: usize) { - for _ in 0..rows { - h.key_press(Key::ArrowDown); - h.step(); - } - h.run_steps(25); -} -fn filter_after_scrolling(h: &mut Harness<'static, MaterialCraftApp>) { - scroll(h, 45); - h.event(Event::Text("noises".into())); - h.step(); - h.run_steps(25); - assert!(search::label_position(h, "Anisotropic Noise").is_some(), "selected first filtered result is offscreen"); -} -fn assert_inserted(h: &mut Harness<'static, MaterialCraftApp>, def: &str) { - h.key_press(Key::Enter); - h.step(); - let g = h.state().session.graph().unwrap(); - assert_eq!(g.nodes.len(), 1); - assert_eq!(g.nodes[0].def, def); -} -#[test] -fn filtering_after_scrolling_reveals_and_inserts_first_match() { - let mut h = search::harness(false); - filter_after_scrolling(&mut h); - assert_inserted(&mut h, "anisotropic_noise"); -} -#[test] -fn clearing_a_scrolled_query_reveals_and_inserts_first_match() { - let mut h = search::harness(false); - h.event(Event::Text("noises".into())); - h.step(); - scroll(&mut h, 15); - h.key_press_modifiers(Modifiers::COMMAND, Key::A); - h.step(); - h.key_press(Key::Backspace); - h.step(); - h.run_steps(25); - assert!(search::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after clearing"); - assert_inserted(&mut h, "bitmap"); -} -#[test] -fn reopening_a_scrolled_search_reveals_first_match() { - let mut h = search::harness(false); - scroll(&mut h, 45); - h.key_press(Key::Escape); - h.step(); - h.run_steps(3); - h.key_press(Key::Tab); - h.step(); - h.run_steps(25); - assert!(h.get_by_label("Search nodes").rect().width() > 0.0); - assert!(search::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after reopening"); - assert_inserted(&mut h, "bitmap"); -} -#[test] -#[ignore = "requires an offscreen GPU"] -fn filtered_first_result_screenshot() { - let mut h = search::harness(true); - filter_after_scrolling(&mut h); - let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("filtered-first-result.png")).unwrap(); -} diff --git a/_to_delete/ui_tests_search_rows.rs b/_to_delete/ui_tests_search_rows.rs deleted file mode 100644 index 5f25bbb..0000000 --- a/_to_delete/ui_tests_search_rows.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Clicking anywhere across a search result's row should insert that result. -#[path = "common/search.rs"] -mod search; -use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; -use egui_kittest::Harness; -use materialcraft_ui_egui::MaterialCraftApp; - -fn right_side(h: &Harness<'static, MaterialCraftApp>) -> Pos2 { - let y = search::label_position(h, "Bitmap").unwrap().y; - let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap(); - pos2(popup.right() - 24.0, y) -} -fn click(h: &mut Harness<'static, MaterialCraftApp>, pos: Pos2) { - h.event(Event::PointerMoved(pos)); - h.step(); - for pressed in [true, false] { - h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.step(); - } - h.run_steps(3); -} -#[test] -fn clicking_label_or_right_side_inserts_the_same_result() { - for right in [false, true] { - let mut h = search::harness(false); - let pos = if right { right_side(&h) } else { search::label_position(&h, "Bitmap").unwrap() + vec2(8.0, 0.0) }; - click(&mut h, pos); - let graph = h.state().session.graph().unwrap(); - assert_eq!(graph.nodes.len(), 1, "row click did not insert a node (right_side={right})"); - assert_eq!(graph.nodes[0].def, "bitmap"); - } -} -#[test] -#[ignore = "requires an offscreen GPU"] -fn full_width_result_screenshot() { - let mut h = search::harness(true); - let pos = right_side(&h); - h.event(Event::PointerMoved(pos)); - h.run_steps(3); - let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("full-width-search-result.png")).unwrap(); -} diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index 5e89276..7e1c94f 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -111,7 +111,15 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"})); return; } - Ok(LineRead::Eof) | Err(_) => 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; @@ -230,6 +238,18 @@ mod tests { 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(); diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index 37dec33..f5e691f 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -125,7 +125,7 @@ mod tests { assert_eq!(s.pkg.name, "Untitled package"); assert_eq!(s.pkg.graphs.len(), 1); let g = s.graph().unwrap(); - assert_eq!(g.name, "Material_Graph"); + assert_eq!(g.name, "New_graph"); assert!(g.nodes.is_empty()); assert!(g.connections.is_empty()); assert!(s.path.is_none()); diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 20ef258..dc30711 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -227,7 +227,7 @@ impl Headless { 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 depth = o.displacement.unwrap_or(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), diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index dae2611..bfcba6b 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -158,11 +158,19 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st 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))?; @@ -338,6 +346,14 @@ mod tests { assert!(e.contains("disabled for automation"), "{e}"); } + #[test] + fn render_displacement_applies_without_hq() { + let h = session(); + let flat = call(&h, "render", json!({"width": 32, "height": 32, "displacement": 0.0})).unwrap(); + let strong = call(&h, "render", json!({"width": 32, "height": 32, "displacement": 0.5})).unwrap(); + assert_ne!(flat["png"], strong["png"], "displacement must change the 3D relief without hq"); + } + #[test] fn tcp_requires_the_token() { use std::io::{BufRead, BufReader}; diff --git a/crates/core/src/resource.rs b/crates/core/src/resource.rs index 4348c8e..f754573 100644 --- a/crates/core/src/resource.rs +++ b/crates/core/src/resource.rs @@ -11,20 +11,11 @@ pub struct Resource { /// The file's bytes (stored in the zip, not in `package.json`) #[serde(skip)] pub bytes: ResourceBytes, - /// A linked resource: the file it is read from (relative to the package's folder when it - /// lies inside it), reloaded by "Reload resources". `None` = embedded in the package - #[serde(default, skip_serializing_if = "Option::is_none")] - pub link: Option<String>, } 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, link: None } - } - - /// A resource that stays on disk at `link` and is read from there - pub fn linked(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes, link: impl Into<String>) -> Resource { - Resource { name: name.into(), file: file.into(), bytes, link: Some(link.into()) } + Resource { name: name.into(), file: file.into(), bytes } } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index ff10767..08e9dd0 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -48,7 +48,6 @@ pub fn command_specs() -> &'static [CommandSpec] { SPECS.get_or_init(|| { let mut v = Vec::new(); v.extend(crate::file_cmds::specs()); - v.extend(crate::resource_cmds::specs()); v.extend(crate::atomic_sample_commands::specs()); v.extend(crate::material_cmds::specs()); v.extend(crate::edit_cmds::specs()); @@ -59,7 +58,6 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::frame_commands::specs()); v.extend(crate::function_commands::specs()); v.extend(crate::comment_commands::specs()); - v.extend(crate::pin_commands::specs()); v.extend(crate::node_cmds::specs()); v.extend(crate::node_graph_commands::specs()); v.extend(crate::pattern_graph_commands::specs()); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d65c8af..0efffef 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -16,7 +16,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> { "Graph...", ["File", "New"], Some("Ctrl+N"), - "{name?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it", + "{name?, kind? (material|function), template? (see graph.templates), size? (default 1024), width?, height?} adds and opens a graph; material dimensions override size per axis, rounded down to powers of two in 16..8192 px", always, new_graph ), @@ -69,7 +69,8 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> { TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1) }; let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192); - let log2 = 63 - size.leading_zeros(); + let width_log2 = graph_dimension(parameters, "width", size)?; + let height_log2 = graph_dimension(parameters, "height", size)?; let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_")); session.edit("New graph", |session| { @@ -79,7 +80,9 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> { graph.function = Some(materialcraft_core::FunctionGraph::default()); graph } else { - template(template_id, &name, log2)? + let mut graph = template(template_id, &name, width_log2)?; + graph.size = [width_log2, height_log2]; + graph }; session.pkg.graphs.push(graph); session.graph = session.pkg.graphs.len() - 1; @@ -91,9 +94,17 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> { }) } +fn graph_dimension(parameters: &J, axis: &str, default_pixels: u64) -> Result<u32> { + let pixels = match parameters.get(axis) { + Some(value) => value.as_u64().ok_or_else(|| bad("file.new", format!("`{axis}` must be a nonnegative integer in pixels")))?, + None => default_pixels, + }; + Ok(63 - pixels.clamp(16, 8192).leading_zeros()) +} + fn new_package(s: &mut Session, p: &J) -> Result<J> { let mut pkg = Package::new(strp(p, "name").unwrap_or("Untitled package")); - pkg.graphs.push(template("pbr", "Material_Graph", 10)?); + pkg.graphs.push(template("pbr", "New_graph", 10)?); replace_package(s, pkg, None); Ok(json!({"name": s.pkg.name})) } @@ -232,9 +243,7 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O } let g = pkg.graph(gi)?; let dec = s.resource_decoder(); - let mut opts = materialcraft_eval::Options::new(&dec); - opts.max_size = s.cook_limit; - let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache); + let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache); let mut out = Vec::new(); let mut names = std::collections::HashSet::new(); for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { @@ -284,6 +293,11 @@ fn export(s: &mut Session, p: &J) -> Result<J> { let (gi, ext, pattern, depth, size) = export_params(s, p)?; let files = export_outputs(s, gi, &ext, &pattern, depth, size)?; std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?; + for f in &files { + if std::path::Path::new(dir).join(&f.file).exists() { + return Err(bad("file.export", format!("duplicate export filename `{}`: use unique output identifiers or a different filename pattern", f.file))); + } + } let mut written = Vec::new(); for f in files { let path = std::path::Path::new(dir).join(&f.file); diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index 420c41b..04e49a2 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -2,7 +2,7 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{ExposedParameter, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value}; +use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value}; use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, point, strp, u64p}; use crate::{Result, Session, cmd}; @@ -13,15 +13,6 @@ pub(crate) fn specs() -> Vec<CommandSpec> { cmd!("graph.rename", "Rename graph", [], None, "{name, graph?}", has_graph, rename), cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete), cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate), - cmd!( - "graph.add", - "Add graph", - [], - None, - "{graph: a graph as JSON (edit.copy of a graph, graph.get)} adds the graph to the package under a unique name and opens it", - always, - add - ), cmd!("graph.size", "Graph size", [], None, "{width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", has_graph, size), cmd!("graph.seed", "Random seed", [], None, "{seed}", has_graph, |s, p| { let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32; @@ -40,7 +31,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> { "Expose parameter", [], None, - "{id, label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}", + "{id (optional with bind: then named after the parameter and kept unique), label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}", has_graph, exposed_add ), @@ -148,30 +139,6 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> { }) } -/// Paste a whole graph (the explorer's Copy/Paste): its JSON, renamed when the name is taken. -fn add(s: &mut Session, p: &J) -> Result<J> { - const MAX_NODES: usize = 100_000; - let v = p.get("graph").ok_or_else(|| bad("graph.add", "`graph` is required"))?; - let mut g: materialcraft_core::Graph = serde_json::from_value(v.clone()).map_err(|e| bad("graph.add", format!("not a graph: {e}")))?; - if g.nodes.len() > MAX_NODES { - return Err(bad("graph.add", format!("a graph holds at most {MAX_NODES} nodes"))); - } - if g.name.trim().is_empty() { - g.name = "Material_Graph".into(); - } - s.edit("Add graph", |s| { - g.name = s.pkg.unique_graph_name(&g.name); - let name = g.name.clone(); - s.pkg.graphs.push(g); - s.graph = s.pkg.graphs.len() - 1; - s.open_material_preview(); - s.selection.clear(); - s.annotation_selection = None; - s.view2d.node = None; - Ok(json!({"graph": s.graph, "name": name})) - }) -} - fn size(s: &mut Session, p: &J) -> Result<J> { let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros(); let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) { @@ -258,12 +225,21 @@ fn pin_delete(s: &mut Session, p: &J) -> Result<J> { } fn exposed_add(s: &mut Session, p: &J) -> Result<J> { - let id = strp(p, "id").map(str::trim).filter(|i| !i.is_empty()).ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?.to_string(); - if s.graph()?.exposed.iter().any(|e| e.id == id) { - return Err(bad("graph.exposed.add", format!("an input is already called `{id}`"))); - } // From a bound node parameter: its value, range and options become the input's let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string()))); + let id = match strp(p, "id").map(str::trim).filter(|i| !i.is_empty()) { + Some(id) => { + if s.graph()?.exposed.iter().any(|e| e.id == id) { + return Err(bad("graph.exposed.add", format!("an input is already called `{id}`"))); + } + id.to_string() + } + // Without an `id`, a bound input is named after its parameter, kept unique across nodes + None => { + let (_, param) = bind.as_ref().ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?; + unique_exposed_id(s.graph()?, param) + } + }; let mut default = Value::Float(0.5); let (mut min, mut max, mut options) = (0.0f32, 1.0f32, Vec::new()); if let Some((node, param)) = &bind { @@ -299,6 +275,15 @@ fn exposed_add(s: &mut Session, p: &J) -> Result<J> { }) } +/// An input id not used in `graph`: `base`, `base_1`, `base_2`… +fn unique_exposed_id(graph: &Graph, base: &str) -> String { + let taken = |id: &str| graph.exposed.iter().any(|e| e.id == id); + if !taken(base) { + return base.to_string(); + } + (1..).map(|i| format!("{base}_{i}")).find(|id| !taken(id)).unwrap_or_else(|| base.to_string()) +} + fn exposed_set(s: &mut Session, p: &J) -> Result<J> { let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.set", "`id` is required"))?.to_string(); let v = p.get("value").ok_or_else(|| bad("graph.exposed.set", "`value` is required"))?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 281c2eb..a2a8846 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,7 +25,6 @@ pub mod graph_grid; pub mod inspect; pub mod material_cmds; pub mod node_cmds; -pub mod resource_cmds; pub mod samples; pub mod session; mod value_input_commands; @@ -37,13 +36,10 @@ pub use session::{CameraPrefs, Session, View2d, View3d, WARNING_PREFIX}; mod clip; mod connection_commands; pub use clip::Clip; -mod view3d_settings; -pub use view3d_settings::{Camera3d, Display3d, Lights3d, Material3d, Renderer3d}; pub use materialcraft_core as core; pub use materialcraft_eval as eval; pub use materialcraft_formats as formats; -pub use materialcraft_geom as geom; pub use materialcraft_image as image; pub use materialcraft_nodes as nodes; @@ -76,7 +72,6 @@ mod frame_contents; mod function_commands; mod node_graph_commands; mod pattern_graph_commands; -mod pin_commands; mod snapshot; pub use annotation_selection::AnnotationSelection; pub use frame_contents::FrameContents; diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs index 922eeef..e4fb3f7 100644 --- a/crates/engine/src/material_cmds.rs +++ b/crates/engine/src/material_cmds.rs @@ -162,7 +162,7 @@ fn export_material(s: &mut Session, p: &J) -> Result<J> { for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() { let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?; let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?; - o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes, false)?); + o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes, !srgb_usage(id))?); } let bytes = material_bytes(s, gi, &o)?; materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?; @@ -312,4 +312,49 @@ mod tests { assert!(values_param("t", g, &json!({"values": {"no_such_input": 1}})).is_err()); assert!(values_param("t", g, &json!({})).unwrap().is_empty()); } + + #[test] + fn export_material_decodes_data_inputs_as_linear() { + #[cfg(not(target_arch = "wasm32"))] + { + use materialcraft_formats::decode; + + let mut s = crate::sample_session(); + let input = + crate::execute(&mut s, "graph.node.add", &json!({"def": "input_color", "params": {"identifier": "normal"}})).unwrap()["id"].as_u64().unwrap(); + let output = + crate::execute(&mut s, "graph.node.add", &json!({"def": "output", "params": {"usage": ComponentUsage::index("normal")}})).unwrap()["id"] + .as_u64() + .unwrap(); + crate::execute(&mut s, "graph.connect", &json!({"from": input, "to": output})).unwrap(); + + let png = encode(&Image::filled(16, 16, materialcraft_image::Kind::Color, [128.0 / 255.0; 4]), "png", Depth::U16, false).unwrap(); + let dir = std::env::temp_dir().join(format!("materialcraft-linear-input-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("normal.png"); + std::fs::write(&file, &png).unwrap(); + let input_path = file.to_str().unwrap().to_string(); + let output_path = dir.join("out.mcmat").to_str().unwrap().to_string(); + + let result = crate::execute(&mut s, "file.exportMaterial", &json!({"path": output_path, "size": 16, "inputs": {"normal": input_path}})); + assert!(result.is_ok()); + + let bytes = std::fs::read(&output_path).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + + // The material archive stores maps uncompressed; pull the normal map + // out of its local file header and decode it as linear data. + let name = b"maps/normal.png"; + let pos = bytes.windows(name.len()).position(|w| w == name).unwrap(); + let header = pos - 30; + assert_eq!(&bytes[header..header + 4], b"PK\x03\x04"); + let name_len = u16::from_le_bytes([bytes[header + 26], bytes[header + 27]]) as usize; + let extra_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize; + let compressed = u32::from_le_bytes([bytes[header + 18], bytes[header + 19], bytes[header + 20], bytes[header + 21]]) as usize; + let start = header + 30 + name_len + extra_len; + let map = &bytes[start..start + compressed]; + let decoded = decode(map, true).unwrap(); + assert!((decoded.get(0, 0, false)[0] - 128.0 / 255.0).abs() < 1e-3, "data inputs must be decoded as linear"); + } + } } diff --git a/crates/engine/src/pin_commands.rs b/crates/engine/src/pin_commands.rs deleted file mode 100644 index 00c1762..0000000 --- a/crates/engine/src/pin_commands.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! Editing a navigation pin after it was added: its name and where it sits - -use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p}; -use crate::{Result, Session, cmd}; -use serde_json::{Value as J, json}; - -pub(crate) fn specs() -> Vec<CommandSpec> { - vec![cmd!("graph.pin.edit", "Edit pin", [], None, "{id, name?, at? [x, y]}", has_graph, pin_edit)] -} - -fn pin_edit(session: &mut Session, parameters: &J) -> Result<J> { - let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.edit", "`id` is required"))?; - let name = strp(parameters, "name").map(str::trim).filter(|name| !name.is_empty()).map(str::to_string); - let at = point(parameters, "at"); - if name.is_none() && at.is_none() { - return Err(bad("graph.pin.edit", "`name` or `at` is required")); - } - let label = if at.is_some() { "Move pin" } else { "Rename pin" }; - session.edit(label, |session| { - let pin = session.graph_mut()?.pins.iter_mut().find(|pin| pin.id == id).ok_or_else(|| bad("graph.pin.edit", format!("no pin {id}")))?; - if let Some(name) = name { - pin.name = name; - } - if let Some(at) = at { - pin.pos = at; - } - Ok(json!({"id": pin.id, "name": pin.name, "at": pin.pos})) - }) -} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs deleted file mode 100644 index 62b8109..0000000 --- a/crates/engine/src/resource_cmds.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! Package resources and dependencies: linked bitmaps (read from disk, reloaded on demand), -//! resource removal, graphs imported from other package files, copies of the package with its -//! dependencies, and the session's size settings (history, cache, cooking limit) - -use serde_json::{Value as J, json}; - -use materialcraft_core::{Package, ResourceBytes, Value}; - -use crate::commands::{CommandSpec, always, bad, strp, u64p}; -use crate::{Result, Session, cmd}; - -pub(crate) fn specs() -> Vec<CommandSpec> { - vec![ - cmd!( - "file.linkBitmap", - "Link bitmap...", - ["File"], - None, - "{path, name?} adds an image file as a linked resource (read from disk, reloaded by file.reloadResources; saved as a link when the file lies in the package's folder); returns its name", - always, - link_bitmap - ), - cmd!( - "file.reloadResources", - "Reload resources", - ["File"], - None, - "{} reads every linked resource from its file again; returns the names reloaded and those whose file is missing", - always, - reload_resources - ), - cmd!( - "file.deleteResource", - "Remove resource", - [], - None, - "{name} removes a bitmap resource; the nodes that used it show an error until they get another", - always, - delete_resource - ), - cmd!( - "file.importGraph", - "Import graph...", - ["File"], - None, - "{path, graph?} copies a graph (default: the first) of another package file into this one, with the graphs it instances and the bitmaps it uses; returns the new graph's name", - always, - import_graph - ), - cmd!( - "file.packageGraphs", - "Graphs of a package file", - [], - None, - "{path} lists the graphs of a package file without opening it: [{name, kind, outputs}]", - always, - package_graphs - ), - cmd!( - "file.saveCopy", - "Save a copy as...", - ["File"], - None, - "{path} writes the package to `path` while the session keeps its own file", - always, - save_copy - ), - cmd!( - "file.exportWithDependencies", - "Export with dependencies...", - ["File"], - None, - "{dir} writes the package and copies of its linked bitmaps into `dir`, the links made relative; returns the files written", - always, - export_with_dependencies - ), - cmd!( - "session.settings", - "Session settings", - [], - None, - "{historySize? (1..10000 undo steps), cacheMb? (16..65536, the cooked image cache), cookLimit? (256..8192 px, or 0 for none: caps every cook, exports included)} sets what is given; returns all three", - always, - session_settings - ), - ] -} - -/// Read package bytes without touching the session: SBS, or a `.mcmat` material's source -pub fn load_bytes(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Package> { - if materialcraft_formats::material::is_material(bytes) { - let (_, source) = materialcraft_formats::material::read_material(bytes)?; - return Ok(materialcraft_formats::sbs::read_sbs(&source, "source.sbs", &|_| None)?.pkg); - } - Ok(materialcraft_formats::sbs::read_sbs(bytes, name, linked)?.pkg) -} - -/// Copy `graph` of `from` into the session's package: the graph, every graph it instances -/// (recursively) and the bitmap resources its nodes use. Graphs that already exist with the -/// same name are reused when identical, else the copy gets a unique name and the instances -/// that point at it follow. Returns the copied graph's name -pub fn import_graph_from(s: &mut Session, from: &Package, graph: &str) -> Result<String> { - let (_, root) = from.graph_by_name(graph).ok_or_else(|| bad("file.importGraph", format!("`{}` has no graph `{graph}`", from.name)))?; - // Walk the instance tree, deepest dependencies first so renames are known when they are used - let mut order: Vec<String> = Vec::new(); - let mut stack = vec![root.name.clone()]; - while let Some(name) = stack.pop() { - if order.contains(&name) { - continue; - } - order.push(name.clone()); - if let Some((_, g)) = from.graph_by_name(&name) { - for n in g.nodes.iter().filter(|n| n.def == "graph_instance") { - if let Some(Value::Text(t)) = n.params.get("graph") - && !order.contains(t) - { - stack.push(t.clone()); - } - } - } - } - order.reverse(); - let from = from.clone(); - let root_name = root.name.clone(); - s.edit("Import graph", |s| { - let mut renamed: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new(); - for name in &order { - let Some((_, g)) = from.graph_by_name(name) else { continue }; - let mut g = g.clone(); - for n in g.nodes.iter_mut() { - if n.def == "graph_instance" - && let Some(Value::Text(t)) = n.params.get("graph").cloned() - && let Some(new) = renamed.get(&t) - { - n.params.insert("graph".into(), Value::Text(new.clone())); - } - if let Some(Value::Text(r)) = n.params.get("resource").cloned() - && let Some(res) = from.resource(&r) - && s.pkg.resource(&r).is_none() - { - s.pkg.resources.push(res.clone()); - } - } - if let Some((_, have)) = s.pkg.graph_by_name(name) - && *have == g - { - renamed.insert(name.clone(), name.clone()); - continue; - } - let new = s.pkg.unique_graph_name(name); - g.name = new.clone(); - renamed.insert(name.clone(), new); - s.pkg.graphs.push(g); - } - Ok(renamed.get(&root_name).cloned().unwrap_or(root_name)) - }) -} - -#[cfg(not(target_arch = "wasm32"))] -fn load_file(cmd: &str, p: &J) -> Result<(String, Package)> { - let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?; - let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - Ok((path.to_string(), load_bytes(&bytes, path, &crate::file_cmds::linked_files(path))?)) -} - -#[cfg(not(target_arch = "wasm32"))] -fn import_graph(s: &mut Session, p: &J) -> Result<J> { - let (_, from) = load_file("file.importGraph", p)?; - let graph = match strp(p, "graph") { - Some(g) => g.to_string(), - None => from.graphs.first().map(|g| g.name.clone()).ok_or_else(|| bad("file.importGraph", "the package has no graphs"))?, - }; - let name = import_graph_from(s, &from, &graph)?; - Ok(json!({"name": name})) -} - -#[cfg(target_arch = "wasm32")] -fn import_graph(_: &mut Session, _: &J) -> Result<J> { - Err(bad("file.importGraph", "the browser has no package files to import from")) -} - -#[cfg(not(target_arch = "wasm32"))] -fn package_graphs(_: &mut Session, p: &J) -> Result<J> { - let (_, from) = load_file("file.packageGraphs", p)?; - Ok(json!( - from.graphs - .iter() - .map(|g| json!({"name": g.name, "kind": format!("{:?}", g.kind()), "outputs": g.nodes.iter().filter(|n| n.def == "output").count()})) - .collect::<Vec<_>>() - )) -} - -#[cfg(target_arch = "wasm32")] -fn package_graphs(_: &mut Session, _: &J) -> Result<J> { - Err(bad("file.packageGraphs", "the browser has no package files to read")) -} - -/// The path a linked file is stored under: relative to the package's folder when it lies -/// inside it (then the link survives in the saved file), else as given -#[cfg(not(target_arch = "wasm32"))] -fn link_path(s: &Session, path: &str) -> String { - let Some(folder) = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).and_then(|p| std::fs::canonicalize(p).ok()) else { - return path.to_string(); - }; - match std::fs::canonicalize(path).ok().and_then(|f| f.strip_prefix(&folder).ok().map(|r| r.to_path_buf())) { - Some(rel) => rel.to_string_lossy().replace('\\', "/"), - None => path.to_string(), - } -} - -/// Read a linked resource's file: a relative link resolves next to the package -#[cfg(not(target_arch = "wasm32"))] -fn read_link(s: &Session, link: &str) -> std::result::Result<Vec<u8>, String> { - let plain = !link.contains(':') && !link.starts_with('/') && !link.starts_with('\\'); - if plain && let Some(path) = &s.path { - return crate::file_cmds::linked_files(path)(link).ok_or_else(|| format!("`{link}` was not found next to the package")); - } - std::fs::read(link).map_err(|e| format!("{link}: {e}")) -} - -#[cfg(not(target_arch = "wasm32"))] -fn link_bitmap(s: &mut Session, p: &J) -> Result<J> { - let path = strp(p, "path").ok_or_else(|| bad("file.linkBitmap", "`path` is required"))?; - let bytes = std::fs::read(path).map_err(|e| bad("file.linkBitmap", format!("{path}: {e}")))?; - materialcraft_formats::decode(&bytes, false)?; - let file = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string(); - let link = link_path(s, path); - let wanted = strp(p, "name").map(str::to_string); - let name = s.edit("Link bitmap", |s| { - // Relinking an existing resource keeps its name (the nodes that use it stay valid) - if let Some(r) = wanted.as_deref().and_then(|w| s.pkg.resources.iter_mut().find(|r| r.name == w)) { - r.bytes = ResourceBytes::new(bytes); - r.link = Some(link.clone()); - return Ok(r.name.clone()); - } - let name = crate::file_cmds::push_resource(&mut s.pkg, &file, bytes, wanted.as_deref()); - if let Some(r) = s.pkg.resources.iter_mut().find(|r| r.name == name) { - r.link = Some(link.clone()); - } - Ok(name) - })?; - s.clear_decoded(); - Ok(json!({"name": name, "link": link, "use": {"command": "graph.node.add", "params": {"def": "bitmap", "params": {"resource": name}}}})) -} - -#[cfg(target_arch = "wasm32")] -fn link_bitmap(_: &mut Session, _: &J) -> Result<J> { - Err(bad("file.linkBitmap", "the browser has no files to link to; import the bitmap instead")) -} - -#[cfg(not(target_arch = "wasm32"))] -fn reload_resources(s: &mut Session, _: &J) -> Result<J> { - let links: Vec<(String, String)> = s.pkg.resources.iter().filter_map(|r| r.link.clone().map(|l| (r.name.clone(), l))).collect(); - let mut fresh: Vec<(String, Vec<u8>)> = Vec::new(); - let mut missing: Vec<String> = Vec::new(); - for (name, link) in links { - match read_link(s, &link) { - Ok(bytes) => fresh.push((name, bytes)), - Err(why) => { - s.log(format!("resource `{name}` not reloaded: {why}")); - missing.push(name); - } - } - } - let changed: Vec<String> = - fresh.iter().filter(|(n, b)| s.pkg.resources.iter().any(|r| &r.name == n && r.bytes.as_slice() != b.as_slice())).map(|(n, _)| n.clone()).collect(); - if !changed.is_empty() { - s.edit("Reload resources", |s| { - for (name, bytes) in fresh { - if let Some(r) = s.pkg.resources.iter_mut().find(|r| r.name == name) { - r.bytes = ResourceBytes::new(bytes); - } - } - Ok(()) - })?; - s.clear_decoded(); - } - s.dirty = true; - Ok(json!({"reloaded": changed, "missing": missing})) -} - -#[cfg(target_arch = "wasm32")] -fn reload_resources(s: &mut Session, _: &J) -> Result<J> { - s.dirty = true; - Ok(json!({"reloaded": [], "missing": []})) -} - -fn delete_resource(s: &mut Session, p: &J) -> Result<J> { - let name = strp(p, "name").ok_or_else(|| bad("file.deleteResource", "`name` is required"))?.to_string(); - if s.pkg.resource(&name).is_none() { - return Err(bad("file.deleteResource", format!("no resource `{name}`"))); - } - s.edit("Remove resource", |s| { - s.pkg.resources.retain(|r| r.name != name); - Ok(J::Null) - })?; - s.clear_decoded(); - Ok(json!({"name": name})) -} - -#[cfg(not(target_arch = "wasm32"))] -fn save_copy(s: &mut Session, p: &J) -> Result<J> { - let path = crate::file_cmds::package_path(strp(p, "path").ok_or_else(|| bad("file.saveCopy", "`path` is required"))?); - let bytes = crate::file_cmds::save_bytes(s)?; - materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?; - s.log(format!("Saved a copy to {path}")); - Ok(json!({"path": path, "bytes": bytes.len()})) -} - -#[cfg(target_arch = "wasm32")] -fn save_copy(_: &mut Session, _: &J) -> Result<J> { - Err(bad("file.saveCopy", "the browser saves with a download")) -} - -#[cfg(not(target_arch = "wasm32"))] -fn export_with_dependencies(s: &mut Session, p: &J) -> Result<J> { - let dir = strp(p, "dir").ok_or_else(|| bad("file.exportWithDependencies", "`dir` is required"))?; - let dir = std::path::Path::new(dir); - std::fs::create_dir_all(dir).map_err(|e| bad("file.exportWithDependencies", format!("{}: {e}", dir.display())))?; - let mut written: Vec<String> = Vec::new(); - // The copy links every linked bitmap by its file name, next to the package - let mut pkg = s.pkg.clone(); - let mut used: std::collections::BTreeSet<String> = std::collections::BTreeSet::new(); - for r in pkg.resources.iter_mut() { - let Some(link) = r.link.clone() else { continue }; - let bytes = match read_link(s, &link) { - Ok(b) => b, - Err(why) => { - s.log(format!("`{}` exported embedded: {why}", r.name)); - r.link = None; - continue; - } - }; - let base = std::path::Path::new(&link).file_name().and_then(|f| f.to_str()).unwrap_or(&r.file).to_string(); - let mut file = base.clone(); - let mut n = 2; - while !used.insert(file.clone()) { - file = match base.rsplit_once('.') { - Some((stem, ext)) => format!("{stem}_{n}.{ext}"), - None => format!("{base}_{n}"), - }; - n += 1; - } - let target = dir.join(&file); - materialcraft_formats::write_atomic(&target, &bytes)?; - written.push(target.display().to_string()); - r.link = Some(file); - r.bytes = ResourceBytes::new(bytes); - } - let name = format!("{}.{}", materialcraft_formats::safe_file_name(&pkg.name), materialcraft_formats::sbs::SBS_EXT); - let target = dir.join(&name); - let bytes = materialcraft_formats::sbs::write_sbs(&pkg)?; - materialcraft_formats::write_atomic(&target, &bytes)?; - written.insert(0, target.display().to_string()); - s.log(format!("Exported {} with {} dependency file(s) to {}", pkg.name, written.len() - 1, dir.display())); - Ok(json!({"files": written})) -} - -#[cfg(target_arch = "wasm32")] -fn export_with_dependencies(_: &mut Session, _: &J) -> Result<J> { - Err(bad("file.exportWithDependencies", "the browser saves with a download")) -} - -fn session_settings(s: &mut Session, p: &J) -> Result<J> { - if let Some(n) = u64p(p, "historySize") { - s.max_undo = n.clamp(1, 10_000) as usize; - s.trim_undo(); - } - if let Some(mb) = u64p(p, "cacheMb") { - let bytes = (mb.clamp(16, 65_536) as usize) << 20; - if let Ok(mut c) = s.cache.lock() { - c.set_cap(bytes); - } - } - if let Some(px) = u64p(p, "cookLimit") { - let limit = if px == 0 { None } else { Some(px.clamp(256, 8192) as u32) }; - if limit != s.cook_limit { - s.cook_limit = limit; - s.dirty = true; - } - } - let cache_mb = s.cache.lock().map(|c| c.cap() >> 20).unwrap_or(0); - Ok(json!({"historySize": s.max_undo, "cacheMb": cache_mb, "cookLimit": s.cook_limit.unwrap_or(0)})) -} diff --git a/crates/engine/src/samples.rs b/crates/engine/src/samples.rs index 3bd0f95..3531f26 100644 --- a/crates/engine/src/samples.rs +++ b/crates/engine/src/samples.rs @@ -13,9 +13,6 @@ pub fn template(id: &str, name: &str, size_log2: u32) -> Result<Graph> { graph.name = name.to_string(); graph.size = [size_log2, size_log2]; if id == "pbr" { - // Uniform colors into every output; the normal is derived from the height, so a height - // wired in shows up in the 3D view right away (as a normal map, and as relief). - let mut height_source = None; for (index, (identifier, color)) in [ ("basecolor", [0.5, 0.5, 0.5, 1.0]), ("normal", [0.5, 0.5, 1.0, 1.0]), @@ -27,32 +24,15 @@ pub fn template(id: &str, name: &str, size_log2: u32) -> Result<Graph> { .into_iter() .enumerate() { - let y = index as f32 * 180.0; - let output = graph.add_node("output", [440.0, y]); + let source = graph.add_node("uniform", [0.0, index as f32 * 180.0]); + let node = graph.node_mut(source)?; + node.params.insert("color_mode".into(), Value::Bool(index <= 1)); + node.params.insert("color".into(), Value::Color(color)); + let output = graph.add_node("output", [220.0, index as f32 * 180.0]); let node = graph.node_mut(output)?; node.params.insert("identifier".into(), Value::Text(identifier.into())); node.params.insert("usage".into(), Value::Enum(index as u32)); - if identifier == "normal" { - // Filled in below, from the height - continue; - } - let source = graph.add_node("uniform", [0.0, y]); - let node = graph.node_mut(source)?; - node.params.insert("color_mode".into(), Value::Bool(index == 0)); - node.params.insert("color".into(), Value::Color(color)); graph.connect(source, "output", output, "input")?; - if identifier == "height" { - height_source = Some(source); - } - } - let normal = graph.add_node("normal", [220.0, 180.0]); - graph.node_mut(normal)?.params.insert("intensity".into(), Value::Float(2.0)); - if let Some(height) = height_source { - graph.connect(height, "output", normal, "input")?; - } - let normal_output = graph.nodes.iter().find(|n| n.def == "output" && n.params.get("identifier") == Some(&Value::Text("normal".into()))).map(|n| n.id); - if let Some(output) = normal_output { - graph.connect(normal, "output", output, "input")?; } } Ok(graph) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 30a3b18..5ff2f67 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,11 +10,10 @@ use materialcraft_image::Image; use serde::{Deserialize, Serialize}; use crate::snapshot::Snapshot; -use crate::view3d_settings::{Camera3d, Display3d, Lights3d, Material3d, Renderer3d}; use crate::{AnnotationSelection, Clip, EngineError, Result}; -/// Undo keeps this many steps unless the session says otherwise. -pub const MAX_UNDO: usize = 200; +/// Undo keeps this many steps. +const MAX_UNDO: usize = 200; /// The 3D view's scene and look. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -45,28 +44,6 @@ pub struct View3d { pub transparency: bool, /// Show the material's alpha channel on the mesh instead of the lit material. pub alpha_view: bool, - /// Camera ▸ Edit properties. - pub camera: Camera3d, - /// Lights ▸ Edit properties. - pub lights: Lights3d, - /// Environment ▸ Edit properties: the environment lights the scene. - pub env_enabled: bool, - /// Renderer ▸ Edit settings. - pub renderer: Renderer3d, - /// Display menu toggles. - pub display: Display3d, - /// Materials ▸ Default ▸ Edit properties. - pub material: Material3d, -} - -impl View3d { - /// Every nested value brought into its range (after a command merged JSON in). - pub fn sanitize(&mut self) { - self.camera.sanitize(); - self.lights.sanitize(); - self.renderer.sanitize(); - self.material.sanitize(); - } } impl Default for View3d { @@ -88,12 +65,6 @@ impl Default for View3d { show_grid: false, transparency: true, alpha_view: false, - camera: Camera3d::default(), - lights: Lights3d::default(), - env_enabled: true, - renderer: Renderer3d::default(), - display: Display3d::default(), - material: Material3d::default(), } } } @@ -180,10 +151,6 @@ pub struct Session { pub cache: Arc<Mutex<Cache>>, /// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry. pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>, - /// Undo steps kept (Preferences ▸ History stack size). - pub max_undo: usize, - /// Cap on the larger side of every cook, previews and exports alike (Preferences ▸ Cooking size limit). - pub cook_limit: Option<u32>, undo: Vec<Snapshot>, redo: Vec<Snapshot>, /// Edits with the same key coalesce into one undo step (slider drags). @@ -217,8 +184,6 @@ impl Session { cook_epoch: 0, cache: Arc::new(Mutex::new(Cache::default())), custom_mesh: None, - max_undo: MAX_UNDO, - cook_limit: None, undo: Vec::new(), redo: Vec::new(), merge_key: None, @@ -346,7 +311,9 @@ impl Session { fn record_undo(&mut self, snapshot: Snapshot) { self.undo.push(snapshot); - self.trim_undo(); + if self.undo.len() > MAX_UNDO { + self.undo.remove(0); + } self.redo.clear(); } @@ -382,23 +349,6 @@ impl Session { self.undo.iter().map(|s| s.label.clone()).collect() } - /// Drop the oldest undo steps past `max_undo`. - pub fn trim_undo(&mut self) { - let max = self.max_undo.max(1); - if self.undo.len() > max { - let extra = self.undo.len() - max; - self.undo.drain(..extra); - } - } - - /// The preview cap and the cooking size limit, whichever is smaller. - pub fn cook_size(&self, preview: Option<u32>) -> Option<u32> { - match (preview, self.cook_limit) { - (Some(p), Some(l)) => Some(p.min(l)), - (p, l) => p.or(l), - } - } - pub fn undo(&mut self) -> Option<String> { self.end_group(); let s = self.undo.pop()?; @@ -407,7 +357,7 @@ impl Session { self.redo.push(cur); self.restore(s); self.merge_key = None; - self.changed(); + self.dirty = true; Some(label) } @@ -419,7 +369,7 @@ impl Session { self.undo.push(cur); self.restore(s); self.merge_key = None; - self.changed(); + self.dirty = true; Some(label) } @@ -459,7 +409,7 @@ impl Session { pub fn cook(&mut self) -> &Cooked { let dec = self.resource_decoder(); let mut opts = Options::new(&dec); - opts.max_size = self.cook_size(self.preview_size); + opts.max_size = self.preview_size; let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache); self.accept_preview(cooked); self.dirty = false; @@ -480,8 +430,7 @@ impl Session { /// Cook graph `gi` at full size, without touching the preview results. pub fn cook_full(&self, gi: usize) -> Cooked { let dec = self.resource_decoder(); - let mut opts = Options::new(&dec); - opts.max_size = self.cook_limit; + let opts = Options::new(&dec); materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache) } diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs index 9b64c36..d254c55 100644 --- a/crates/engine/src/session.test.rs +++ b/crates/engine/src/session.test.rs @@ -7,7 +7,7 @@ use crate::session::Session; fn normal_map_session() -> Session { let mut pkg = Package::new("T"); let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap(); - pkg.resources.push(Resource::new("n", "n.png", materialcraft_core::ResourceBytes::new(png))); + pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: materialcraft_core::ResourceBytes::new(png) }); Session::new(pkg) } diff --git a/crates/engine/src/startup.rs b/crates/engine/src/startup.rs index 94a5877..b603f1b 100644 --- a/crates/engine/src/startup.rs +++ b/crates/engine/src/startup.rs @@ -3,7 +3,7 @@ use crate::{Session, core}; /// A fresh, unsaved package with one empty graph, used at desktop and browser startup pub fn new_session() -> Session { let mut pkg = core::Package::new("Untitled package"); - pkg.graphs.push(core::Graph::new("Material_Graph")); + pkg.graphs.push(core::Graph::new("New_graph")); Session::new(pkg) } diff --git a/crates/engine/src/view3d_settings.rs b/crates/engine/src/view3d_settings.rs deleted file mode 100644 index 3888001..0000000 --- a/crates/engine/src/view3d_settings.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! The 3D view's property pages as session state: camera, lights, renderer, display toggles and -//! the material's common values. Every field is clamped by `sanitize` after a command merges JSON in. - -use serde::{Deserialize, Serialize}; - -pub use materialcraft_geom::preview::{Common, MapUse, PointLight, Shader}; - -/// The 3D view's camera properties. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Camera3d { - /// Millimetres (a 36 mm frame): 35 mm ≈ 35° vertical field of view on a 3:2 frame. - pub focal_length: f32, - /// `perspective` or `orthographic`. - pub projection: String, - /// `backdrop`, `color` or `environment`. - pub background: String, - /// Linear RGBA. - pub background_color: [f32; 4], - /// Render at a fixed resolution (Save Render) instead of the viewport's. - pub override_resolution: bool, - pub resolution: [u32; 2], - /// Multiplier on the render resolution. - pub resolution_scale: f32, - /// Clip planes from the scene size; else `near`/`far` in mesh radii from the camera. - pub auto_clip: bool, - pub near: f32, - pub far: f32, -} - -impl Default for Camera3d { - fn default() -> Self { - Camera3d { - focal_length: 35.0, - projection: "perspective".into(), - background: "backdrop".into(), - background_color: [0.016, 0.016, 0.016, 1.0], - override_resolution: false, - resolution: [1920, 1080], - resolution_scale: 1.0, - auto_clip: true, - near: 0.1, - far: 100.0, - } - } -} - -impl Camera3d { - /// Vertical field of view in degrees for the focal length (36 × 24 mm frame). - pub fn fov(&self) -> f32 { - (2.0 * (12.0 / self.focal_length.max(1.0)).atan()).to_degrees().clamp(5.0, 120.0) - } - - pub(crate) fn sanitize(&mut self) { - let d = Camera3d::default(); - let f = |v: f32, lo: f32, hi: f32, dv: f32| if v.is_finite() { v.clamp(lo, hi) } else { dv }; - self.focal_length = f(self.focal_length, 4.0, 1200.0, d.focal_length); - if !["perspective", "orthographic"].contains(&self.projection.as_str()) { - self.projection = d.projection; - } - if !["backdrop", "color", "environment"].contains(&self.background.as_str()) { - self.background = d.background; - } - for (i, v) in self.background_color.iter_mut().enumerate() { - *v = f(*v, 0.0, 1.0, d.background_color[i]); - } - self.resolution = self.resolution.map(|v| v.clamp(16, 8192)); - self.resolution_scale = f(self.resolution_scale, 0.1, 4.0, d.resolution_scale); - self.near = f(self.near, 0.001, 1000.0, d.near); - self.far = f(self.far, 0.01, 10_000.0, d.far).max(self.near * 1.01); - } -} - -/// The 3D view's lights: an ambient term and two point lights. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Lights3d { - pub ambient_on: bool, - /// Linear RGB. - pub ambient: [f32; 3], - pub point: [PointLight; 2], -} - -impl Default for Lights3d { - fn default() -> Self { - Lights3d { ambient_on: true, ambient: [0.0; 3], point: PointLight::DEFAULTS } - } -} - -impl Lights3d { - pub(crate) fn sanitize(&mut self) { - for v in self.ambient.iter_mut() { - *v = if v.is_finite() { v.clamp(0.0, 16.0) } else { 0.0 }; - } - let d = PointLight::DEFAULTS; - self.point = [self.point[0].sanitized(d[0]), self.point[1].sanitized(d[1])]; - } -} - -/// Renderer ▸ Edit settings. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Renderer3d { - pub use_viewport_resolution: bool, - pub resolution: [u32; 2], - /// Resolution scale of the viewport render (0.25..2). - pub scale: f32, - /// Supersampling of the resting frame (1..4 per axis). - pub samples: u32, - /// Ray-traced ambient occlusion rays per sample (0 = off). - pub ao_rays: u32, -} - -impl Default for Renderer3d { - fn default() -> Self { - Renderer3d { use_viewport_resolution: true, resolution: [1920, 1080], scale: 1.0, samples: 2, ao_rays: 0 } - } -} - -impl Renderer3d { - pub(crate) fn sanitize(&mut self) { - self.resolution = self.resolution.map(|v| v.clamp(16, 4096)); - self.scale = if self.scale.is_finite() { self.scale.clamp(0.25, 2.0) } else { 1.0 }; - self.samples = self.samples.clamp(1, 4); - self.ao_rays = self.ao_rays.min(64); - } -} - -/// Display menu toggles. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Display3d { - pub wireframe: bool, - pub backface_culling: bool, - pub bounding_box: bool, - /// Draw the point lights. - pub lights: bool, - /// Overlay the render resolution. - pub resolution: bool, - /// Overlay the scene statistics (triangles, maps). - pub stats: bool, - /// Overlay the frame rate. - pub fps: bool, -} - -/// Materials ▸ Default: the shading model and what each channel is without a map. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Material3d { - pub shader: Shader, - pub common: Common, - pub use_map: MapUse, - /// Displacement subdivision budget multiplier (0.1..4). - pub tessellation: f32, - /// Extra UV scale of the material on the mesh. - pub uv_scale: [f32; 2], -} - -impl Default for Material3d { - fn default() -> Self { - Material3d { shader: Shader::OpenPbr, common: Common::default(), use_map: MapUse::default(), tessellation: 1.0, uv_scale: [1.0, 1.0] } - } -} - -impl Material3d { - pub(crate) fn sanitize(&mut self) { - self.common = self.common.sanitized(); - self.tessellation = if self.tessellation.is_finite() { self.tessellation.clamp(0.1, 4.0) } else { 1.0 }; - self.uv_scale = self.uv_scale.map(|v| if v.is_finite() { v.clamp(0.01, 64.0) } else { 1.0 }); - } -} diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index d142cb7..274a88f 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -12,19 +12,14 @@ pub const SCENES: &[(&str, &str)] = &[ ("cube", "Cube"), ("cylinder", "Cylinder"), ("plane", "Plane"), - ("plane_hires", "Plane (hi-res)"), ("sphere", "Sphere"), - ("cloth", "Cloth"), ("material_ball", "Mat ball"), ("rounded_cube", "Rounded cube"), - ("rounded_cylinder", "Rounded cylinder"), - ("sphere_2_tiles", "Sphere 2 tiles"), ("torus", "Torus"), ]; /// Environments: (id, label). -pub const ENVIRONMENTS: &[(&str, &str)] = - &[("studio", "Studio"), ("contrast", "Studio contrast"), ("warehouse", "Warehouse"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")]; +pub const ENVIRONMENTS: &[(&str, &str)] = &[("studio", "Studio"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")]; pub(crate) fn specs() -> Vec<CommandSpec> { vec![ @@ -34,24 +29,15 @@ pub(crate) fn specs() -> Vec<CommandSpec> { "3D view settings", [], None, - "{scene? (cube|cylinder|plane|plane_hires|sphere|cloth|material_ball|rounded_cube|rounded_cylinder|sphere_2_tiles|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night|contrast|warehouse), envRotation?, exposure?, envEnabled?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel), camera? ({focalLength, projection, background, backgroundColor, overrideResolution, resolution, resolutionScale, autoClip, near, far}: the keys given change), lights? ({ambientOn, ambient, point: [{on, color, intensity, position}, …]}), renderer? ({useViewportResolution, resolution, scale, samples, aoRays}), display? ({wireframe, backfaceCulling, boundingBox, lights, resolution, stats, fps}), material? ({shader, common: {…}, useMap: {…}, tessellation, uvScale})} returns the whole 3D view state", + "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", always, view3d ), cmd!("view.3d.loadMesh", "Load mesh...", [], None, "{path} shows an OBJ, glTF or GLB mesh in the 3D view (scene \"custom\")", always, load_mesh), - cmd!("view.3d.reset", "Reset scene", [], None, "{what?: all|scene|camera|lights|environment|material|renderer|display} (default all)", always, reset3d), - cmd!("view.3d.state", "3D view state", [], None, "{} the whole 3D view state as JSON (Scene ▸ Save current state)", always, |s, _| Ok( - serde_json::to_value(&s.view3d).unwrap_or(J::Null) - )), - cmd!( - "view.3d.loadState", - "Load 3D view state", - [], - None, - "{state: JSON from view.3d.state, keepScene?: bool} restores the 3D view", - always, - load_state - ), + cmd!("view.3d.reset", "Reset scene", [], None, "{}", always, |s, _| { + s.view3d = crate::View3d::default(); + Ok(J::Null) + }), cmd!("view.previewSize", "Preview size", [], None, "{size: 64..8192, or 0 for full size} caps node outputs while editing", always, preview_size), cmd!( "library.list", @@ -100,102 +86,6 @@ fn view2d(s: &mut Session, p: &J) -> Result<J> { Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null)) } -/// Overlay `patch` on `base`: objects merge key by key, arrays element by element (a shorter -/// patch leaves the rest), a `null` leaves the value alone, anything else replaces. -fn merge_json(base: &mut J, patch: &J) { - match (base, patch) { - (_, J::Null) => {} - (J::Object(b), J::Object(p)) => { - for (k, v) in p { - match b.get_mut(k) { - Some(slot) => merge_json(slot, v), - None => { - b.insert(k.clone(), v.clone()); - } - } - } - } - (J::Array(b), J::Array(p)) => { - for (i, v) in p.iter().enumerate() { - match b.get_mut(i) { - Some(slot) => merge_json(slot, v), - None => b.push(v.clone()), - } - } - } - (b, p) => *b = p.clone(), - } -} - -/// Merge a nested object of the `view.3d` request into one of the view's sub-structs. -fn merge_into<T: serde::Serialize + serde::de::DeserializeOwned>(key: &str, current: &T, patch: &J) -> Result<T> { - if !patch.is_object() { - return Err(bad("view.3d", format!("`{key}` is an object"))); - } - let mut v = serde_json::to_value(current).map_err(|e| bad("view.3d", e.to_string()))?; - merge_json(&mut v, patch); - serde_json::from_value(v).map_err(|e| bad("view.3d", format!("`{key}`: {e}"))) -} - -fn reset3d(s: &mut Session, p: &J) -> Result<J> { - let d = crate::View3d::default(); - let v = &mut s.view3d; - match strp(p, "what").unwrap_or("all") { - "all" => *v = d, - "scene" => { - v.scene = d.scene; - v.tiling = d.tiling; - v.height_scale = d.height_scale; - v.height_level = d.height_level; - } - "camera" => { - v.yaw = d.yaw; - v.pitch = d.pitch; - v.distance = d.distance; - v.target = d.target; - v.camera = d.camera; - } - "lights" => v.lights = d.lights, - "environment" => { - v.environment = d.environment; - v.env_rotation = d.env_rotation; - v.exposure = d.exposure; - v.env_enabled = d.env_enabled; - } - "material" => v.material = d.material, - "renderer" => v.renderer = d.renderer, - "display" => v.display = d.display, - other => return Err(bad("view.3d.reset", format!("unknown `what` `{other}`"))), - } - Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null)) -} - -fn load_state(s: &mut Session, p: &J) -> Result<J> { - let state = p.get("state").ok_or_else(|| bad("view.3d.loadState", "`state` is required"))?; - let mut v: crate::View3d = merge_into("state", &crate::View3d::default(), state)?; - v.sanitize(); - if !SCENES.iter().any(|(id, _)| *id == v.scene) && !(v.scene == "custom" && s.custom_mesh.is_some()) { - v.scene = crate::View3d::default().scene; - } - if !ENVIRONMENTS.iter().any(|(id, _)| *id == v.environment) { - v.environment = crate::View3d::default().environment; - } - if boolp(p, "keepScene").unwrap_or(false) { - v.scene = s.view3d.scene.clone(); - } - v.target = s.camera.clamp_target(v.target); - v.yaw = if v.yaw.is_finite() { v.yaw.rem_euclid(360.0) } else { 0.0 }; - v.pitch = if v.pitch.is_finite() { v.pitch.clamp(-89.0, 89.0) } else { 0.0 }; - v.distance = if v.distance.is_finite() { v.distance.clamp(1.2, 20.0) } else { 3.2 }; - v.tiling = if v.tiling.is_finite() { v.tiling.clamp(0.1, 64.0) } else { 1.0 }; - v.exposure = if v.exposure.is_finite() { v.exposure.clamp(-10.0, 10.0) } else { 0.0 }; - v.env_rotation = if v.env_rotation.is_finite() { v.env_rotation.rem_euclid(360.0) } else { 0.0 }; - v.height_scale = if v.height_scale.is_finite() { v.height_scale.clamp(0.0, 0.5) } else { 0.0 }; - v.height_level = if v.height_level.is_finite() { v.height_level.clamp(0.0, 1.0) } else { 0.0 }; - s.view3d = v; - Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null)) -} - fn view3d(s: &mut Session, p: &J) -> Result<J> { // Validated up front so a bad target changes nothing. let target = match p.get("target") { @@ -209,12 +99,6 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> { } } }; - // Nested objects are parsed first: a bad one changes nothing. - let camera = p.get("camera").map(|c| merge_into("camera", &s.view3d.camera, c)).transpose()?; - let lights = p.get("lights").map(|l| merge_into("lights", &s.view3d.lights, l)).transpose()?; - let renderer = p.get("renderer").map(|r| merge_into("renderer", &s.view3d.renderer, r)).transpose()?; - let display = p.get("display").map(|d| merge_into("display", &s.view3d.display, d)).transpose()?; - let material = p.get("material").map(|m| merge_into("material", &s.view3d.material, m)).transpose()?; // A rejected environment must not leave a new scene applied. let environment = strp(p, "environment"); if let Some(e) = environment @@ -278,25 +162,6 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> { if let Some(b) = boolp(p, "alphaView") { v.alpha_view = b; } - if let Some(b) = boolp(p, "envEnabled") { - v.env_enabled = b; - } - if let Some(c) = camera { - v.camera = c; - } - if let Some(l) = lights { - v.lights = l; - } - if let Some(r) = renderer { - v.renderer = r; - } - if let Some(d) = display { - v.display = d; - } - if let Some(m) = material { - v.material = m; - } - v.sanitize(); Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null)) } diff --git a/crates/engine/tests/export_names.rs b/crates/engine/tests/export_names.rs index df71446..f3457a9 100644 --- a/crates/engine/tests/export_names.rs +++ b/crates/engine/tests/export_names.rs @@ -78,6 +78,23 @@ fn colliding_export_preserves_existing_files_and_writes_no_partial_outputs() { ); } +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn export_rejects_existing_file_in_destination_before_writing() { + let (mut s, _) = session(); + let dir = TempDir::new("existing"); + let sentinel = b"existing file must survive a rejected export"; + std::fs::write(dir.0.join("first.png"), sentinel).unwrap(); + let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})); + let existing = std::fs::read(dir.0.join("first.png")).unwrap(); + let files = std::fs::read_dir(&dir.0).unwrap().count(); + assert!( + result.is_err() && existing == sentinel && files == 1, + "export overwrote an existing destination file: response={result:?}, files={files}, sentinel preserved={}", + existing == sentinel + ); +} + #[test] #[cfg(not(target_arch = "wasm32"))] fn unique_export_writes_both_maps_with_their_expected_pixels() { diff --git a/crates/engine/tests/exposed_inputs.rs b/crates/engine/tests/exposed_inputs.rs new file mode 100644 index 0000000..e11f09d --- /dev/null +++ b/crates/engine/tests/exposed_inputs.rs @@ -0,0 +1,28 @@ +use materialcraft_engine::{core::NodeId, execute, new_session}; +use serde_json::json; + +#[test] +fn exposing_the_same_parameter_on_two_nodes_gives_each_its_own_input() { + let mut s = new_session(); + let nodes: Vec<NodeId> = (0..3).map(|_| NodeId(execute(&mut s, "graph.node.add", &json!({"def": "blend"})).unwrap()["id"].as_u64().unwrap())).collect(); + + // The properties panel's "Expose as graph input" sends no `id` + let ids: Vec<String> = nodes + .iter() + .map(|node| { + let reply = execute(&mut s, "graph.exposed.add", &json!({"label": "Opacity", "bind": {"node": node.0, "param": "opacity"}})).unwrap(); + reply["id"].as_str().unwrap().to_string() + }) + .collect(); + assert_eq!(ids, ["opacity", "opacity_1", "opacity_2"]); + + let graph = s.graph().unwrap(); + assert_eq!(graph.exposed.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ids); + for (node, id) in nodes.iter().zip(&ids) { + assert_eq!(graph.node(*node).unwrap().bindings.get("opacity"), Some(id)); + } + + // An explicit id still has to be free, and an unbound input still needs one + assert!(execute(&mut s, "graph.exposed.add", &json!({"id": "opacity_1", "bind": {"node": nodes[0].0, "param": "opacity"}})).is_err()); + assert!(execute(&mut s, "graph.exposed.add", &json!({"default": 0.5})).is_err()); +} diff --git a/crates/engine/tests/new_graph_dimensions.rs b/crates/engine/tests/new_graph_dimensions.rs new file mode 100644 index 0000000..0ba06fd --- /dev/null +++ b/crates/engine/tests/new_graph_dimensions.rs @@ -0,0 +1,48 @@ +use materialcraft_engine::{execute, new_session}; +use serde_json::json; + +#[test] +fn rectangular_templates_are_created_and_undone_as_one_edit() { + for template in ["empty", "pbr", "atomics"] { + let mut session = new_session(); + let original = session.pkg.clone(); + let original_graph = session.graph; + execute(&mut session, "file.new", &json!({"template": template, "name": "Wide", "width": 512, "height": 128})).unwrap(); + assert_eq!(session.graph().unwrap().size_px(), [512, 128]); + assert_eq!(session.graph().unwrap().name, "Wide"); + assert_eq!(session.pkg.graphs.len(), original.graphs.len() + 1); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.pkg, original); + assert_eq!(session.graph, original_graph); + assert!(!session.modified); + execute(&mut session, "edit.redo", &json!({})).unwrap(); + assert_eq!(session.graph().unwrap().size_px(), [512, 128]); + } +} + +#[test] +fn dimension_overrides_keep_square_defaults_and_bound_each_axis() { + for (parameters, expected) in [ + (json!({"size": 256}), [256, 256]), + (json!({"size": 256, "height": 64}), [256, 64]), + (json!({"size": 256, "width": 64}), [64, 256]), + (json!({"width": 1000, "height": 127}), [512, 64]), + (json!({"width": 0, "height": u64::MAX}), [16, 8192]), + ] { + let mut session = new_session(); + execute(&mut session, "file.new", ¶meters).unwrap(); + assert_eq!(session.graph().unwrap().size_px(), expected, "{parameters}"); + } +} + +#[test] +fn invalid_dimensions_do_not_create_a_partial_graph_or_undo_entry() { + for parameters in [json!({"width": -1}), json!({"height": "128"}), json!({"width": 32.5}), json!({"height": null})] { + let mut session = new_session(); + let original = session.pkg.clone(); + assert!(execute(&mut session, "file.new", ¶meters).is_err(), "{parameters}"); + assert_eq!(session.pkg, original); + assert!(!session.modified); + assert!(execute(&mut session, "edit.undo", &json!({})).is_err()); + } +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 44c239c..8ee5d14 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,4 +1,4 @@ -use materialcraft_engine::{Session, command_specs, execute, new_session, sample_session}; +use materialcraft_engine::{Session, command_specs, execute, sample_session}; use serde_json::{Value, json}; fn run(s: &mut Session, id: &str, p: Value) -> Value { @@ -235,15 +235,7 @@ fn panic_hunt() { // Skip file writes to the working directory and opening paths if matches!( spec.id, - "file.save" - | "file.saveAs" - | "file.saveCopy" - | "file.exportWithDependencies" - | "file.export" - | "file.open" - | "file.importBitmap" - | "file.exportMaterial" - | "file.sendToTextureCraft" + "file.save" | "file.saveAs" | "file.export" | "file.open" | "file.importBitmap" | "file.exportMaterial" | "file.sendToTextureCraft" ) { continue; } @@ -477,37 +469,13 @@ fn selected_wires_swap_their_sources_and_delete_together() { } #[test] -fn graphs_import_from_another_package_with_their_dependencies() { - use materialcraft_engine::core::{Package, Resource, ResourceBytes, Value}; - let mut from = Package::new("Other"); - from.graphs.push(materialcraft_engine::samples::template("empty", "Leaf", 8).unwrap()); - from.graphs.push(materialcraft_engine::samples::template("empty", "Root", 8).unwrap()); - from.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(vec![1, 2, 3]))); - { - let root = &mut from.graphs[1]; - let inst = root.add_node("graph_instance", [0.0, 0.0]); - root.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text("Leaf".into())); - let bm = root.add_node("bitmap", [0.0, 100.0]); - root.node_mut(bm).unwrap().params.insert("resource".into(), Value::Text("tex".into())); - } - let mut s = new_session(); - let name = materialcraft_engine::resource_cmds::import_graph_from(&mut s, &from, "Root").unwrap(); - assert_eq!(name, "Root"); - assert!(s.pkg.graph_by_name("Leaf").is_some(), "the instanced graph comes along"); - assert!(s.pkg.resource("tex").is_some(), "the bitmap comes along"); - // Importing again reuses identical graphs instead of duplicating them. - let again = materialcraft_engine::resource_cmds::import_graph_from(&mut s, &from, "Root").unwrap(); - assert_eq!(again, "Root"); - assert_eq!(s.pkg.graphs.iter().filter(|g| g.name.starts_with("Leaf")).count(), 1); - assert!(materialcraft_engine::resource_cmds::import_graph_from(&mut s, &from, "Nope").is_err()); - // graph.add pastes a graph as JSON and refuses garbage. - let g = serde_json::to_value(&from.graphs[0]).unwrap(); - let r = execute(&mut s, "graph.add", &json!({"graph": g})).unwrap(); - assert_eq!(r["name"], "Leaf_1"); - assert!(execute(&mut s, "graph.add", &json!({"graph": "nope"})).is_err()); - assert!(execute(&mut s, "graph.add", &json!({})).is_err()); - // Resources can be removed. - execute(&mut s, "file.deleteResource", &json!({"name": "tex"})).unwrap(); - assert!(s.pkg.resource("tex").is_none()); - assert!(execute(&mut s, "file.deleteResource", &json!({"name": "tex"})).is_err()); +fn undo_to_unmodified_state_clears_modified_flag() { + let mut s = sample_session(); + assert!(!s.modified); + run(&mut s, "graph.node.add", json!({"def": "uniform", "at": [0, 0]})); + assert!(s.modified); + run(&mut s, "edit.undo", json!({})); + assert!(!s.modified, "undoing to the unmodified state should clear the modified flag"); + run(&mut s, "edit.redo", json!({})); + assert!(s.modified, "redoing to the modified state should set the modified flag"); } diff --git a/crates/engine/tests/view_settings.rs b/crates/engine/tests/view_settings.rs index 6d95ea2..47d0ea1 100644 --- a/crates/engine/tests/view_settings.rs +++ b/crates/engine/tests/view_settings.rs @@ -51,66 +51,3 @@ fn valid_view_updates_still_apply_and_return_the_complete_settings() { assert_eq!(result["target"], json!([1.0, 2.0, 3.0])); assert_eq!(result, serde_json::to_value(&s.view3d).unwrap()); } - -#[test] -fn nested_3d_settings_merge_sanitize_and_reject_as_a_whole() { - let mut s = new_session(); - // Only the keys given change; the rest of the sub-struct stays. - let v = execute(&mut s, "view.3d", &json!({"camera": {"focalLength": 50}, "lights": {"point": [{"on": true, "intensity": 3}]}})).unwrap(); - assert_eq!(v["camera"]["focalLength"], 50.0); - assert_eq!(v["camera"]["projection"], "perspective"); - assert_eq!(v["lights"]["point"][0]["on"], true); - assert_eq!(v["lights"]["point"][0]["intensity"], 3.0); - assert_eq!(v["lights"]["point"][1]["on"], false); - let before = s.view3d.clone(); - // A malformed nested object rejects the whole request, scalars included. - assert!(execute(&mut s, "view.3d", &json!({"yaw": 10, "camera": "nope"})).is_err()); - assert!(execute(&mut s, "view.3d", &json!({"yaw": 10, "material": {"shader": "unknown"}})).is_err()); - assert_eq!(s.view3d, before); - // Hostile values are clamped, not kept. - let v = execute(&mut s, "view.3d", &json!({"camera": {"focalLength": 1e30, "near": -5, "far": 1e-9}, "material": {"common": {"ior": f64::NAN, "baseColor": [99.0, -1.0, 0.5]}, "tessellation": 1e9}})).unwrap(); - assert_eq!(v["camera"]["focalLength"], 1200.0); - assert!(v["camera"]["far"].as_f64().unwrap() > v["camera"]["near"].as_f64().unwrap()); - assert_eq!(v["material"]["common"]["ior"], 1.5); - assert_eq!(v["material"]["common"]["baseColor"], json!([64.0, 0.0, 0.5])); - assert_eq!(v["material"]["tessellation"], 4.0); - // Reset one part leaves the others. - execute(&mut s, "view.3d", &json!({"scene": "torus"})).unwrap(); - execute(&mut s, "view.3d.reset", &json!({"what": "camera"})).unwrap(); - assert_eq!(s.view3d.camera, materialcraft_engine::Camera3d::default()); - assert_eq!(s.view3d.scene, "torus"); - assert!(execute(&mut s, "view.3d.reset", &json!({"what": "nope"})).is_err()); -} - -#[test] -fn state_round_trips_and_garbage_state_falls_back_to_defaults() { - let mut s = new_session(); - execute(&mut s, "view.3d", &json!({"scene": "cloth", "environment": "warehouse", "exposure": 1.5, "lights": {"ambient": [0.2, 0.2, 0.2]}})).unwrap(); - let state = execute(&mut s, "view.3d.state", &json!({})).unwrap(); - execute(&mut s, "view.3d.reset", &json!({})).unwrap(); - assert_eq!(s.view3d.scene, "rounded_cube"); - execute(&mut s, "view.3d.loadState", &json!({"state": state, "keepScene": true})).unwrap(); - assert_eq!(s.view3d.scene, "rounded_cube", "keepScene leaves the mesh"); - assert_eq!(s.view3d.environment, "warehouse"); - assert_eq!(s.view3d.exposure, 1.5); - execute(&mut s, "view.3d.loadState", &json!({"state": {"scene": "nope", "environment": "nope", "yaw": f64::INFINITY, "distance": 1e9}})).unwrap(); - assert_eq!(s.view3d.scene, "rounded_cube"); - assert_eq!(s.view3d.environment, "studio"); - assert_eq!(s.view3d.distance, 20.0); - assert!(execute(&mut s, "view.3d.loadState", &json!({"state": 5})).is_err()); - assert!(execute(&mut s, "view.3d.loadState", &json!({})).is_err()); -} - -#[test] -fn session_settings_bound_history_cache_and_cook_size() { - let mut s = new_session(); - let v = execute(&mut s, "session.settings", &json!({"historySize": 3, "cacheMb": 1, "cookLimit": 100})).unwrap(); - assert_eq!(v["historySize"], 3); - assert_eq!(v["cacheMb"], 16, "the cache keeps at least 16 MB"); - assert_eq!(v["cookLimit"], 256); - for _ in 0..6 { - execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap(); - } - assert_eq!(s.history().len(), 3, "only 3 steps are kept"); - assert_eq!(execute(&mut s, "session.settings", &json!({"cookLimit": 0})).unwrap()["cookLimit"], 0); -} diff --git a/crates/eval/src/cache.rs b/crates/eval/src/cache.rs index f75e6d5..e175cea 100644 --- a/crates/eval/src/cache.rs +++ b/crates/eval/src/cache.rs @@ -26,26 +26,6 @@ impl Cache { self.bytes } - /// The cache's size limit in bytes - pub fn cap(&self) -> usize { - self.cap - } - - /// Change the size limit (at least 16 MB), evicting the least recently used entries past it - pub fn set_cap(&mut self, cap_bytes: usize) { - self.cap = cap_bytes.max(16 << 20); - self.evict(); - } - - fn evict(&mut self) { - while self.bytes > self.cap && self.entries.len() > 1 { - let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break }; - if let Some(e) = self.entries.remove(&k) { - self.bytes = self.bytes.saturating_sub(e.1); - } - } - } - pub fn len(&self) -> usize { self.entries.len() } @@ -76,6 +56,11 @@ impl Cache { self.bytes = self.bytes.saturating_sub(old.1); } self.bytes += size; - self.evict(); + while self.bytes > self.cap && self.entries.len() > 1 { + let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break }; + if let Some(e) = self.entries.remove(&k) { + self.bytes = self.bytes.saturating_sub(e.1); + } + } } } diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index 40e4772..62b01ab 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -52,6 +52,11 @@ pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 { index.hash(&mut h); serde_json::to_string(graph).unwrap_or_default().hash(&mut h); + for (id, res) in &graph.input_images { + pkg.resource(res).map(|r| r.bytes.content_hash()).hash(&mut h); + id.hash(&mut h); + graph.input_images_linear.contains(id).hash(&mut h); + } for n in &graph.nodes { if let Some(Value::Text(name)) = n.params.get("resource") { pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h); diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index f02a170..a9c48c1 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -12,9 +12,9 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu let mut cooked = Cooked::default(); let Some(graph) = package.graphs.get(graph_index) else { return cooked }; - // The top-level graph's input nodes show their preview images; the caller's images win + // Input nodes show their bound preview images; the caller's images win let bound; - let options = if options.depth == 0 && !graph.input_images.is_empty() { + let options = if !graph.input_images.is_empty() { let mut inputs: BTreeMap<String, Image> = graph .input_images .iter() diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index bacffb8..1ed1298 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -364,3 +364,68 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() { p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1)); assert_eq!(first(&p), (0.5, 0.5)); } + +#[test] +fn bound_input_image_resource_change_recooks_instance() { + use materialcraft_core::{Resource, ResourceBytes}; + use std::sync::atomic::AtomicU8; + let mut sub = Graph::new("sub"); + sub.size = [4, 4]; + let i = sub.add_node("input_grayscale", [0.0, 0.0]); + sub.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("in".into())); + let o = sub.add_node("output", [100.0, 0.0]); + sub.connect(i, "output", o, "input").unwrap(); + sub.input_images.insert("in".into(), "curv".into()); + let (top, inst) = instancing("top", "sub"); + let mut p = Package::new("p"); + p.graphs = vec![top, sub]; + p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100]))); + // Stands in for decoding: the first byte picks the shade. + let shade = AtomicU8::new(1); + let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 4])); + let cache = Mutex::new(Cache::default()); + let opts = Options::new(&res); + let first = cook(&p, 0, &opts, &cache); + assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error); + assert!(!first.nodes[&inst].cached); + let unchanged = cook(&p, 0, &opts, &cache); + assert!(unchanged.nodes[&inst].cached, "an unchanged instance should be served from the cache"); + p.resources[0].bytes = ResourceBytes::new(vec![2; 100]); + shade.store(2, Ordering::Relaxed); + let second = cook(&p, 0, &opts, &cache); + assert!(!second.nodes[&inst].cached, "changing the bound input image resource must recook the instance"); +} + +#[test] +fn bound_input_image_linear_flag_change_recooks_instance() { + use materialcraft_core::{Resource, ResourceBytes}; + let mut sub = Graph::new("sub"); + sub.size = [4, 4]; + let i = sub.add_node("input_grayscale", [0.0, 0.0]); + sub.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("in".into())); + let o = sub.add_node("output", [100.0, 0.0]); + sub.connect(i, "output", o, "input").unwrap(); + sub.input_images.insert("in".into(), "curv".into()); + let (top, inst) = instancing("top", "sub"); + let mut p = Package::new("p"); + p.graphs = vec![top, sub]; + p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100]))); + let res = |k: &str| { + let (name, linear) = materialcraft_image::split_resource_key(k); + (name == "curv").then(|| Image::filled(4, 4, Kind::Gray, [if linear { 0.5 } else { 0.2 }; 4])) + }; + let cache = Mutex::new(Cache::default()); + let opts = Options::new(&res); + let first = cook(&p, 0, &opts, &cache); + assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error); + assert!(!first.nodes[&inst].cached); + let first_value = first.image(inst, 0).unwrap().data[0]; + assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}"); + let second = cook(&p, 0, &opts, &cache); + assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache"); + p.graphs[1].input_images_linear.insert("in".into()); + let third = cook(&p, 0, &opts, &cache); + assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance"); + let third_value = third.image(inst, 0).unwrap().data[0]; + assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); +} diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 88b1c00..9d71287 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -132,7 +132,15 @@ fn gltf(bytes: &[u8]) -> Result<Mesh> { let pos: Vec<Vec3> = pos.map(|p| m.transform_point3(Vec3::from(p))).collect(); let n = pos.len(); match reader.read_normals() { - Some(ns) => normals.extend(ns.map(|q| m.transform_vector3(Vec3::from(q)).normalize_or_zero())), + Some(ns) => { + for q in ns { + let v = m.transform_vector3(Vec3::from(q)); + if !v.is_finite() { + return Err(bad("the mesh has non-finite (NaN or infinite) normals")); + } + normals.push(v.normalize_or_zero()); + } + } None => all_normals = false, } match reader.read_tex_coords(0) { @@ -241,6 +249,33 @@ mod tests { assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n").is_err()); } + #[test] + fn gltf_non_finite_normals_are_rejected() { + use base64::Engine as _; + let gltf_with_normals = |normals: [[f32; 3]; 4]| { + let idx: [u16; 6] = [0, 1, 2, 0, 2, 3]; + let mut buf: Vec<u8> = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect(); + buf.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes())); + buf.extend(idx.iter().flat_map(|i| i.to_le_bytes())); + let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + format!( + r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], +"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0,"NORMAL":1}},"indices":2}}]}}], +"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{{"bufferView":1,"componentType":5126,"count":4,"type":"VEC3"}},{{"bufferView":2,"componentType":5123,"count":6,"type":"SCALAR"}}], +"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{{"buffer":0,"byteOffset":48,"byteLength":48}},{{"buffer":0,"byteOffset":96,"byteLength":12}}], +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, + buf.len() + ) + .into_bytes() + }; + let mut nan_normals = [[0.0f32, 0.0, 1.0]; 4]; + nan_normals[2][0] = f32::NAN; + assert!(load_mesh("x.gltf", &gltf_with_normals(nan_normals)).is_err()); + let mut inf_normals = [[0.0f32, 0.0, 1.0]; 4]; + inf_normals[1][2] = f32::INFINITY; + assert!(load_mesh("x.gltf", &gltf_with_normals(inf_normals)).is_err()); + } + #[test] fn a_bad_index_drops_its_whole_triangle_and_later_ones_keep_their_vertices() { // Triangles: (0,1,2), (0,1,9) out of range, (0,2,3). diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index 8328368..1c8dc7e 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -67,7 +67,6 @@ impl<'text> SbsReader<'text, '_> { let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase(); let source = child_element(item, "source"); let mut bytes: Option<Vec<u8>> = None; - let mut link: Option<String> = None; let mut why_missing = String::new(); if let Some(embedded) = source.and_then(|s| child_element(s, "binembedded")) { @@ -87,7 +86,6 @@ impl<'text> SbsReader<'text, '_> { match linked(file) { Some(data) => { bytes = Some(data); - link = Some(file.to_string()); break; } None => why_missing = format!("its file `{file}` was not found next to the package"), @@ -104,11 +102,7 @@ impl<'text> SbsReader<'text, '_> { self.resource_bytes += data.len(); let ext = if kind == "svg" { "svg".to_string() } else { format }; - let file = crate::safe_file_name(&format!("{name}.{ext}")); - pkg.resources.push(match link { - Some(l) => Resource::linked(name.clone(), file, ResourceBytes::new(data), l), - None => Resource::new(name.clone(), file, ResourceBytes::new(data)), - }); + pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data))); } None => { let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing }; diff --git a/crates/formats/src/sbs/write.rs b/crates/formats/src/sbs/write.rs index 2b2ea55..dbed697 100644 --- a/crates/formats/src/sbs/write.rs +++ b/crates/formats/src/sbs/write.rs @@ -25,34 +25,16 @@ pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> { for resource in &pkg.resources { let svg = resource.file.to_ascii_lowercase().ends_with(".svg"); let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e); - // A resource linked to a file next to the package stays a link; one linked from - // elsewhere (or opened without a folder) is embedded, so the file is whole - let relative = resource.link.as_deref().filter(|l| !l.contains(':') && !l.starts_with('/') && !l.starts_with('\\')); - match relative { - Some(path) => { - let _ = write!( - content, - "<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"{}\"/></resource>", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - xml_escape(path) - ); - } - None => { - let _ = write!( - content, - "<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>", - xml_escape(&resource.name), - writer.next_uid(), - if svg { "svg" } else { "bitmap" }, - xml_escape(ext), - resource.bytes.len(), - encode_embedded(resource.bytes.as_slice())? - ); - } - } + let _ = write!( + content, + "<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>", + xml_escape(&resource.name), + writer.next_uid(), + if svg { "svg" } else { "bitmap" }, + xml_escape(ext), + resource.bytes.len(), + encode_embedded(resource.bytes.as_slice())? + ); } content.push_str("</content></group>"); } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 82f6724..fd5deba 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -10,7 +10,6 @@ pub mod bvh; pub mod camera; pub mod gbuffer; pub mod mesh; -pub mod preview; pub mod primitives; pub mod unwrap; diff --git a/crates/geom/src/preview.rs b/crates/geom/src/preview.rs deleted file mode 100644 index c5a8ebd..0000000 --- a/crates/geom/src/preview.rs +++ /dev/null @@ -1,233 +0,0 @@ -//! The 3D preview's plain-data description shared by the engine (where it is session state) -//! and the renderer: what shows behind the mesh, the lights, the shading model and the -//! material's common values. - -use serde::{Deserialize, Serialize}; - -/// What shows where a camera ray misses the mesh. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Background { - /// The studio vignette. - Backdrop, - /// A flat color (linear RGB). - Color([f32; 3]), - /// The (blurred) environment map. - Environment, -} - -/// A point light in the scene (position in scene radii from the center). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct PointLight { - pub on: bool, - /// Linear RGB. - pub color: [f32; 3], - pub intensity: f32, - pub position: [f32; 3], -} - -impl PointLight { - /// The two default lights: key from the upper left, fill from the right and behind. - pub const DEFAULTS: [PointLight; 2] = [ - PointLight { on: false, color: [1.0; 3], intensity: 1.0, position: [-2.5, 3.0, 2.5] }, - PointLight { on: false, color: [0.2; 3], intensity: 1.0, position: [3.0, 1.0, -2.0] }, - ]; - - /// Every value brought into its range; non-finite values become the default. - pub fn sanitized(mut self, default: PointLight) -> PointLight { - for (v, d) in self.color.iter_mut().zip(default.color) { - *v = if v.is_finite() { v.clamp(0.0, 64.0) } else { d }; - } - self.intensity = if self.intensity.is_finite() { self.intensity.clamp(0.0, 100.0) } else { default.intensity }; - for (v, d) in self.position.iter_mut().zip(default.position) { - *v = if v.is_finite() { v.clamp(-50.0, 50.0) } else { d }; - } - self - } -} - -impl Default for PointLight { - fn default() -> Self { - PointLight::DEFAULTS[0] - } -} - -/// The shading model. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Shader { - /// Metallic/roughness with coat, fuzz, emission, thin film, transmission and subsurface terms. - OpenPbr, - /// Plain metallic/roughness. - MetallicRoughness, - /// Metallic/roughness with the coat layer. - Coated, - /// Metallic/roughness with the subsurface term. - Subsurface, - /// Specular color / glossiness maps instead of metallic / roughness. - SpecularGlossiness, - /// Lambert diffuse plus a Blinn-Phong highlight from the lights. - Blinn, - /// Diffuse only. - Lambert, - /// The base color as is. - Unlit, - /// Normals as colors (surface inspection). - MeshInfo, -} - -impl Shader { - pub const ALL: [(Shader, &'static str); 9] = [ - (Shader::OpenPbr, "openPbr"), - (Shader::MetallicRoughness, "metallicRoughness"), - (Shader::Coated, "coated"), - (Shader::Subsurface, "subsurface"), - (Shader::SpecularGlossiness, "specularGlossiness"), - (Shader::Blinn, "blinn"), - (Shader::Lambert, "lambert"), - (Shader::Unlit, "unlit"), - (Shader::MeshInfo, "meshInfo"), - ]; - - pub fn id(self) -> &'static str { - Self::ALL.iter().find(|(s, _)| *s == self).map_or("openPbr", |(_, id)| id) - } - - pub fn by_id(id: &str) -> Option<Shader> { - Self::ALL.iter().find(|(_, i)| *i == id).map(|(s, _)| *s) - } -} - -/// Which maps drive the material (off = the common value is used even when the map exists). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct MapUse { - pub base_color: bool, - pub roughness: bool, - pub metallic: bool, - pub normal: bool, - pub height: bool, - pub ao: bool, - pub emissive: bool, - pub opacity: bool, - pub specular: bool, -} - -impl Default for MapUse { - fn default() -> Self { - MapUse { base_color: true, roughness: true, metallic: true, normal: true, height: true, ao: true, emissive: true, opacity: true, specular: true } - } -} - -/// The material's common values: what each channel is where no map drives it, and the layer -/// terms that have no map at all. Colors are linear RGB; weights 0..1. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Common { - pub base_weight: f32, - pub base_color: [f32; 3], - pub metalness: f32, - pub diffuse_roughness: f32, - pub specular_weight: f32, - pub specular_color: [f32; 3], - pub specular_roughness: f32, - pub ior: f32, - pub transmission_weight: f32, - pub transmission_color: [f32; 3], - pub subsurface_weight: f32, - pub subsurface_color: [f32; 3], - pub coat_weight: f32, - pub coat_color: [f32; 3], - pub coat_roughness: f32, - pub coat_ior: f32, - pub coat_darkening: f32, - pub fuzz_weight: f32, - pub fuzz_color: [f32; 3], - pub emission_luminance: f32, - pub emission_color: [f32; 3], - pub thin_film_weight: f32, - /// Nanometres. - pub thin_film_thickness: f32, - pub thin_film_ior: f32, - pub opacity: f32, - pub thin_walled: bool, - pub ambient_occlusion: f32, - pub height: f32, -} - -impl Default for Common { - fn default() -> Self { - Common { - base_weight: 1.0, - base_color: [0.5; 3], - metalness: 0.0, - diffuse_roughness: 0.0, - specular_weight: 1.0, - specular_color: [1.0; 3], - specular_roughness: 0.5, - ior: 1.5, - transmission_weight: 0.0, - transmission_color: [1.0; 3], - subsurface_weight: 0.0, - subsurface_color: [0.8; 3], - coat_weight: 0.0, - coat_color: [1.0; 3], - coat_roughness: 0.0, - coat_ior: 1.6, - coat_darkening: 1.0, - fuzz_weight: 0.0, - fuzz_color: [1.0; 3], - emission_luminance: 0.0, - emission_color: [1.0; 3], - thin_film_weight: 0.0, - thin_film_thickness: 500.0, - thin_film_ior: 1.4, - opacity: 1.0, - thin_walled: false, - ambient_occlusion: 1.0, - height: 0.5, - } - } -} - -impl Common { - /// Every value brought into its range; non-finite values become the default. - pub fn sanitized(mut self) -> Common { - let d = Common::default(); - let unit = |v: &mut f32, dv: f32| *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { dv }; - let col = |c: &mut [f32; 3], dc: [f32; 3]| { - for (v, dv) in c.iter_mut().zip(dc) { - *v = if v.is_finite() { v.clamp(0.0, 64.0) } else { dv }; - } - }; - unit(&mut self.base_weight, d.base_weight); - col(&mut self.base_color, d.base_color); - unit(&mut self.metalness, d.metalness); - unit(&mut self.diffuse_roughness, d.diffuse_roughness); - unit(&mut self.specular_weight, d.specular_weight); - col(&mut self.specular_color, d.specular_color); - unit(&mut self.specular_roughness, d.specular_roughness); - self.ior = if self.ior.is_finite() { self.ior.clamp(1.0, 3.0) } else { d.ior }; - unit(&mut self.transmission_weight, d.transmission_weight); - col(&mut self.transmission_color, d.transmission_color); - unit(&mut self.subsurface_weight, d.subsurface_weight); - col(&mut self.subsurface_color, d.subsurface_color); - unit(&mut self.coat_weight, d.coat_weight); - col(&mut self.coat_color, d.coat_color); - unit(&mut self.coat_roughness, d.coat_roughness); - self.coat_ior = if self.coat_ior.is_finite() { self.coat_ior.clamp(1.0, 3.0) } else { d.coat_ior }; - unit(&mut self.coat_darkening, d.coat_darkening); - unit(&mut self.fuzz_weight, d.fuzz_weight); - col(&mut self.fuzz_color, d.fuzz_color); - self.emission_luminance = if self.emission_luminance.is_finite() { self.emission_luminance.clamp(0.0, 100.0) } else { d.emission_luminance }; - col(&mut self.emission_color, d.emission_color); - unit(&mut self.thin_film_weight, d.thin_film_weight); - self.thin_film_thickness = if self.thin_film_thickness.is_finite() { self.thin_film_thickness.clamp(0.0, 2000.0) } else { d.thin_film_thickness }; - self.thin_film_ior = if self.thin_film_ior.is_finite() { self.thin_film_ior.clamp(1.0, 3.0) } else { d.thin_film_ior }; - unit(&mut self.opacity, d.opacity); - unit(&mut self.ambient_occlusion, d.ambient_occlusion); - unit(&mut self.height, d.height); - self - } -} diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 0126840..7f07270 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -216,42 +216,6 @@ pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh { b.finish("Cylinder") } -/// A cylinder along Y with rounded rims (`bevel` = rim radius). -pub fn rounded_cylinder(radius: f32, height: f32, bevel: f32, segs: usize) -> Mesh { - let mut b = Builder::default(); - let h = height * 0.5; - let bev = bevel.clamp(0.0, radius.min(h) * 0.9); - let mut profile = Vec::new(); - for k in 0..=6 { - let a = k as f32 / 6.0 * PI * 0.5; - profile.push((radius - bev + bev * a.sin(), h - bev + bev * a.cos())); - } - for k in 0..=6 { - let a = k as f32 / 6.0 * PI * 0.5; - profile.push((radius - bev + bev * a.cos(), -h + bev - bev * a.sin())); - } - lathe_into(&mut b, Vec3::ZERO, &profile, segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); - disk_into(&mut b, Vec3::Y * h, radius - bev, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); - disk_into(&mut b, -Vec3::Y * h, radius - bev, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); - b.finish("Rounded cylinder") -} - -/// A draped square of cloth: a plane with soft folds, facing +Y. -pub fn cloth(size: f32, subdivisions: usize) -> Mesh { - let mut b = Builder::default(); - let s = subdivisions.max(8); - let fold = |x: f32, z: f32| 0.07 * (x * 4.2).sin() * (z * 2.6 + 0.5).cos() + 0.035 * (x * 9.0 + z * 7.0).sin() + 0.02 * (z * 12.0).cos(); - b.grid(s, s, |i, j| { - let (u, v) = (j as f32 / s as f32, i as f32 / s as f32); - let (x, z) = ((u - 0.5) * size, (v - 0.5) * size); - let y = fold(x, z); - let e = 1e-3; - let (dx, dz) = ((fold(x + e, z) - fold(x - e, z)) / (2.0 * e), (fold(x, z + e) - fold(x, z - e)) / (2.0 * e)); - (Vec3::new(x, y, z), Vec3::new(-dx, 1.0, -dz), Vec2::new(u, v)) - }); - b.finish("Cloth") -} - /// A torus around Y. pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { let mut b = Builder::default(); @@ -366,11 +330,8 @@ pub fn builtin(id: &str) -> Option<Mesh> { "cube" => cube(2.0), "rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15), "cylinder" => cylinder(1.0, 2.0, 96), - "rounded_cylinder" | "roundedcylinder" => rounded_cylinder(1.0, 2.0, 0.12, 96), "torus" => torus(1.0, 0.35, 128, 48), "plane" => plane(2.0, 16), - "plane_hires" | "planehires" => plane(2.0, 128), - "cloth" => cloth(2.0, 96), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), _ => return None, @@ -378,17 +339,14 @@ pub fn builtin(id: &str) -> Option<Mesh> { } /// Ids accepted by [`builtin`], in menu order. -pub const BUILTINS: [(&str, &str); 12] = [ +pub const BUILTINS: [(&str, &str); 9] = [ ("material_ball", "Material ball"), ("sphere", "Sphere"), ("cube", "Cube"), ("rounded_cube", "Rounded cube"), ("cylinder", "Cylinder"), - ("rounded_cylinder", "Rounded cylinder"), ("torus", "Torus"), ("plane", "Plane"), - ("plane_hires", "Plane (hi-res)"), - ("cloth", "Cloth"), ("crate", "Crate"), ("udim_plane", "UDIM plane"), ]; diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs index 6a7bf85..c6a84ad 100644 --- a/crates/nodes/src/ops.rs +++ b/crates/nodes/src/ops.rs @@ -302,18 +302,12 @@ pub fn blend_channel(mode: i32, b: f32, f: f32) -> f32 { } 12 => (b - f).abs(), 13 => { - if f >= 1.0 { - 1.0 - } else { - (b / (1.0 - f)).min(1.0) - } + // W3C color dodge: a black background stays black, even under a white foreground + if f >= 1.0 { if b > 0.0 { 1.0 } else { 0.0 } } else { (b / (1.0 - f)).min(1.0) } } 14 => { - if f <= 0.0 { - 0.0 - } else { - 1.0 - ((1.0 - b) / f).min(1.0) - } + // W3C color burn: a white background stays white, even under a black foreground + if f <= 0.0 { if b < 1.0 { 0.0 } else { 1.0 } } else { 1.0 - ((1.0 - b) / f).min(1.0) } } 15 => { if f < 0.5 { @@ -352,6 +346,19 @@ pub fn gray_from(w: u32, h: u32, v: Vec<f32>) -> Image { mod tests { use super::*; + #[test] + fn color_dodge_and_burn_keep_black_and_white_backgrounds() { + const DODGE: i32 = 13; + const BURN: i32 = 14; + // (background, foreground, expected), W3C compositing formulas + for (b, f, expected) in [(0.0, 1.0, 0.0), (0.0, 0.5, 0.0), (0.5, 1.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0.75, 1.0)] { + assert_eq!(blend_channel(DODGE, b, f), expected, "dodge b={b} f={f}"); + } + for (b, f, expected) in [(1.0, 0.0, 1.0), (1.0, 0.5, 1.0), (0.5, 0.0, 0.0), (0.75, 0.5, 0.5), (0.0, 0.25, 0.0)] { + assert_eq!(blend_channel(BURN, b, f), expected, "burn b={b} f={f}"); + } + } + #[test] fn blur_keeps_mean_and_tiles() { let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 }); diff --git a/crates/nodes/src/parameter.rs b/crates/nodes/src/parameter.rs index 46b5112..4925f86 100644 --- a/crates/nodes/src/parameter.rs +++ b/crates/nodes/src/parameter.rs @@ -14,9 +14,12 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) for p in &def.params { let Some(v) = params.get_mut(p.id) else { continue }; if let Value::Enum(i) = v { - if !p.options.is_empty() { - *i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX)); - } + // (an enum without options has nothing to choose from: its default stands) + *i = match (p.options.len().checked_sub(1), &p.default) { + (Some(last), _) => (*i).min(u32::try_from(last).unwrap_or(u32::MAX)), + (None, Value::Enum(d)) => *d, + (None, _) => 0, + }; continue; } if let Value::Color(c) = v { @@ -25,11 +28,11 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) } continue; } - if p.min >= p.max { - continue; - } + // No range declared (an Input Value's default takes any number): only a value that isn't + // a number goes + let ranged = p.min < p.max; let span = p.max - p.min; - let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span); + let (lo, hi) = if ranged { (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) }; // The default's component `i`, or 0 when the default is a different variant let fallback = |i: usize| match &p.default { Value::Float(d) => [*d].get(i).copied(), @@ -46,8 +49,8 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>) Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)), - Value::Int(x) => clamp_int(x), - Value::Int2(a) => a.iter_mut().for_each(clamp_int), + Value::Int(x) if ranged => clamp_int(x), + Value::Int2(a) if ranged => a.iter_mut().for_each(clamp_int), _ => {} } } diff --git a/crates/nodes/src/parameter.test.rs b/crates/nodes/src/parameter.test.rs index 226e9e5..5ecacfd 100644 --- a/crates/nodes/src/parameter.test.rs +++ b/crates/nodes/src/parameter.test.rs @@ -33,6 +33,32 @@ fn clamp_params_covers_values_set_after_resolution() { assert_eq!(p["opacity"], Value::Float(17.0)); } +#[test] +fn clamp_params_bounds_an_enum_without_options() { + let mut def = find("blend").unwrap().clone(); + let enums = def.params.iter_mut().find(|p| matches!(p.default, Value::Enum(_))).expect("an enum parameter"); + enums.options = &[]; + enums.default = Value::Enum(1); + let id = enums.id; + let mut p = BTreeMap::from([(id.to_string(), Value::Enum(999))]); + clamp_params(&def, &mut p); + assert_eq!(p[id], Value::Enum(1)); +} + +/// A parameter with no declared range keeps any number, and only a value that isn't a number goes. +#[test] +fn clamp_params_keeps_numbers_without_a_declared_range() { + let def = find("input_value").unwrap(); + let default = def.params.iter().find(|p| p.id == "default").unwrap(); + assert!(default.min >= default.max, "input_value's default declares no range"); + let mut p = over("default", Value::Float(3.5)); + clamp_params(def, &mut p); + assert_eq!(p["default"], Value::Float(3.5)); + let mut p = over("default", Value::Float(f32::NAN)); + clamp_params(def, &mut p); + assert_eq!(p["default"], default.default); +} + #[test] fn defaults_lie_inside_their_hard_limits() { for def in catalog() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 495af74..25e484f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -14,6 +14,4 @@ mod relief; pub use displacement::Displacement; pub use relief::Relief; -pub use preview::{ - Background, Common, Lighting, MapUse, Maps, PointLight, Scene, Settings, Shader, VIEW_TRIANGLES, builtin_mesh, camera, pan, render, render_cancellable, -}; +pub use preview::{Lighting, Maps, Scene, Settings, VIEW_TRIANGLES, builtin_mesh, pan, render, render_cancellable}; diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 44fc5dd..a7fca3b 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -13,8 +13,6 @@ use materialcraft_geom::{Bvh, Mesh, OrbitCamera}; use materialcraft_image::{Image, linear_to_srgb}; use rayon::prelude::*; -pub use materialcraft_geom::preview::{Background, Common, MapUse, PointLight, Shader}; - use crate::ibl::{self, EnvImage}; /// The material's maps (any may be missing: defaults are mid gray, flat, rough 0.5, dielectric). @@ -28,10 +26,6 @@ pub struct Maps { pub ao: Option<Image>, pub emissive: Option<Image>, pub opacity: Option<Image>, - /// Specular color (the specular/glossiness workflow and OpenPBR's specular weight). - pub specular: Option<Image>, - /// Glossiness (the specular/glossiness workflow: 1 − roughness). - pub glossiness: Option<Image>, } impl Maps { @@ -40,19 +34,6 @@ impl Maps { let mut m = Maps::default(); for (usage, img) in items { use materialcraft_core::MaterialChannel; - // The specular/glossiness workflow's maps are not preview channels of their own - if usage.eq_ignore_ascii_case("specular") { - if m.specular.is_none() { - m.specular = Some(img.clone()); - } - continue; - } - if usage.eq_ignore_ascii_case("glossiness") { - if m.glossiness.is_none() { - m.glossiness = Some(img.clone()); - } - continue; - } let Some(channel) = MaterialChannel::from_id(usage) else { continue }; let slot = match channel { @@ -173,9 +154,8 @@ pub const VIEW_TRIANGLES: usize = 500_000; /// A built-in mesh by id; unknown ids give the rounded cube. pub fn builtin_mesh(id: &str) -> Mesh { - let base = if id == "sphere_2_tiles" { "sphere" } else { id }; - let mut m = materialcraft_geom::primitives::builtin(base).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15)); - if id == "sphere_2_tiles" { + let mut m = materialcraft_geom::primitives::builtin(id).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15)); + if id == "sphere" { // The texture wraps twice around, so texels are square at the equator. m.uvs.iter_mut().for_each(|uv| uv.x *= 2.0); } @@ -218,7 +198,7 @@ impl Lighting { } /// Camera and look. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug)] pub struct Settings { /// Degrees. pub yaw: f32, @@ -248,27 +228,6 @@ pub struct Settings { pub transparency: bool, /// Show the material's alpha channel on the mesh, unlit (white = opaque, black = clear). pub alpha_view: bool, - /// Vertical field of view, degrees (perspective). - pub fov: f32, - /// Orthographic projection. - pub ortho: bool, - /// What a miss shows (`show_env` = true overrides it with the environment). - pub background: Background, - /// Fixed near and far clip distances in scene radii from the camera (`None` = automatic). - pub clip: Option<[f32; 2]>, - /// Ambient light added to every surface (linear RGB; black = off). - pub ambient: [f32; 3], - /// Point lights. - pub lights: [PointLight; 2], - /// Environment lighting on (off leaves the ambient and point lights). - pub env_light: bool, - pub shader: Shader, - pub common: Common, - pub use_map: MapUse, - /// Draw the triangle edges over the surface. - pub wireframe: bool, - /// Skip faces turned away from the camera. - pub backface_culling: bool, } impl Default for Settings { @@ -288,18 +247,6 @@ impl Default for Settings { key_light: 0.0, transparency: true, alpha_view: false, - fov: 35.0, - ortho: false, - background: Background::Backdrop, - clip: None, - ambient: [0.0; 3], - lights: PointLight::DEFAULTS, - env_light: true, - shader: Shader::OpenPbr, - common: Common::default(), - use_map: MapUse::default(), - wireframe: false, - backface_culling: false, } } } @@ -312,9 +259,9 @@ pub fn camera(scene: &Scene, s: &Settings) -> OrbitCamera { yaw: s.yaw.to_radians(), pitch: s.pitch.clamp(-89.0, 89.0).to_radians(), distance: s.distance.clamp(1.05, 50.0) * scene.radius, - fov: if s.fov.is_finite() { s.fov.clamp(5.0, 120.0) } else { 35.0 }, + fov: 35.0, scene_radius: scene.radius, - ortho: s.ortho, + ortho: false, } } @@ -327,6 +274,16 @@ pub fn pan(scene: &Scene, s: &Settings, dx: f32, dy: f32) -> [f32; 3] { t.to_array().map(|v| if v.is_finite() { v } else { 0.0 }) } +#[inline] +fn tex(img: &Option<Image>, uv: Vec2) -> Option<[f32; 4]> { + img.as_ref().map(|i| i.sample(uv.x, uv.y, true)) +} + +#[inline] +fn tex_gray(img: &Option<Image>, uv: Vec2, default: f32) -> f32 { + img.as_ref().map_or(default, |i| i.sample_gray(uv.x, uv.y, true)) +} + /// Narkowicz's fit of the ACES filmic curve. #[inline] fn aces(x: f32) -> f32 { @@ -350,11 +307,11 @@ fn rotate_y(v: Vec3, deg: f32) -> Vec3 { /// The material's alpha at `uv`: the opacity output, else the base color's alpha channel, else /// opaque. -fn alpha(maps: &Maps, s: &Settings, uv: Vec2) -> f32 { +fn alpha(maps: &Maps, uv: Vec2) -> f32 { let a = match (&maps.opacity, &maps.base_color) { - (Some(o), _) if s.use_map.opacity => o.sample_gray(uv.x, uv.y, true), - (_, Some(b)) if s.use_map.base_color && !b.is_gray() => b.sample(uv.x, uv.y, true)[3] * s.common.opacity, - _ => s.common.opacity, + (Some(o), _) => o.sample_gray(uv.x, uv.y, true), + (None, Some(b)) if !b.is_gray() => b.sample(uv.x, uv.y, true)[3], + _ => 1.0, }; if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 } } @@ -413,101 +370,9 @@ struct Shaded { t: f32, } -/// Schlick Fresnel for a dielectric of `ior` at `cos`. -#[inline] -fn fresnel(ior: f32, cos: f32) -> f32 { - let f0 = ((ior - 1.0) / (ior + 1.0)).powi(2); - f0 + (1.0 - f0) * (1.0 - cos.clamp(0.0, 1.0)).powi(5) -} - -/// Thin-film interference tint: the reflectance of a film `nm` thick with index `ior` for the -/// three wavelengths 650/550/450 nm at `cos` (a cosine-series approximation). -#[inline] -fn thin_film(nm: f32, ior: f32, cos: f32) -> Vec3 { - let sin2 = (1.0 - cos * cos).clamp(0.0, 1.0) / (ior * ior); - let cos_t = (1.0 - sin2).max(0.0).sqrt(); - let path = 2.0 * ior * nm * cos_t; - let r = |lambda: f32| 0.5 + 0.5 * (std::f32::consts::TAU * path / lambda).cos(); - Vec3::new(r(650.0), r(550.0), r(450.0)) -} - -/// Blinn-Phong highlight exponent from roughness. -#[inline] -fn blinn_exponent(rough: f32) -> f32 { - 2.0 / (rough * rough).max(1e-3) - 2.0 -} - -/// What the maps (or the common values) say about the surface at `uv`. -struct Surface { - base: Vec3, - rough: f32, - metal: f32, - ao: f32, - /// Dielectric reflectance at normal incidence (the specular workflow's specular color). - spec_f0: Vec3, -} - -fn surface(maps: &Maps, s: &Settings, uv: Vec2) -> Surface { - let c = &s.common; - let common_base = Vec3::from(c.base_color) * c.base_weight; - let base = match &maps.base_color { - Some(b) if s.use_map.base_color => { - let v = b.sample(uv.x, uv.y, true); - Vec3::new(v[0], v[1], v[2]) * c.base_weight - } - _ => common_base, - }; - let (rough, spec_f0) = if s.shader == Shader::SpecularGlossiness { - let gloss = match &maps.glossiness { - Some(g) => g.sample_gray(uv.x, uv.y, true), - None => 1.0 - c.specular_roughness, - }; - let spec = match &maps.specular { - Some(sp) if s.use_map.specular => { - let v = sp.sample(uv.x, uv.y, true); - Vec3::new(v[0], v[1], v[2]) - } - _ => Vec3::from(c.specular_color) * 0.04, - }; - ((1.0 - gloss).clamp(0.02, 1.0), spec) - } else { - let rough = match &maps.roughness { - Some(r) if s.use_map.roughness => r.sample_gray(uv.x, uv.y, true), - _ => c.specular_roughness, - }; - let f0 = ((c.ior - 1.0) / (c.ior + 1.0)).powi(2); - let spec_w = match &maps.specular { - Some(sp) if s.use_map.specular && s.shader == Shader::OpenPbr => sp.sample_gray(uv.x, uv.y, true), - _ => 1.0, - }; - (rough.clamp(0.02, 1.0), Vec3::from(c.specular_color) * (f0 * c.specular_weight * spec_w)) - }; - let metal = match &maps.metallic { - Some(m) if s.use_map.metallic && s.shader != Shader::SpecularGlossiness => m.sample_gray(uv.x, uv.y, true), - _ if s.shader == Shader::SpecularGlossiness => 0.0, - _ => c.metalness, - }; - let ao = match &maps.ao { - Some(a) if s.use_map.ao => a.sample_gray(uv.x, uv.y, true), - _ => c.ambient_occlusion, - }; - Surface { base, rough, metal: metal.clamp(0.0, 1.0), ao: ao.clamp(0.0, 1.0), spec_f0 } -} - /// Shade the first surface along one ray; `None` = missed the mesh. -fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, tmax: f32) -> Option<Shaded> { - let hit = if s.backface_culling { - let m = &scene.mesh; - scene.bvh.closest_filtered(origin, dir, tmax, &|t| { - let Some([i0, i1, i2]) = m.tri(t as usize) else { return true }; - match (m.positions.get(i0), m.positions.get(i1), m.positions.get(i2)) { - (Some(a), Some(b), Some(c)) => (*b - *a).cross(*c - *a).dot(dir) < 0.0, - _ => true, - } - })? - } else { - scene.bvh.closest(origin, dir, tmax)? - }; +fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Shaded> { + let hit = scene.bvh.closest(origin, dir, f32::MAX)?; let m = &scene.mesh; let [i0, i1, i2] = m.tri(hit.tri as usize)?; let (w1, w2) = (hit.u, hit.v); @@ -524,17 +389,16 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec let uv0 = *m.uvs.get(i0)? * w0 + *m.uvs.get(i1)? * w1 + *m.uvs.get(i2)? * w2; let uv = uv0 * s.tiling; let v = -dir; - let t_total = hit.t; - let a = alpha(maps, s, uv); - // Wireframe: the edges of the triangle hit, in the barycentric sense. - let on_edge = s.wireframe && [w0, w1, w2].iter().any(|w| *w < 0.03); + let a = alpha(maps, uv); if s.alpha_view { - return Some(Shaded { color: if on_edge { Vec3::new(1.0, 0.5, 0.0) } else { Vec3::splat(a) }, alpha: 1.0, t: t_total }); + return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t }); } - let sf = surface(maps, s, uv); - let n = match &maps.normal { - Some(nm) if s.use_map.normal => { - let c = nm.sample(uv.x, uv.y, true); + let base = tex(&maps.base_color, uv).map_or(Vec3::splat(0.5), |c| Vec3::new(c[0], c[1], c[2])); + let rough = tex_gray(&maps.roughness, uv, 0.5).clamp(0.02, 1.0); + let metal = tex_gray(&maps.metallic, uv, 0.0).clamp(0.0, 1.0); + let ao = tex_gray(&maps.ao, uv, 1.0).clamp(0.0, 1.0); + let n = match tex(&maps.normal, uv) { + Some(c) => { let mut t = Vec3::new(c[0] * 2.0 - 1.0, c[1] * 2.0 - 1.0, c[2] * 2.0 - 1.0); if s.normal_y_flip { t.y = -t.y; @@ -543,119 +407,35 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec // with top-left UVs. (tan * t.x - bit * t.y + nrm * t.z.max(0.05)).normalize_or_zero() } - _ => nrm, + None => nrm, }; let n = if n.dot(v) < 0.0 { nrm } else { n }; let ndv = n.dot(v).clamp(1e-4, 1.0); - let c = &s.common; - let wire = |mut color: Vec3| { - if on_edge { - color = Vec3::new(1.0, 0.5, 0.0); - } - color - }; - match s.shader { - Shader::Unlit => return Some(Shaded { color: wire(sf.base), alpha: if s.transparency { a } else { 1.0 }, t: t_total }), - Shader::MeshInfo => return Some(Shaded { color: wire(n * 0.5 + Vec3::splat(0.5)), alpha: 1.0, t: t_total }), - _ => {} - } - let (base, rough, metal, ao) = (sf.base, sf.rough, sf.metal, sf.ao); - let f0 = sf.spec_f0.lerp(base, metal); - // Diffuse roughness darkens the grazing diffuse a little (a cheap Oren-Nayar stand-in). - let diffuse_col = base * (1.0 - metal) * (1.0 - 0.5 * c.diffuse_roughness * (1.0 - ndv)); + let f0 = Vec3::splat(0.04).lerp(base, metal); + let diffuse_col = base * (1.0 - metal); let rot = |d: Vec3| rotate_y(d, -s.env_rotation); let r = (n * (2.0 * n.dot(v)) - v).normalize_or_zero(); let (sa, sb) = env_brdf(rough, ndv); - let env_diff = if s.env_light { light.diffuse(rot(n)) } else { Vec3::ZERO }; - let env_spec = if s.env_light { light.specular(rot(r), rough) } else { Vec3::ZERO }; - let ambient = Vec3::from(s.ambient); - let subsurface = matches!(s.shader, Shader::OpenPbr | Shader::Subsurface) && c.subsurface_weight > 0.0; - let mut diff = (env_diff + ambient) * diffuse_col; - if subsurface { - // Light that enters and leaves nearby: the surface glows with the subsurface color. - let sss = (env_diff + ambient) * Vec3::from(c.subsurface_color) * (1.0 - metal); - diff = diff.lerp(sss, c.subsurface_weight); - } - let mut color = match s.shader { - Shader::Lambert => diff, - Shader::Blinn => diff + ambient * f0, - _ => { - let mut spec_tint = f0 * sa + Vec3::splat(sb); - if s.shader == Shader::OpenPbr && c.thin_film_weight > 0.0 { - let film = thin_film(c.thin_film_thickness, c.thin_film_ior, ndv); - spec_tint = spec_tint.lerp(spec_tint * film * 2.0, c.thin_film_weight); - } - diff + env_spec * spec_tint - } - }; - color *= ao; - // Direct lights (the key light and the point lights cast shadows). - let need_rays = s.ao_rays > 0 || s.key_light > 0.0 || s.lights.iter().any(|l| l.on); - if need_rays { + let spec = light.specular(rot(r), rough) * (f0 * sa + Vec3::splat(sb)); + let diff = light.diffuse(rot(n)) * diffuse_col; + let mut c = (diff + spec) * ao; + if s.ao_rays > 0 || s.key_light > 0.0 { // The true surface (a displaced scene's facets), offset to avoid self-hits. let (p0, p1, p2) = (*m.positions.get(i0)?, *m.positions.get(i1)?, *m.positions.get(i2)?); let face = (p1 - p0).cross(p2 - p0).normalize_or_zero(); let face = if face.dot(nrm) < 0.0 { -face } else { face }; let p = origin + dir * hit.t + face * scene.radius * 2e-4; if s.ao_rays > 0 { - color *= ambient_occlusion(scene, p, face, s.ao_rays, px.jitter); + c *= ambient_occlusion(scene, p, face, s.ao_rays, px.jitter); } - let mut lit = |l: Vec3, radiance: Vec3, reach: f32| { - if face.dot(l) > 0.0 && !scene.bvh.occluded(p, l, reach) { - let term = match s.shader { - Shader::Lambert => diffuse_col * n.dot(l).max(0.0) / std::f32::consts::PI, - Shader::Blinn => { - let h = (v + l).normalize_or_zero(); - let spec = n.dot(h).max(0.0).powf(blinn_exponent(rough)) * (blinn_exponent(rough) + 8.0) / (8.0 * std::f32::consts::PI); - (diffuse_col / std::f32::consts::PI + f0 * spec) * n.dot(l).max(0.0) - } - _ => direct(n, v, l, base, f0, metal, rough), - }; - color += term * radiance * ao; - } - }; - if s.key_light > 0.0 { - lit(px.key, Vec3::splat(s.key_light), f32::MAX); - } - for pl in s.lights.iter().filter(|l| l.on) { - let lp = scene.center + Vec3::from(pl.position) * scene.radius; - let to = lp - p; - let dist = to.length().max(1e-4); - let l = to / dist; - // Inverse square falloff, normalised so a light at one radius has unit power. - let radiance = Vec3::from(pl.color) * pl.intensity * (scene.radius * scene.radius) / (dist * dist) * 4.0; - lit(l, radiance, dist); + if s.key_light > 0.0 && face.dot(px.key) > 0.0 && !scene.bvh.occluded(p, px.key, f32::MAX) { + c += direct(n, v, px.key, base, f0, metal, rough) * s.key_light * ao; } } - let coat = matches!(s.shader, Shader::OpenPbr | Shader::Coated) && c.coat_weight > 0.0; - if coat { - // A dielectric layer over everything: its reflection on top, the base dimmed and tinted below. - let cf = fresnel(c.coat_ior, ndv) * c.coat_weight; - let coat_rough = c.coat_roughness.clamp(0.02, 1.0); - let coat_spec = if s.env_light { light.specular(rot(r), coat_rough) } else { Vec3::ZERO } + ambient * 0.04; - let darkening = 1.0 - c.coat_darkening * c.coat_weight * 0.25; - color = color * (1.0 - cf) * Vec3::from(c.coat_color).lerp(Vec3::ONE, 1.0 - c.coat_weight) * darkening + coat_spec * cf; + if let Some(e) = tex(&maps.emissive, uv) { + c += Vec3::new(e[0], e[1], e[2]); } - if s.shader == Shader::OpenPbr && c.fuzz_weight > 0.0 { - // Sheen: a soft rim of the fuzz color. - let rim = (1.0 - ndv).powi(3); - color += (env_diff + ambient) * Vec3::from(c.fuzz_color) * (c.fuzz_weight * (0.15 + 0.85 * rim)); - } - let mut alpha_out = if s.transparency { a } else { 1.0 }; - if s.shader == Shader::OpenPbr && c.transmission_weight > 0.0 { - // Transmission: what lies behind shows through, tinted. - color = color.lerp(color * Vec3::from(c.transmission_color), c.transmission_weight); - alpha_out *= 1.0 - c.transmission_weight * (1.0 - metal) * (1.0 - fresnel(c.ior, ndv)); - } - if let Some(e) = &maps.emissive - && s.use_map.emissive - { - let e = e.sample(uv.x, uv.y, true); - color += Vec3::new(e[0], e[1], e[2]) * c.emission_luminance.max(1.0); - } else if c.emission_luminance > 0.0 { - color += Vec3::from(c.emission_color) * c.emission_luminance; - } - Some(Shaded { color: wire(color), alpha: alpha_out, t: t_total }) + Some(Shaded { color: c, alpha: if s.transparency { a } else { 1.0 }, t: hit.t }) } /// Follow one camera ray through up to [`MAX_LAYERS`] transparent surfaces, compositing front to @@ -664,12 +444,10 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, k: f32, miss: Vec3) -> Vec3 { let mut acc = Vec3::ZERO; let mut through = 1.0; - let (tmin, mut tmax) = clip_range(scene, s); - let mut o = origin + dir * tmin; + let mut o = origin; let step = scene.radius * 1e-4; for _ in 0..MAX_LAYERS { - let Some(h) = shade(scene, maps, light, s, o, dir, px, tmax) else { return acc + miss * through }; - tmax = (tmax - h.t - step).max(0.0); + let Some(h) = shade(scene, maps, light, s, o, dir, px) else { return acc + miss * through }; acc += h.color * k * h.alpha * through; through *= 1.0 - h.alpha; if through < 1e-3 { @@ -680,14 +458,6 @@ fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec acc + miss * through } -/// The near and far clip distances along a camera ray (scene radii → world units). -fn clip_range(scene: &Scene, s: &Settings) -> (f32, f32) { - match s.clip { - Some([n, f]) if n.is_finite() && f.is_finite() && f > n => (n.max(0.0) * scene.radius, (f - n.max(0.0)) * scene.radius), - _ => (0.0, f32::MAX), - } -} - /// The studio backdrop at screen position `p` (−1..1): a soft vignette (linear). fn backdrop(p: Vec2) -> Vec3 { let t = (p.length() * 0.75).clamp(0.0, 1.0); @@ -735,16 +505,15 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett let px = (x as f32 + (sx as f32 + 0.5) / ss as f32) / w as f32 * 2.0 - 1.0; let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0; let ray = cam.ray(Vec2::new(px, py), aspect); + let bg = backdrop(Vec2::new(px, py)); let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) }; - let miss = match (s.show_env || s.background == Background::Environment, bg_env, s.background) { - (true, Some(e), _) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k, - (_, _, Background::Color(c)) => Vec3::from(c), - _ => backdrop(Vec2::new(px, py)), + let miss = match (s.show_env, bg_env) { + (true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k, + _ => bg, }; acc += if s.alpha_view { // Display values: the alpha as is, the background tone mapped. - let (tmin, tmax) = clip_range(scene, s); - match shade(scene, maps, light, s, ray.origin + ray.dir * tmin, ray.dir, &p, tmax) { + match shade(scene, maps, light, s, ray.origin, ray.dir, &p) { Some(h) => h.color, None => miss.map(|v| linear_to_srgb(aces(v))), } @@ -817,98 +586,6 @@ mod tests { Image::filled(8, 8, Kind::Gray, [value; 4]) } - /// Mean brightness of the center pixel's neighbourhood. - fn center_lum(px: &[u8], w: usize, h: usize) -> f32 { - let (cx, cy) = (w / 2, h / 2); - let mut sum = 0.0; - for y in cy - 2..cy + 2 { - for x in cx - 2..cx + 2 { - let i = (y * w + x) * 4; - sum += (px[i] as f32 + px[i + 1] as f32 + px[i + 2] as f32) / 3.0; - } - } - sum / 16.0 - } - - #[test] - fn point_lights_ambient_and_the_environment_switch_change_the_brightness() { - let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio")); - let maps = Maps { base_color: Some(Image::filled(8, 8, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() }; - let base = Settings::default(); - let plain = center_lum(&render(&scene, &maps, &light, &base, 64, 48), 64, 48); - let dark = Settings { env_light: false, ..base }; - let no_env = center_lum(&render(&scene, &maps, &light, &dark, 64, 48), 64, 48); - assert!(no_env < plain - 20.0, "no environment light leaves the sphere dark: {no_env} vs {plain}"); - let mut lit = dark; - lit.lights[0].on = true; - lit.lights[0].intensity = 4.0; - let with_light = center_lum(&render(&scene, &maps, &light, &lit, 64, 48), 64, 48); - assert!(with_light > no_env + 20.0, "a point light brightens the dark sphere: {with_light} vs {no_env}"); - let ambient = Settings { env_light: false, ambient: [0.5; 3], ..base }; - let amb = center_lum(&render(&scene, &maps, &light, &ambient, 64, 48), 64, 48); - assert!(amb > no_env + 20.0, "ambient light lifts it again: {amb} vs {no_env}"); - } - - #[test] - fn every_shader_renders_and_the_common_values_drive_unmapped_channels() { - let (scene, light) = (Scene::builtin("rounded_cube"), Lighting::new("studio")); - let maps = Maps::default(); - for (shader, _) in Shader::ALL { - let s = Settings { shader, ..Settings::default() }; - let px = render(&scene, &maps, &light, &s, 48, 32); - assert_eq!(px.len(), 48 * 32 * 4, "{shader:?}"); - } - let mut red = Settings::default(); - red.common.base_color = [0.8, 0.05, 0.05]; - let px = render(&scene, &maps, &light, &red, 64, 48); - let c = ((24 * 64 + 32) * 4) as usize; - assert!(px[c] > px[c + 1] + 30, "the common base color shows without a map: {:?}", &px[c..c + 3]); - // A map wins over the common value, unless its use is switched off. - let blue = Maps { base_color: Some(Image::filled(8, 8, Kind::Color, [0.05, 0.05, 0.8, 1.0])), ..Maps::default() }; - let px = render(&scene, &blue, &light, &red, 64, 48); - assert!(px[c + 2] > px[c] + 30, "the map wins: {:?}", &px[c..c + 3]); - let mut off = red; - off.use_map.base_color = false; - let px = render(&scene, &blue, &light, &off, 64, 48); - assert!(px[c] > px[c + 2] + 30, "use_map off falls back to the common color: {:?}", &px[c..c + 3]); - // Emission from the common values lights the surface by itself. - let mut glow = Settings { env_light: false, ..Settings::default() }; - glow.common.emission_luminance = 2.0; - glow.common.emission_color = [0.0, 1.0, 0.0]; - let px = render(&scene, &maps, &light, &glow, 64, 48); - assert!(px[c + 1] > 150 && px[c] < 60, "emission glows green: {:?}", &px[c..c + 3]); - } - - #[test] - fn background_clip_planes_wireframe_and_culling_show_in_the_frame() { - let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio")); - let maps = Maps::default(); - let corner = 0usize; - let s = Settings { background: Background::Color([0.0, 1.0, 0.0]), ..Settings::default() }; - let px = render(&scene, &maps, &light, &s, 64, 48); - assert!(px[corner + 1] > 200 && px[corner] < 40, "a flat green background: {:?}", &px[corner..corner + 3]); - // Clip planes past the sphere: only the background is left. - let s = Settings { background: Background::Color([0.0, 1.0, 0.0]), clip: Some([10.0, 12.0]), ..Settings::default() }; - let px = render(&scene, &maps, &light, &s, 64, 48); - let c = ((24 * 64 + 32) * 4) as usize; - assert!(px[c + 1] > 200 && px[c] < 40, "clipped away: {:?}", &px[c..c + 3]); - // Wireframe paints orange along the edges of a cube's twelve triangles, not everywhere. - let cube = Scene::builtin("cube"); - let s = Settings { wireframe: true, ..Settings::default() }; - let px = render(&cube, &maps, &light, &s, 96, 72); - let orange = px.chunks_exact(4).filter(|p| p[0] > 200 && p[1] > 120 && p[1] < 235 && p[2] < 60).count(); - assert!(orange > 20 && orange < 96 * 72 / 2, "wire edges drawn: {orange}"); - // Backface culling on a plane seen from below leaves the background. - let plane = Scene::builtin("plane"); - let below = - Settings { pitch: -60.0, background: Background::Color([0.0, 1.0, 0.0]), backface_culling: true, transparency: false, ..Settings::default() }; - let px = render(&plane, &maps, &light, &below, 64, 48); - assert!(px[c + 1] > 200 && px[c] < 40, "the plane's back face is culled: {:?}", &px[c..c + 3]); - let shown = Settings { backface_culling: false, ..below }; - let px = render(&plane, &maps, &light, &shown, 64, 48); - assert!(!(px[c + 1] > 200 && px[c] < 40), "without culling the back face shows: {:?}", &px[c..c + 3]); - } - fn displacement(depth: f32, level: f32) -> Displacement { Displacement { depth, level, tiling: 1.0, max_triangles: 2048, shade_relief: false } } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index cc485e5..ed7cb99 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -25,7 +25,6 @@ zip = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] sys-locale = "0.3" rfd = { workspace = true } -rayon = { workspace = true } # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b99fb84..c5a4a86 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -226,6 +226,16 @@ fn merge_json(dst: &mut Value, patch: &Value) { } pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value { + match crate::cook::guard("control request", || Ok(handle_inner(app, ctx, method, p))) { + Ok(v) => v, + Err(e) => { + app.session.dirty = false; + err(e) + } + } +} + +fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value { match method { "ping" => ok(json!("pong")), "ui.resize" => { @@ -243,22 +253,37 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") }; let params = p.get("params").cloned().unwrap_or(Value::Null); match crate::cook::guard("command request", || { - materialcraft_engine::commands::execute_request(&mut app.session, id, ¶ms).map_err(|error| error.to_string()) + Ok(materialcraft_engine::commands::execute_request(&mut app.session, id, ¶ms).map_err(|error| error.to_string())) }) { - Ok(v) => { + Ok(Ok(v)) => { if id == "view.previewSize" { app.ui.prefs.preview_size = app.session.preview_size.unwrap_or(0); } app.close_subgraph_after(id); ok(v) } - Err(e) => err(e), + Ok(Err(e)) => err(e), + Err(e) => { + app.session.dirty = false; + err(e) + } } } "command.list" => ok(materialcraft_engine::commands::list(&app.session, p.get("filter").and_then(Value::as_str))), "session.inspect" => { - app.session.cook_if_dirty(); - ok(materialcraft_engine::inspect::session(&app.session, None)) + match crate::cook::guard("session.inspect", || { + app.session.cook_if_dirty(); + if app.session.graph().is_err() { + return Err(format!("invalid graph {}", app.session.graph)); + } + Ok(materialcraft_engine::inspect::session(&app.session, None)) + }) { + Ok(v) => ok(v), + Err(e) => { + app.session.dirty = false; + err(e) + } + } } "ui.inspect" => { let rect = |r: egui::Rect| json!([r.min.x, r.min.y, r.width(), r.height()]); @@ -266,6 +291,7 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: let (view, nodes, ports) = (app.graph.view, &app.graph.rects, &app.graph.ports); ok(json!({ "state": app.ui, + "maximizedPanel": app.ui.dock.maximized(), "graphView": rect(view), "selection": app.session.selection, "inspectedNode": app.graph.inspected_node, @@ -294,6 +320,19 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::<Vec<_>>(), })) } + "ui.panel.maximize" => { + let Some(panel) = p.get("panel").cloned().and_then(|value| serde_json::from_value::<crate::docking::Panel>(value).ok()) else { + return err("`panel` must name a workspace panel, such as Graph or View2d"); + }; + + match app.ui.dock.maximize(panel) { + Ok(()) => { + ctx.request_repaint(); + ok(Value::Null) + } + Err(error) => err(error), + } + } "ui.menu.list" => ok(crate::menus::list(app)), "ui.menu.invoke" => { let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") }; @@ -391,4 +430,21 @@ mod tests { let c = &app.ui.graph_camera; assert!((c.pan[0] + 100.0 / c.zoom).is_finite()); } + + #[test] + fn session_inspect_panic_returns_error_and_resets_cook_state() { + let mut app = app(); + let ctx = egui::Context::default(); + app.session.preview_size = Some(64); + app.session.cook(); + let valid_graph = app.session.graph; + app.session.graph = app.session.graph.wrapping_add(1_000); + app.session.dirty = true; + let r = handle(&mut app, &ctx, "session.inspect", &json!({})); + assert_eq!(r["ok"], json!(false), "{r}"); + assert!(!app.session.dirty, "cook state not reset after panic: dirty={}", app.session.dirty); + app.session.graph = valid_graph; + let r = handle(&mut app, &ctx, "session.inspect", &json!({})); + assert_eq!(r["ok"], json!(true), "{r}"); + } } diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index 53c9c72..07f8908 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -13,7 +13,11 @@ use crate::MaterialCraftApp; /// the app (and unsaved work) down pub fn guard<T>(what: &str, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> { catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|p| { - let msg = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_default(); + let msg = p + .downcast_ref::<&str>() + .map(|s| s.to_string()) + .or_else(|| p.downcast_ref::<String>().cloned()) + .unwrap_or_else(|| "unknown panic payload".to_string()); Err(format!("internal error in {what}: {msg}")) }) } @@ -45,58 +49,12 @@ pub struct Cooker { pub started: Option<f64>, /// `Session::cook_epoch` when the running cook started epoch: u64, - /// Tools ▸ Suspend engine: no cook starts until resumed - pub suspended: bool, - /// Tools ▸ Cancel rendering: the running cook stops and nothing restarts until the next edit - pub hold: bool, - /// Tools ▸ Switch engine: worker threads for the cook (0 = all the cores) - pub threads: usize, - #[cfg(not(target_arch = "wasm32"))] - pool: Option<(usize, std::sync::Arc<rayon::ThreadPool>)>, -} - -/// Stop the running cook (Tools ▸ Cancel rendering). The graph stays as it was until the -/// next edit computes it again -pub fn cancel(app: &mut MaterialCraftApp) { - #[cfg(not(target_arch = "wasm32"))] - if let Some(flag) = &app.cooker.cancel { - flag.store(true, std::sync::atomic::Ordering::Relaxed); - } - app.cooker.hold = true; - app.session.dirty = false; } impl Cooker { pub fn busy(&self) -> bool { self.rx.is_some() } - - /// The cook's thread pool for the chosen thread count (built once per count); `None` runs - /// on the global pool (all the cores) - #[cfg(not(target_arch = "wasm32"))] - fn pool(&mut self) -> Option<std::sync::Arc<rayon::ThreadPool>> { - let n = self.threads; - if n == 0 { - self.pool = None; - return None; - } - if let Some((have, p)) = &self.pool - && *have == n - { - return Some(p.clone()); - } - match rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("materialcraft-cook-{i}")).build() { - Ok(p) => { - let p = std::sync::Arc::new(p); - self.pool = Some((n, p.clone())); - Some(p) - } - Err(e) => { - log::warn!("could not build a {n}-thread pool ({e}); using every core"); - None - } - } - } } /// Collect a finished cook and start the next one if the graph changed @@ -112,9 +70,8 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { } match result { // A stopped cook is partial: keep the previous results and cook again - // (unless the user cancelled it: then wait for the next edit) Ok(c) if c.cancelled() => { - if app.cooker.epoch == app.session.cook_epoch && !app.cooker.hold { + if app.cooker.epoch == app.session.cook_epoch { app.session.dirty = true; } } @@ -155,8 +112,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } } - if app.session.dirty && !app.cooker.suspended { - app.cooker.hold = false; + if app.session.dirty { start(app, ctx.input(|i| i.time)); ctx.request_repaint(); } @@ -167,7 +123,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let s = &mut app.session; s.dirty = false; let pkg = s.pkg.clone(); - let (gi, max) = (s.graph, s.cook_size(s.preview_size)); + let (gi, max) = (s.graph, s.preview_size); let materials = s.material_preview.graphs(); let cache = s.cache.clone(); let epoch = s.cook_epoch; @@ -175,20 +131,12 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let (tx, rx) = std::sync::mpsc::channel(); let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let thread_flag = flag.clone(); - let pool = app.cooker.pool(); use materialcraft_engine::eval::Options; let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || { - let run = || { - let mut opts = Options::new(&dec); - opts.max_size = max; - opts.cancel = Some(&thread_flag); - guard("cook", || Ok(PreviewCook::run(&pkg, gi, &materials, &opts, &cache))) - }; - // A pool of the chosen size keeps the cook's parallel work to that many threads - let cooked = match pool { - Some(p) => p.install(run), - None => run(), - }; + let mut opts = Options::new(&dec); + opts.max_size = max; + opts.cancel = Some(&thread_flag); + let cooked = guard("cook", || Ok(PreviewCook::run(&pkg, gi, &materials, &opts, &cache))); let _ = tx.send(cooked); }); match spawned { diff --git a/crates/ui-egui/src/cook.test.rs b/crates/ui-egui/src/cook.test.rs index 8438ced..c4e80b4 100644 --- a/crates/ui-egui/src/cook.test.rs +++ b/crates/ui-egui/src/cook.test.rs @@ -61,6 +61,14 @@ mod worker_failure_tests { assert_eq!(guard("test", || Ok::<_, String>(7)).unwrap(), 7); } + #[test] + fn guard_reports_unknown_panic_payload_instead_of_empty() { + let r: Result<u32, String> = guard("test", || -> Result<u32, String> { std::panic::panic_any(42) }); + let e = r.unwrap_err(); + assert!(e.contains("unknown"), "{e}"); + assert!(!e.trim_end().ends_with(':'), "{e}"); + } + #[test] fn a_panicked_cook_worker_reports_errors_on_every_node() { let mut app = app(); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index fa53a13..af6b022 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -1,336 +1,74 @@ -//! The dock host: every panel (explorer, library, graph, 3D view, 2D view, properties, console, -//! history) is a tab that can be docked, tabbed, resized, floated and closed. craft-ui's shared -//! docking (`craft_ui::docking`) draws the frames, tab strips, floating windows and drop previews -//! and owns the gestures; this module names the panels, builds the default arrangement, applies -//! the dock's changes and hosts the panel bodies. -//! -//! The graph is the central canvas: it stays docked, never takes tabs and is the only panel that -//! cannot close or float. The layout persists with `UiState` as a craft-ui `Workspace`; a layout -//! that does not load or validate becomes the default. +//! Panel hosting, workspace validation and transient maximization -use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement}; -use craft_ui::layout::{SplitAxis, SplitSize}; -use egui::{Id, Margin, RichText, Ui, vec2}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; +mod dock; +mod maximization; +mod panel; +mod panel_content; +mod workspace; -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; +pub use dock::Dock; +pub use panel::{Panel, VIEWS, view_panel}; +pub use workspace::{Workspace, default_workspace, permissions, validate}; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Panel { - Graph, - Explorer, - Library, - View3d, - View2d, - Properties, - Console, - History, -} +use craft_ui::docking::{DockArea, DockStyle}; +use egui::{Id, Ui}; -/// Windows menu items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 7] = [ - ("ui.view.explorer", Panel::Explorer), - ("ui.view.properties", Panel::Properties), - ("ui.view.console", Panel::Console), - ("ui.view.3d", Panel::View3d), - ("ui.view.2d", Panel::View2d), - ("ui.view.library", Panel::Library), - ("ui.view.history", Panel::History), -]; - -/// The panel a Windows menu item toggles. -pub fn view_panel(id: &str) -> Option<Panel> { - VIEWS.iter().find(|(v, _)| *v == id).map(|(_, p)| *p) -} - -impl Panel { - pub const ALL: [Panel; 8] = - [Panel::Graph, Panel::Explorer, Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Console, Panel::History]; - - pub fn name(self) -> &'static str { - match self { - Panel::Graph => "Graph", - Panel::Explorer => "Explorer", - Panel::Library => "Library", - Panel::View3d => "3D View", - Panel::View2d => "2D View", - Panel::Properties => "Properties", - Panel::Console => "Console", - Panel::History => "History", - } - } - - /// Where the panel floats when it has never been laid out: `[x, y, width, height]`, cascaded. - fn float_rect(self) -> Option<[f32; 4]> { - let slot = match self { - Panel::Console => 0.0, - Panel::History => 1.0, - _ => return None, - }; - Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0]) - } -} - -/// The saved panel arrangement: craft-ui's workspace over MaterialCraft's panels. -pub type Workspace = craft_ui::docking::Workspace<Panel>; - -/// The graph never moves, floats, closes or takes tabs; panels dock beside it. -pub fn permissions(panel: &Panel) -> Permissions { - if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() } -} - -fn tabs(panels: &[Panel]) -> Node<Panel> { - Node::Tabs { panels: panels.to_vec(), active: 0 } -} - -fn split(axis: SplitAxis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> { - Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) } -} - -/// The default: explorer over library on the left; the graph over the 3D and 2D views in the -/// middle; properties on the right. Console and history are closed and open floating. -pub fn default_workspace() -> Workspace { - use Panel::*; - let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library])); - let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d])); - let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views); - let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 0.8, center, tabs(&[Properties]))); - let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); - for panel in Panel::ALL { - if let Some(rect) = panel.float_rect() { - let location = Location { - floating: Some(rect), - anchor: None, - placement: Placement::Tab { before: None }, - size: None, - stack: None, - sibling: Vec::new(), - group: None, - }; - workspace.hidden.push((panel, location)); - } - } - workspace -} - -/// craft-ui's checks plus the graph's: a saved or hand-edited file cannot hide, float, group -/// or collapse it. -pub fn validate(workspace: &Workspace) -> Result<(), String> { - workspace.validate().map_err(|error| error.to_string())?; - let layout = &workspace.layout; - if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) { - return Err("The graph cannot float".into()); - } - if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) { - return Err("The graph cannot be hidden".into()); - } - let mut found = false; - let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect(); - while let Some(node) = nodes.pop() { - match node { - Node::Split { first, second, .. } => { - nodes.push(first); - nodes.push(second); - } - Node::Tabs { panels, .. } if panels.contains(&Panel::Graph) => { - if panels.len() != 1 { - return Err("The graph cannot share a tab group".into()); - } - found = true; - } - Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => { - return Err("The graph cannot be collapsed".into()); - } - Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => { - return Err("The graph cannot be in a dock".into()); - } - _ => {} - } - } - if found { Ok(()) } else { Err("The panel layout must contain the graph".into()) } -} - -// --------------------------------------------------------------------------------------------- -// The live dock - -/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`). -#[derive(Clone, Debug)] -pub struct Dock { - workspace: Workspace, - /// A panel to bring in front of the other floating windows on the next frame. - raise: Option<Panel>, - /// A panel shown alone over the whole dock (Shift+Space on a panel; Windows ▸ Unmaximize - /// window). Not saved with the layout. - pub maximized: Option<Panel>, - /// The panel under the pointer on the last frame (the one Shift+Space maximizes). - pub hovered: Option<Panel>, -} - -impl Default for Dock { - fn default() -> Self { - Dock { workspace: default_workspace(), raise: None, maximized: None, hovered: None } - } -} - -impl PartialEq for Dock { - fn eq(&self, other: &Self) -> bool { - self.workspace == other.workspace - } -} - -impl Serialize for Dock { - fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { - self.workspace.serialize(s) - } -} - -impl<'de> Deserialize<'de> for Dock { - /// Never fails: a layout that cannot be read or fails the graph's rules is the default. - fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { - Ok(Dock::from_value(Value::deserialize(d)?)) - } -} - -impl Dock { - /// The dock for a saved layout; the default when it is not a valid workspace. - pub fn from_value(value: Value) -> Dock { - let default = default_workspace(); - let loaded = serde_json::from_value::<Workspace>(value).ok(); - let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return Dock::default() }; - workspace.reconcile(|_| true, permissions, &default); - if validate(&workspace).is_err() { - return Dock::default(); - } - Dock { workspace, raise: None, maximized: None, hovered: None } - } - - pub fn workspace(&self) -> &Workspace { - &self.workspace - } - - pub fn is_open(&self, p: Panel) -> bool { - self.workspace.layout.contains(&p) - } - - /// Open and the front tab of its group. - pub fn is_visible(&self, p: Panel) -> bool { - self.workspace.layout.panel_state(&p) == PanelState::Front - } - - /// Hide a visible panel, otherwise bring it up. - pub fn toggle(&mut self, p: Panel) { - if self.is_visible(p) { self.close(p) } else { self.focus(p) } - } - - pub fn close(&mut self, p: Panel) { - if let Err(error) = self.workspace.set_visible(p, false, None, permissions) { - log::warn!("panel {p:?} was not closed: {error}"); - } - } - - /// Open `p` (where it was when closed, else where it lives by default) and bring it to the - /// front. - pub fn focus(&mut self, p: Panel) { - let mut next = self.workspace.clone(); - match next.set_visible(p, true, None, permissions) { - Ok(()) if validate(&next).is_ok() => { - self.workspace = next; - self.raise = Some(p); - } - Ok(()) => log::warn!("panel {p:?} was not opened: it would break the graph's rules"), - Err(error) => log::warn!("panel {p:?} was not opened: {error}"), - } - } - - /// One change from the dock area's gestures. A change that is rejected leaves the layout as - /// it was. - fn apply(&mut self, action: Action<Panel>) { - let mut next = self.workspace.clone(); - match next.apply(action, permissions) { - Ok(_) if validate(&next).is_ok() => self.workspace = next, - Ok(_) => log::warn!("a panel move would break the graph's rules"), - Err(error) => log::warn!("a panel move was not applied: {error}"), - } - } -} - -// --------------------------------------------------------------------------------------------- -// Drawing +use crate::{MaterialCraftApp, theme::Tokens}; +use panel_content::PanelContent; fn area_id() -> Id { Id::unique("materialcraft-docking") } -/// The dock look: every panel group is a card on the window's frame colour, its tab strip -/// without hard lines, the shown tab a pill, uppercase captions. -fn style(ui: &Ui, t: &Tokens) -> DockStyle { - let mut s = DockStyle::from_ui(ui); - s.gap = 6.0; - // Smallest panel extent a divider drag leaves. - s.min_pane = 60.0; - s.background = t.panel; - s.tab_background = t.panel; - s.active_background = t.button; - s.text = t.text_strong; - s.inactive_text = t.text_dim; - s.border = egui::Stroke::NONE; - s.accent = t.accent; - s.floating_background = t.panel; - s.floating_stroke = egui::Stroke::new(1.0, t.button_border); - s.font = egui::FontId::proportional(10.5); - s.min_tab_width = 54.0; - s.tab_height = 30.0; - // Panels arrange in a split tree around the graph; floating title bars only move windows. - s.new_dock_zones = false; - s.title_bar_docks = false; - s +/// Shared appearance for docked and floating panels +fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { + let mut style = DockStyle::from_ui(ui); + style.gap = 6.0; + // Smallest panel extent a divider drag leaves + style.min_pane = 60.0; + style.background = tokens.panel; + style.tab_background = tokens.panel; + style.active_background = tokens.button; + style.text = tokens.text_strong; + style.inactive_text = tokens.text_dim; + style.border = egui::Stroke::NONE; + style.accent = tokens.accent; + style.floating_background = tokens.panel; + style.floating_stroke = egui::Stroke::new(1.0, tokens.button_border); + style.font = egui::FontId::proportional(10.5); + style.min_tab_width = 54.0; + style.tab_height = 30.0; + // Floating title bars move windows without creating new docks + style.new_dock_zones = false; + style.title_bar_docks = false; + style } -/// Draw the dock (graph and panels) into `ui`. +/// Draw the saved workspace or its maximized panel pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let ctx = ui.ctx().clone(); - let tk = Tokens::get(&ctx); - // Shift+Space maximizes the panel under the pointer, or brings the layout back. - if !ctx.egui_wants_keyboard_input() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::Space)) { - app.ui.dock.maximized = match app.ui.dock.maximized { - Some(_) => None, - None => app.ui.dock.hovered, - }; + let context = ui.ctx().clone(); + if app.ui.dock.maximized().is_some() && maximization::consume_shortcut(&context) { + app.ui.dock.restore(); } - if let Some(panel) = app.ui.dock.maximized { - let title = Panels { app: &mut *app }.logical_label(&panel); - egui::Frame::NONE.fill(tk.panel).show(ui, |ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(title).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.small_button(tr("Unmaximize (Shift+Space)")).clicked() { - app.ui.dock.maximized = None; - } - }); - }); - let rect = ui.available_rect_before_wrap(); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); - Panels { app }.body(&mut child, &panel); - }); + if let Some(panel) = app.ui.dock.maximized() { + maximization::show(app, ui, panel); return; } - let style = style(ui, &tk); + + let tokens = Tokens::get(&context); + let style = style(ui, &tokens); let layout = app.ui.dock.workspace.layout.clone(); - let mut area = DockArea::new(area_id()).input_blocked(ctx.memory(|m| m.top_modal_layer()).is_some()); + let mut area = DockArea::new(area_id()).input_blocked(context.memory(|m| m.top_modal_layer()).is_some()); if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app }); + let output = area.show_content(ui, &layout, &style, &mut PanelContent { app }); if let Some(error) = &output.error { log::warn!("docking: {error}"); } - // A body that changed the layout (a panel opened from its own menu) wins over this frame's - // gestures, which were made against the old one. - if app.ui.dock.workspace.layout != layout { - craft_ui::docking::cancel_drag::<Panel>(&ctx, area_id()); + // Panel actions take priority over gestures against the previous layout + if app.ui.dock.workspace.layout != layout || app.ui.dock.maximized().is_some() { + craft_ui::docking::cancel_drag::<Panel>(&context, area_id()); return; } for action in output.actions { @@ -338,62 +76,6 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } } -/// The panels' contents, names and limits for the dock area. -struct Panels<'a> { - app: &'a mut MaterialCraftApp, -} - -impl DockContent<Panel> for Panels<'_> { - fn body(&mut self, ui: &mut Ui, panel: &Panel) { - let app = &mut *self.app; - if ui.rect_contains_pointer(ui.max_rect()) { - app.ui.dock.hovered = Some(*panel); - } - match panel { - Panel::Graph => crate::graph::show(app, ui), - Panel::View3d => crate::view3d::show(app, ui), - Panel::View2d => crate::view2d::show(app, ui), - _ => { - egui::Frame::new().inner_margin(Margin::symmetric(6, 4)).show(ui, |ui| match panel { - Panel::Explorer => crate::explorer::show(app, ui), - Panel::Library => crate::library::show(app, ui), - Panel::Properties => crate::properties::show(app, ui), - Panel::Console => crate::windows::console(app, ui), - Panel::History => crate::windows::history(app, ui), - _ => {} - }); - } - } - } - - fn logical_label(&self, panel: &Panel) -> String { - match panel { - Panel::Properties => crate::properties::title(self.app), - Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()), - Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")), - Panel::View2d => crate::view2d::title(self.app), - p => tr(p.name()).to_string(), - } - } - - fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into() - } - - fn permissions(&self, panel: &Panel) -> Permissions { - permissions(panel) - } - - fn limits(&self, panel: &Panel) -> PanelLimits { - let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) }; - PanelLimits { min, ..PanelLimits::default() } - } - - fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> { - Some(vec2(420.0, 320.0)) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/docking/dock.rs b/crates/ui-egui/src/docking/dock.rs new file mode 100644 index 0000000..fdd9dac --- /dev/null +++ b/crates/ui-egui/src/docking/dock.rs @@ -0,0 +1,122 @@ +use craft_ui::docking::{Action, PanelState}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::{Panel, Workspace, default_workspace, permissions, validate}; + +/// Saved workspace and transient panel presentation +#[derive(Clone, Debug)] +pub struct Dock { + pub(super) workspace: Workspace, + pub(super) raise: Option<Panel>, + maximized: Option<Panel>, +} + +impl Default for Dock { + fn default() -> Self { + Self { workspace: default_workspace(), raise: None, maximized: None } + } +} + +impl PartialEq for Dock { + fn eq(&self, other: &Self) -> bool { + self.workspace == other.workspace + } +} + +impl Serialize for Dock { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + self.workspace.serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for Dock { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + Ok(Self::from_value(Value::deserialize(deserializer)?)) + } +} + +impl Dock { + /// Invalid layouts fall back to the default workspace + pub fn from_value(value: Value) -> Self { + let default = default_workspace(); + let loaded = serde_json::from_value::<Workspace>(value).ok(); + let Some(mut workspace) = loaded.filter(|workspace| validate(workspace).is_ok()) else { + return Self::default(); + }; + + workspace.reconcile(|_| true, permissions, &default); + if validate(&workspace).is_err() { + return Self::default(); + } + Self { workspace, raise: None, maximized: None } + } + + pub fn workspace(&self) -> &Workspace { + &self.workspace + } + + pub fn maximized(&self) -> Option<Panel> { + self.maximized + } + + /// Maximization never alters the saved layout or opens hidden panels + pub fn maximize(&mut self, panel: Panel) -> Result<(), String> { + if self.workspace.layout.panel_state(&panel) != PanelState::Front { + return Err(format!("{} must be an open, active panel before maximizing", panel.name())); + } + self.maximized = Some(panel); + Ok(()) + } + + pub fn restore(&mut self) { + self.maximized = None; + } + + pub fn is_open(&self, panel: Panel) -> bool { + self.workspace.layout.contains(&panel) + } + + pub fn is_visible(&self, panel: Panel) -> bool { + self.maximized.map_or_else(|| self.workspace.layout.panel_state(&panel) == PanelState::Front, |maximized| maximized == panel) + } + + /// Hide a visible panel or bring it into view + pub fn toggle(&mut self, panel: Panel) { + if self.is_visible(panel) { self.close(panel) } else { self.focus(panel) } + } + + pub fn close(&mut self, panel: Panel) { + match self.workspace.set_visible(panel, false, None, permissions) { + Ok(()) if self.maximized == Some(panel) => self.restore(), + Ok(()) => {} + Err(error) => log::warn!("panel {panel:?} was not closed: {error}"), + } + } + + /// Reveal the requested panel in its existing location + pub fn focus(&mut self, panel: Panel) { + let mut next = self.workspace.clone(); + match next.set_visible(panel, true, None, permissions) { + Ok(()) if validate(&next).is_ok() => { + self.workspace = next; + self.raise = Some(panel); + if self.maximized != Some(panel) { + self.restore(); + } + } + Ok(()) => log::warn!("panel {panel:?} was not opened: it would break the graph's rules"), + Err(error) => log::warn!("panel {panel:?} was not opened: {error}"), + } + } + + /// Rejected gestures leave the layout intact + pub(super) fn apply(&mut self, action: Action<Panel>) { + let mut next = self.workspace.clone(); + match next.apply(action, permissions) { + Ok(_) if validate(&next).is_ok() => self.workspace = next, + Ok(_) => log::warn!("a panel move would break the graph's rules"), + Err(error) => log::warn!("a panel move was not applied: {error}"), + } + } +} diff --git a/crates/ui-egui/src/docking/maximization.rs b/crates/ui-egui/src/docking/maximization.rs new file mode 100644 index 0000000..12f1d57 --- /dev/null +++ b/crates/ui-egui/src/docking/maximization.rs @@ -0,0 +1,39 @@ +use craft_ui::docking::DockContent; +use egui::{Context, Key, Modifiers, RichText, Ui}; + +use super::{Panel, panel_content::PanelContent}; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; + +pub(super) fn consume_shortcut(context: &Context) -> bool { + if context.egui_wants_keyboard_input() + || egui::Popup::is_any_open(context) + || context.memory(|memory| memory.top_modal_layer()).is_some() + || context.input(|input| input.pointer.any_down()) + { + return false; + } + context.input_mut(|input| input.consume_key(Modifiers::SHIFT, Key::Space)) +} + +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, panel: Panel) { + let tokens = Tokens::get(ui.ctx()); + let title = PanelContent { app }.logical_label(&panel); + egui::Frame::NONE.fill(tokens.panel).show(ui, |ui| { + ui.set_min_size(ui.available_size()); + ui.horizontal(|ui| { + ui.label(RichText::new(title.to_uppercase()).size(10.5).strong().color(tokens.text_strong)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.small_button(tr("Restore panel layout")).on_hover_text("Shift+Space").clicked() { + crate::menus::invoke(app, ui.ctx(), "ui.unmaximize"); + } + }); + }); + let rectangle = ui.available_rect_before_wrap(); + // Match the dock host's scope so widget state survives maximizing and restoring + let mut body = ui.new_child( + egui::UiBuilder::new().scope_id(super::area_id().with(("body", &panel))).max_rect(rectangle).layout(egui::Layout::top_down(egui::Align::Min)), + ); + body.set_clip_rect(rectangle.intersect(ui.clip_rect())); + PanelContent { app }.body(&mut body, &panel); + }); +} diff --git a/crates/ui-egui/src/docking/panel.rs b/crates/ui-egui/src/docking/panel.rs new file mode 100644 index 0000000..1689d87 --- /dev/null +++ b/crates/ui-egui/src/docking/panel.rs @@ -0,0 +1,57 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Panel { + Graph, + Explorer, + Library, + View3d, + View2d, + Properties, + Console, + History, +} + +/// Windows menu items and the panels they show or hide +pub const VIEWS: [(&str, Panel); 7] = [ + ("ui.view.explorer", Panel::Explorer), + ("ui.view.properties", Panel::Properties), + ("ui.view.console", Panel::Console), + ("ui.view.3d", Panel::View3d), + ("ui.view.2d", Panel::View2d), + ("ui.view.library", Panel::Library), + ("ui.view.history", Panel::History), +]; + +/// The panel a Windows menu item toggles +pub fn view_panel(id: &str) -> Option<Panel> { + VIEWS.iter().find(|(v, _)| *v == id).map(|(_, p)| *p) +} + +impl Panel { + pub const ALL: [Panel; 8] = + [Panel::Graph, Panel::Explorer, Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Console, Panel::History]; + + pub fn name(self) -> &'static str { + match self { + Panel::Graph => "Graph", + Panel::Explorer => "Explorer", + Panel::Library => "Library", + Panel::View3d => "3D View", + Panel::View2d => "2D View", + Panel::Properties => "Properties", + Panel::Console => "Console", + Panel::History => "History", + } + } + + /// Initial floating rectangle in points: `[x, y, width, height]` + pub(super) fn float_rect(self) -> Option<[f32; 4]> { + let slot = match self { + Panel::Console => 0.0, + Panel::History => 1.0, + _ => return None, + }; + Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0]) + } +} diff --git a/crates/ui-egui/src/docking/panel_content.rs b/crates/ui-egui/src/docking/panel_content.rs new file mode 100644 index 0000000..5c36e1a --- /dev/null +++ b/crates/ui-egui/src/docking/panel_content.rs @@ -0,0 +1,65 @@ +use craft_ui::docking::{DockContent, PanelLimits, Permissions}; +use egui::{Margin, RichText, Ui, vec2}; + +use super::{Panel, permissions}; +use crate::{MaterialCraftApp, i18n::tr}; + +/// Panel bodies, titles and sizing constraints +pub(super) struct PanelContent<'a> { + pub(super) app: &'a mut MaterialCraftApp, +} + +impl DockContent<Panel> for PanelContent<'_> { + fn body(&mut self, ui: &mut Ui, panel: &Panel) { + let app = &mut *self.app; + if app.ui.dock.maximized().is_none() && ui.rect_contains_pointer(ui.max_rect()) && super::maximization::consume_shortcut(ui.ctx()) { + if let Err(error) = app.ui.dock.maximize(*panel) { + log::warn!("panel was not maximized: {error}"); + } + ui.ctx().request_repaint(); + } + + match panel { + Panel::Graph => crate::graph::show(app, ui), + Panel::View3d => crate::view3d::show(app, ui), + Panel::View2d => crate::view2d::show(app, ui), + _ => { + egui::Frame::new().inner_margin(Margin::symmetric(6, 4)).show(ui, |ui| match panel { + Panel::Explorer => crate::explorer::show(app, ui), + Panel::Library => crate::library::show(app, ui), + Panel::Properties => crate::properties::show(app, ui), + Panel::Console => crate::windows::console(app, ui), + Panel::History => crate::windows::history(app, ui), + _ => {} + }); + } + } + } + + fn logical_label(&self, panel: &Panel) -> String { + match panel { + Panel::Properties => crate::properties::title(self.app), + Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()), + Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")), + Panel::View2d => crate::view2d::title(self.app), + p => tr(p.name()).to_string(), + } + } + + fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { + RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into() + } + + fn permissions(&self, panel: &Panel) -> Permissions { + permissions(panel) + } + + fn limits(&self, panel: &Panel) -> PanelLimits { + let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) }; + PanelLimits { min, ..PanelLimits::default() } + } + + fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> { + Some(vec2(420.0, 320.0)) + } +} diff --git a/crates/ui-egui/src/docking/workspace.rs b/crates/ui-egui/src/docking/workspace.rs new file mode 100644 index 0000000..cddb451 --- /dev/null +++ b/crates/ui-egui/src/docking/workspace.rs @@ -0,0 +1,81 @@ +use craft_ui::docking::{Layout, Location, Node, Permissions, Placement}; +use craft_ui::layout::{SplitAxis, SplitSize}; + +use super::Panel; + +/// The saved panel arrangement +pub type Workspace = craft_ui::docking::Workspace<Panel>; + +/// The graph stays docked and separate from other tabs +pub fn permissions(panel: &Panel) -> Permissions { + if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() } +} + +fn tabs(panels: &[Panel]) -> Node<Panel> { + Node::Tabs { panels: panels.to_vec(), active: 0 } +} + +fn split(axis: SplitAxis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> { + Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) } +} + +/// Default workspace with console and history initially hidden +pub fn default_workspace() -> Workspace { + use Panel::*; + let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library])); + let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d])); + let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views); + let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 0.8, center, tabs(&[Properties]))); + let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); + for panel in Panel::ALL { + if let Some(rect) = panel.float_rect() { + let location = Location { + floating: Some(rect), + anchor: None, + placement: Placement::Tab { before: None }, + size: None, + stack: None, + sibling: Vec::new(), + group: None, + }; + workspace.hidden.push((panel, location)); + } + } + workspace +} + +/// Validate the workspace and protect the central graph panel +pub fn validate(workspace: &Workspace) -> Result<(), String> { + workspace.validate().map_err(|error| error.to_string())?; + let layout = &workspace.layout; + if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) { + return Err("The graph cannot float".into()); + } + if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) { + return Err("The graph cannot be hidden".into()); + } + let mut found = false; + let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect(); + while let Some(node) = nodes.pop() { + match node { + Node::Split { first, second, .. } => { + nodes.push(first); + nodes.push(second); + } + Node::Tabs { panels, .. } if panels.contains(&Panel::Graph) => { + if panels.len() != 1 { + return Err("The graph cannot share a tab group".into()); + } + found = true; + } + Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => { + return Err("The graph cannot be collapsed".into()); + } + Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => { + return Err("The graph cannot be in a dock".into()); + } + _ => {} + } + } + if found { Ok(()) } else { Err("The panel layout must contain the graph".into()) } +} diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 01046b1..1d22730 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -1,15 +1,11 @@ -//! The package tree, its graphs, inputs, outputs and resources, each with a context menu +//! The package tree, its graphs, inputs, outputs and resources -use egui::{RichText, Sense, Ui}; +use egui::{RichText, Ui}; -mod actions; -mod package_menu; mod tree_row; use egui_phosphor::regular as icon; use serde_json::json; -pub use actions::{GraphClipboard, Rename}; - use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::Tokens; @@ -35,59 +31,16 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); ui.add_space(2.0); - let mut menu_pick: Option<&'static str> = None; - let mut resource_action: Option<(&str, usize)> = None; - let mut rename_done: Option<(usize, Option<String>)> = None; egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let name = format!("{}{}", app.session.pkg.name, if app.session.modified { "*" } else { "" }); - let package_row = tree_row::show(ui, &name, icon::PACKAGE, false); - if let Some(path) = &app.session.path { - package_row.clone().on_hover_text(path); - } - package_row.context_menu(|ui| { - if let Some(id) = package_menu::show(app, ui) { - menu_pick = Some(id); - } - }); + ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong)); let mut open: Option<usize> = None; let mut action: Option<(&str, usize)> = None; let mut selected_node = None; let mut assignment = None; - let renaming = app.explorer_rename.0.clone(); - let can_paste = app.explorer_clipboard.0.is_some(); - // Keyboard over the tree: F2 renames the open graph, Delete removes it - if ui.ui_contains_pointer() && renaming.is_none() && !ui.ctx().egui_wants_keyboard_input() { - let gi = app.session.graph; - ui.input(|i| { - if i.key_pressed(egui::Key::F2) { - action = Some(("rename", gi)); - } else if i.key_pressed(egui::Key::Delete) { - action = Some(("delete", gi)); - } - }); - } for (index, graph) in app.session.pkg.graphs.iter().enumerate() { let active = index == app.session.graph; let function = graph.function.is_some(); - // Rename in place (F2 / the context menu) - if let Some((ri, mut text)) = renaming.clone() - && ri == index - { - let resp = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 24.0)); - if !resp.has_focus() && !resp.lost_focus() { - resp.request_focus(); - } - let enter = ui.input(|inp| inp.key_pressed(egui::Key::Enter)); - let escape = ui.input(|inp| inp.key_pressed(egui::Key::Escape)); - if escape { - rename_done = Some((index, None)); - } else if resp.lost_focus() || enter { - rename_done = Some((index, Some(text.clone()))); - } else if resp.changed() { - app.explorer_rename.0 = Some((index, text)); - } - continue; - } let mut header = |ui: &mut Ui| { let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE }; let response = tree_row::show(ui, &graph.name, symbol, active); @@ -105,19 +58,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ui.close(); } } - ui.separator(); } - for (label, command, key, enabled) in [ - ("Open", "open", "Return", true), - ("Copy", "copy", "", true), - ("Paste", "paste", "", can_paste), - ("Remove", "delete", "Del", true), - ("Rename", "rename", "F2", true), - ("Duplicate", "duplicate", "", true), - ("Compute Outputs", "compute", "", true), - ("Export outputs...", "export", "", true), - ] { - if crate::menus::menu_row(ui, tr(label), key, enabled).clicked() { + for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] { + if ui.button(tr(label)).clicked() { action = Some((command, index)); ui.close(); } @@ -198,71 +141,14 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { Some(("delete", i)) => { app.run("graph.delete", json!({"graph": i})); } - Some(("copy", i)) => actions::copy_graph(app, ui.ctx(), i), - Some(("paste", _)) => actions::paste_graph(app), - Some(("rename", i)) => { - if let Some(g) = app.session.pkg.graphs.get(i) { - app.explorer_rename.0 = Some((i, g.name.clone())); - } - } - Some(("compute", i)) if app.run("graph.open", json!({"graph": i})).is_some() => actions::compute(app), _ => {} } if !app.session.pkg.resources.is_empty() { ui.add_space(6.0); ui.label(RichText::new(tr("Resources")).color(tk.text_dim).size(11.0)); - for (i, r) in app.session.pkg.resources.iter().enumerate() { - let linked = r.link.is_some(); - let text = format!("{} {} ({} KB)", if linked { icon::LINK } else { icon::IMAGE }, r.name, r.bytes.len() / 1024); - let hover = match &r.link { - Some(l) => format!("{} {l}", tr("Linked:")), - None => tr("Embedded in the package").to_string(), - }; - let resp = ui.add(egui::Label::new(text).sense(Sense::click())).on_hover_text(hover); - resp.context_menu(|ui| { - if linked && ui.button(tr("Relink...")).clicked() { - resource_action = Some(("relink", i)); - ui.close(); - } - if ui.button(tr("Add a Bitmap node")).clicked() { - resource_action = Some(("node", i)); - ui.close(); - } - if ui.button(tr("Remove")).clicked() { - resource_action = Some(("delete", i)); - ui.close(); - } - }); + for r in &app.session.pkg.resources { + ui.label(format!("{} {} ({} KB)", icon::IMAGE, r.name, r.bytes.len() / 1024)); } } }); - if let Some((i, text)) = rename_done { - let old = app.session.pkg.graphs.get(i).map(|g| g.name.clone()).unwrap_or_default(); - app.explorer_rename.0 = None; - if let Some(new) = text.map(|t| t.trim().to_string()).filter(|t| !t.is_empty() && *t != old) { - app.run("graph.rename", json!({"graph": i, "name": new})); - } - } - match menu_pick { - Some("explorer.copy") => actions::copy_graph(app, ui.ctx(), app.session.graph), - Some("explorer.paste") => actions::paste_graph(app), - Some("explorer.compute") => actions::compute(app), - Some("explorer.reveal") => actions::reveal(app), - Some(id) => crate::menus::invoke(app, ui.ctx(), id), - None => {} - } - match resource_action { - Some(("delete", i)) => { - if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) { - app.run("file.deleteResource", json!({"name": name})); - } - } - Some(("node", i)) => { - if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) { - app.run("graph.node.add", json!({"def": "bitmap", "params": {"resource": name}})); - } - } - Some(("relink", i)) => actions::relink(app, i), - _ => {} - } } diff --git a/crates/ui-egui/src/explorer/actions.rs b/crates/ui-egui/src/explorer/actions.rs deleted file mode 100644 index 08dc553..0000000 --- a/crates/ui-egui/src/explorer/actions.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! What the explorer's menus do beyond running a command: copy and paste whole graphs, compute -//! the outputs again, reveal the package file, relink a bitmap - -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; - -/// A graph on the explorer's clipboard (Copy / Paste a graph) -#[derive(Clone, Debug, Default)] -pub struct GraphClipboard(pub Option<serde_json::Value>); - -/// Rename-in-place state: the graph index and the text being edited -#[derive(Clone, Debug, Default)] -pub struct Rename(pub Option<(usize, String)>); - -/// Copy a graph as JSON: to the explorer clipboard, and as text to the system clipboard -pub(super) fn copy_graph(app: &mut MaterialCraftApp, ctx: &egui::Context, i: usize) { - let Some(g) = app.session.pkg.graphs.get(i) else { return }; - match serde_json::to_value(g) { - Ok(v) => { - if let Ok(text) = serde_json::to_string(&v) { - ctx.copy_text(text); - } - app.explorer_clipboard.0 = Some(v); - app.toast(format!("{} {}", tr("Copied graph"), g.name), false); - } - Err(e) => app.toast(format!("{}: {e}", tr("Could not copy the graph")), true), - } -} - -pub(super) fn paste_graph(app: &mut MaterialCraftApp) { - let Some(v) = app.explorer_clipboard.0.clone() else { return }; - if let Some(r) = app.run("graph.add", json!({"graph": v})) { - app.toast(format!("{} {}", tr("Pasted graph"), r["name"].as_str().unwrap_or_default()), false); - } -} - -/// Compute the open graph's outputs now: the cache is kept, the cook restarts (also lifts a Cancel) -pub(super) fn compute(app: &mut MaterialCraftApp) { - app.cooker.hold = false; - app.session.dirty = true; -} - -/// Show the package file in the system's file browser -pub(super) fn reveal(app: &mut MaterialCraftApp) { - #[cfg(not(target_arch = "wasm32"))] - { - let Some(path) = app.session.path.clone() else { return }; - let folder = std::path::Path::new(&path).parent().map(|p| p.to_path_buf()).unwrap_or_default(); - let result = if cfg!(target_os = "windows") { - std::process::Command::new("explorer").arg(format!("/select,{path}")).spawn() - } else if cfg!(target_os = "macos") { - std::process::Command::new("open").arg("-R").arg(&path).spawn() - } else { - std::process::Command::new("xdg-open").arg(&folder).spawn() - }; - if let Err(e) = result { - app.toast(format!("{} {} ({e})", tr("Package folder:"), folder.display()), true); - } - } - #[cfg(target_arch = "wasm32")] - app.toast(tr("The browser keeps no package folder"), true); -} - -/// Pick a new file for a linked resource -pub(super) fn relink(app: &mut MaterialCraftApp, i: usize) { - #[cfg(not(target_arch = "wasm32"))] - if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) - && let Some(p) = crate::windows::dialog(app).add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - { - crate::windows::remember_dir(app, &p); - app.run("file.linkBitmap", json!({"path": p.display().to_string(), "name": name})); - } - #[cfg(target_arch = "wasm32")] - { - let _ = i; - app.toast(tr("The browser has no files to link to"), true); - } -} diff --git a/crates/ui-egui/src/explorer/package_menu.rs b/crates/ui-egui/src/explorer/package_menu.rs deleted file mode 100644 index 2846220..0000000 --- a/crates/ui-egui/src/explorer/package_menu.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! The package row's context menu (New, Import, Link, Save, Export, Send to, Copy/Paste, -//! Close, Compute, Show in Explorer, Dependency Manager) - -use egui::Ui; - -use crate::MaterialCraftApp; -use crate::i18n::tr; - -/// Draw the menu; returns the menu id picked (a `ui.`/`file.` command or an `explorer.` action) -pub(super) fn show(app: &MaterialCraftApp, ui: &mut Ui) -> Option<&'static str> { - let mut picked: Option<&'static str> = None; - let mut pick = |ui: &mut Ui, label: &str, id: &'static str, key: &str, enabled: bool| { - if crate::menus::menu_row(ui, tr(label), key, enabled).clicked() { - picked = Some(id); - ui.close(); - } - }; - ui.menu_button(tr("New"), |ui| { - pick(ui, "Graph...", "ui.newGraph", "Ctrl+N", true); - pick(ui, "Function Graph...", "ui.newFunctionGraph", "", true); - }); - ui.menu_button(tr("Import"), |ui| { - pick(ui, "Bitmap...", "file.importBitmap", "", true); - pick(ui, "Graph from a package...", "file.importGraph", "", true); - }); - ui.menu_button(tr("Link"), |ui| { - pick(ui, "Bitmap...", "file.linkBitmap", "", true); - }); - pick(ui, "Reload", "ui.reloadResources", "", true); - ui.separator(); - pick(ui, "Save", "file.save", "Ctrl+S", true); - pick(ui, "Save as...", "file.saveAs", "Ctrl+Shift+S", true); - pick(ui, "Save a copy as...", "file.saveCopy", "", true); - pick(ui, "Export with dependencies...", "file.exportWithDependencies", "", true); - ui.menu_button(tr("Send to"), |ui| { - pick(ui, "TextureCraft", "file.sendToTextureCraft", "", true); - }); - ui.separator(); - pick(ui, "Copy", "explorer.copy", "", true); - pick(ui, "Paste", "explorer.paste", "", app.explorer_clipboard.0.is_some()); - ui.separator(); - pick(ui, "Close package", "ui.closeAll", "", true); - pick(ui, "Compute Outputs", "explorer.compute", "", true); - pick(ui, "Show in Explorer...", "explorer.reveal", "", app.session.path.is_some()); - ui.separator(); - pick(ui, "Dependency Manager", "ui.view.dependencies", "", true); - picked -} diff --git a/crates/ui-egui/src/function/library.rs b/crates/ui-egui/src/function/library.rs index 645ab0b..56ea6a7 100644 --- a/crates/ui-egui/src/function/library.rs +++ b/crates/ui-egui/src/function/library.rs @@ -1,141 +1,22 @@ -//! The library while a function graph is being edited: the operations by category, each with -//! a text icon saying what it is, its inputs, and a tooltip. Double-click adds one. - -use egui::{Align2, Color32, FontId, RichText, Ui, vec2}; -use materialcraft_engine::FunctionEdit; -use materialcraft_engine::nodes::function::FunctionDefinition; - -use super::op_badge; -use crate::theme::Tokens; use crate::{MaterialCraftApp, i18n::tr}; - -/// The categories in the order the reference library lists them -const ORDER: [&str; 10] = ["Constant", "Variables", "Vector", "Cast", "Operator", "Logical", "Comparison", "Function", "Control", "Samplers"]; +use egui::Ui; +use materialcraft_engine::FunctionEdit; pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) else { return }; - let tk = Tokens::get(ui.ctx()); + let operations = target.available_operations(&app.session); + ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions"))); let search = app.ui.library_search.to_ascii_lowercase(); - let operations: Vec<&'static FunctionDefinition> = target - .available_operations(&app.session) - .filter(|d| { - search.is_empty() - || d.label.to_ascii_lowercase().contains(&search) - || d.id.contains(&search) - || op_badge::text(d.id).to_ascii_lowercase().contains(&search) - }) - .collect(); - - let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions")).desired_width(f32::INFINITY)); - crate::widgets::name(&r, egui::Role::TextInput, "Search functions"); - ui.label(RichText::new(tr("Double-click an operation to add it to the function")).small().color(tk.text_dim)); - ui.add_space(2.0); - - let mut add: Option<&'static str> = None; - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - let mut categories: Vec<&str> = ORDER.to_vec(); - for d in &operations { - if !categories.contains(&d.category) { - categories.push(d.category); + egui::ScrollArea::vertical().show(ui, |ui| { + for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) { + if ui.selectable_label(false, tr(definition.label)).double_clicked() + && let Some(mut editor) = app.function_editor.take() + { + let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]); + editor.edit(app, FunctionEdit::Add { operation: definition.id.into(), at, snap: app.ui.prefs.snap_to_grid }, false); + app.function_editor = Some(editor); } } - for category in categories { - let rows: Vec<&&FunctionDefinition> = operations.iter().filter(|d| d.category == category).collect(); - if rows.is_empty() { - continue; - } - let key = format!("fn:{category}"); - let collapsed = app.ui.library_collapsed.contains(&key) && search.is_empty(); - let header = ui.horizontal(|ui| { - let color = op_badge::color(category); - ui.label(RichText::new(if collapsed { egui_phosphor::regular::CARET_RIGHT } else { egui_phosphor::regular::CARET_DOWN }).color(tk.text_dim)); - ui.label(RichText::new(op_badge::icon(category)).color(color)); - ui.label(RichText::new(tr(category)).strong()); - ui.label(RichText::new(format!("{}", rows.len())).small().color(tk.text_dim)); - }); - let header = ui.interact(header.response.rect, ui.scope_id().with(&key), egui::Sense::click()); - crate::widgets::name(&header, egui::Role::TreeItem, category); - if header.clicked() { - if collapsed { - app.ui.library_collapsed.retain(|k| k != &key); - } else { - app.ui.library_collapsed.push(key.clone()); - } - } - if collapsed { - continue; - } - for d in rows { - if row(ui, d, &tk) { - add = Some(d.id); - } - } - ui.add_space(4.0); - } }); - - if let Some(operation) = add - && let Some(mut editor) = app.function_editor.take() - { - let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]); - editor.edit(app, FunctionEdit::Add { operation: operation.into(), at, snap: app.ui.prefs.snap_to_grid }, false); - app.function_editor = Some(editor); - } -} - -/// One operation: the badge, the label, its inputs; true on a double-click -fn row(ui: &mut Ui, d: &FunctionDefinition, tk: &Tokens) -> bool { - let height = 24.0; - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::click()); - crate::widgets::name(&resp, egui::Role::ListItem, d.label); - let p = ui.painter(); - if resp.hovered() { - p.rect_filled(rect, 4.0, tk.row_hover); - } - let color = op_badge::color(d.category); - let badge = egui::Rect::from_min_size(rect.min + vec2(14.0, 3.0), vec2(46.0, height - 6.0)); - p.rect_filled(badge, 4.0, Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), 48)); - p.rect_stroke(badge, 4.0, egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), 140)), egui::StrokeKind::Inside); - p.text(badge.center(), Align2::CENTER_CENTER, op_badge::text(d.id), FontId::monospace(11.0), color); - p.text(badge.right_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, tr(d.label), FontId::proportional(12.5), tk.text); - if !d.inputs.is_empty() { - p.text(rect.right_center() - vec2(6.0, 0.0), Align2::RIGHT_CENTER, d.inputs.join(", "), FontId::proportional(10.5), tk.text_dim); - } - let added = resp.double_clicked(); - resp.on_hover_ui(|ui| { - ui.label(RichText::new(tr(d.label)).strong()); - ui.label(tr(op_badge::describe(d.id))); - ui.label( - RichText::new(format!( - "{}: {} {}: {}", - tr("Category"), - tr(d.category), - tr("Inputs"), - if d.inputs.is_empty() { "none".to_string() } else { d.inputs.join(", ") } - )) - .small() - .color(tk.text_dim), - ); - }); - added -} - -#[cfg(test)] -mod tests { - use super::op_badge; - - /// Every operation has its own badge, and every badge is drawn from glyphs the UI font has - #[test] - fn every_operation_has_a_badge_in_the_font() { - let allowed = "≠≥≤√×÷−·•¬ƒ"; - for d in materialcraft_engine::nodes::function::FUNCTIONS.iter() { - let badge = op_badge::text(d.id); - assert_ne!(badge, "ƒ", "{} has no badge", d.id); - for c in badge.chars() { - assert!(c.is_ascii() || allowed.contains(c), "{}: {c:?} is not in the UI font", d.id); - } - assert_ne!(op_badge::describe(d.id), "A function node.", "{} has no description", d.id); - } - } } diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs index ab7c42f..136b0db 100644 --- a/crates/ui-egui/src/function/mod.rs +++ b/crates/ui-egui/src/function/mod.rs @@ -4,7 +4,6 @@ mod function_drag; mod function_editor; mod function_target; pub(crate) mod library; -pub(crate) mod op_badge; mod port_label; pub(crate) mod properties; diff --git a/crates/ui-egui/src/function/op_badge.rs b/crates/ui-egui/src/function/op_badge.rs deleted file mode 100644 index d5d5091..0000000 --- a/crates/ui-egui/src/function/op_badge.rs +++ /dev/null @@ -1,173 +0,0 @@ -//! A short text icon for each function operation: what the node is at a glance ("F2", "+", -//! "≥", "sin", "if"), with a colour per category - -use egui::Color32; - -/// The text icon of a function operation (its id), always from the glyphs the UI font has -pub fn text(id: &str) -> &'static str { - match id { - "const_bool" => "B", - "const_float1" => "F1", - "const_float2" => "F2", - "const_float3" => "F3", - "const_float4" => "F4", - "const_int1" => "I1", - "const_int2" => "I2", - "const_int3" => "I3", - "const_int4" => "I4", - "const_string" => "S", - "get_bool" => "$B", - "get_float1" => "$F1", - "get_float2" => "$F2", - "get_float3" => "$F3", - "get_float4" => "$F4", - "get_integer1" => "$I1", - "get_integer2" => "$I2", - "get_integer3" => "$I3", - "get_integer4" => "$I4", - "get_string" => "$S", - "set" => "$=", - "isdefined" => "$?", - "add" => "+", - "sub" => "−", - "mul" => "×", - "div" => "÷", - "mod" => "%", - "neg" => "−x", - "mulscalar" => "×s", - "dot" => "a·b", - "and" => "&&", - "or" => "||", - "not" => "¬", - "eq" => "=", - "noteq" => "≠", - "gt" => ">", - "gteq" => "≥", - "lr" => "<", - "lreq" => "≤", - "abs" => "|x|", - "floor" => "flr", - "ceil" => "ceil", - "sqrt" => "√", - "exp" => "e^x", - "log" => "ln", - "log2" => "log2", - "pow2" => "2^x", - "sin" => "sin", - "cos" => "cos", - "tan" => "tan", - "atan2" => "atan", - "rand" => "rnd", - "min" => "min", - "max" => "max", - "pow" => "x^y", - "lerp" => "lerp", - "cartesian" => "polar", - "vector2" => "F2( )", - "vector3" => "F3( )", - "vector4" => "F4( )", - "swizzle1" => ".x", - "swizzle2" => ".xy", - "swizzle3" => ".xyz", - "swizzle4" => ".xyzw", - "ivector2" => "I2( )", - "ivector3" => "I3( )", - "ivector4" => "I4( )", - "iswizzle1" => "i.x", - "iswizzle2" => "i.xy", - "iswizzle3" => "i.xyz", - "iswizzle4" => "i.xyzw", - "tofloat" => "(F1)", - "toint1" => "(I1)", - "tofloat2" => "(F2)", - "toint2" => "(I2)", - "tofloat3" => "(F3)", - "toint3" => "(I3)", - "tofloat4" => "(F4)", - "toint4" => "(I4)", - "samplecol" => "RGBA", - "samplelum" => "Gray", - "ifelse" => "if", - "sequence" => "seq", - "while" => "loop", - "passthrough" => "•", - _ => "ƒ", - } -} - -/// The colour of a category's badges: the node header colour, lightened so text in it reads -/// on both themes -pub fn color(category: &str) -> Color32 { - let base = super::geometry::category_color(category); - let lift = |c: u8| (c as f32 + (255.0 - c as f32) * 0.45) as u8; - Color32::from_rgb(lift(base.r()), lift(base.g()), lift(base.b())) -} - -/// The category's icon (phosphor glyph) -pub fn icon(category: &str) -> &'static str { - use egui_phosphor::regular as icon; - match category { - "Constant" => icon::HASH, - "Variables" => icon::BRACKETS_CURLY, - "Vector" => icon::ARROWS_OUT_CARDINAL, - "Cast" => icon::ARROWS_LEFT_RIGHT, - "Operator" => icon::PLUS_MINUS, - "Logical" => icon::CIRCLES_THREE, - "Comparison" => icon::EQUALS, - "Function" => icon::FUNCTION, - "Control" => icon::GIT_FORK, - "Samplers" => icon::EYEDROPPER_SAMPLE, - _ => icon::DOTS_THREE, - } -} - -/// One line on what the operation does (the row's tooltip) -pub fn describe(id: &str) -> &'static str { - match id { - "const_bool" | "const_float1" | "const_float2" | "const_float3" | "const_float4" | "const_int1" | "const_int2" | "const_int3" | "const_int4" - | "const_string" => "A constant value of this type, set in the node's properties.", - "get_bool" | "get_float1" | "get_float2" | "get_float3" | "get_float4" | "get_integer1" | "get_integer2" | "get_integer3" | "get_integer4" - | "get_string" => "Reads a variable of this type: a graph input, an exposed parameter, or $pos / $size / $time.", - "set" => "Stores the value in a named variable for later Get nodes in the same function.", - "isdefined" => "True when the named variable has a value.", - "add" => "a + b (same types).", - "sub" => "a − b.", - "mul" => "a × b, component by component.", - "div" => "a ÷ b.", - "mod" => "The remainder of a ÷ b.", - "neg" => "−a.", - "mulscalar" => "Every component of a multiplied by the scalar.", - "dot" => "The dot product of two vectors.", - "and" | "or" | "not" => "Boolean logic.", - "eq" | "noteq" | "gt" | "gteq" | "lr" | "lreq" => "Compares a with b; the result is a boolean.", - "abs" => "|a|.", - "floor" => "Rounds down to a whole number.", - "ceil" => "Rounds up to a whole number.", - "sqrt" => "The square root.", - "exp" => "e to the power a.", - "log" => "The natural logarithm.", - "log2" => "The logarithm base 2.", - "pow2" => "2 to the power a.", - "sin" | "cos" | "tan" => "Trigonometry; the input is in radians.", - "atan2" => "The angle of the vector (y, x), in radians.", - "rand" => "A random number from 0 to a.", - "min" => "The smaller of a and b.", - "max" => "The larger of a and b.", - "pow" => "a to the power b.", - "lerp" => "a blended to b by x (0 = a, 1 = b).", - "cartesian" => "Polar (rho, theta) to cartesian (x, y).", - "vector2" | "vector3" | "vector4" | "ivector2" | "ivector3" | "ivector4" => "Builds a vector from its components (the first ones, then the last).", - "swizzle1" | "swizzle2" | "swizzle3" | "swizzle4" | "iswizzle1" | "iswizzle2" | "iswizzle3" | "iswizzle4" => { - "Picks and reorders components of a vector (the pattern is in the node's properties)." - } - "tofloat" | "tofloat2" | "tofloat3" | "tofloat4" => "Converts the value to floats.", - "toint1" | "toint2" | "toint3" | "toint4" => "Converts the value to integers (truncated).", - "samplecol" => "The colour of an image input at a position (pixel processors).", - "samplelum" => "The grayscale value of an image input at a position (pixel processors).", - "ifelse" => "The if path when the condition is true, else the else path.", - "sequence" => "Evaluates the first input (for its side effects), returns the last.", - "while" => "Runs the loop input while the condition holds, after init.", - "passthrough" => "A dot: passes its input through, to tidy wires.", - _ => "A function node.", - } -} diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs index a2a4ca6..60a320b 100644 --- a/crates/ui-egui/src/function/render.rs +++ b/crates/ui-egui/src/function/render.rs @@ -50,7 +50,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu } let mut camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; - camera.zoom_from_input(ui, canvas_bounds, app.ui.prefs.invert_zoom); + camera.zoom_from_input(ui, canvas_bounds); editor.pan = camera.pan; editor.zoom = camera.zoom; let document = standalone.then(|| app.session.graph().ok()).flatten(); @@ -109,10 +109,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); let body = node_card::body(screen_rect, editor.zoom); if node.value.is_none() { - // The operation's text icon ("+", "≥", "sin", "F2( )"): what the node is at a glance - let badge = super::op_badge::text(&node.op); - let size = if badge.chars().count() > 3 { 16.0 } else { 24.0 } * editor.zoom; - painter.text(body.center(), Align2::CENTER_CENTER, badge, FontId::monospace(size.min(30.0)), tokens.text_strong); + painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); } if is_output { let header = node_card::header(screen_rect, editor.zoom); diff --git a/crates/ui-egui/src/graph/annotation_canvas.rs b/crates/ui-egui/src/graph/annotation_canvas.rs index 14ab7ed..e37bb4d 100644 --- a/crates/ui-egui/src/graph/annotation_canvas.rs +++ b/crates/ui-egui/src/graph/annotation_canvas.rs @@ -87,29 +87,16 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, comments: &[Comment], ca hits } -/// Paint the navigation pins; returns each pin's screen rect (icon and name) for hit testing -pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) -> Vec<(u64, Rect)> { +pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) { let painter = ui.painter_at(app.graph.view); let theme = Tokens::get(ui.ctx()); - let mut hits = Vec::with_capacity(pins.len()); for pin in pins { - let mut position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); - if let Some(GraphDrag::Pin { id, delta }) = &app.graph.drag - && *id == pin.id - { - position += materialcraft_engine::graph_grid::snap_position([delta.x, delta.y], app.ui.prefs.snap_to_grid).into(); - } + let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id)); let position = camera.to_screen(position); - let dragging = matches!(&app.graph.drag, Some(GraphDrag::Pin { id, .. }) if *id == pin.id); - let color = if dragging { theme.text_strong } else { theme.accent }; - painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), color); - let name = painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text); - let icon_rect = Rect::from_min_max(position + vec2(-9.0, -20.0), position + vec2(9.0, 2.0)); - hits.push((pin.id, icon_rect.union(name))); + painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent); + painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text); } - - hits } pub(crate) fn offset(app: &MaterialCraftApp, contains: impl FnOnce(&materialcraft_engine::FrameContents) -> bool) -> Vec2 { diff --git a/crates/ui-egui/src/graph/annotation_input.rs b/crates/ui-egui/src/graph/annotation_input.rs index de76af8..565462a 100644 --- a/crates/ui-egui/src/graph/annotation_input.rs +++ b/crates/ui-egui/src/graph/annotation_input.rs @@ -22,7 +22,7 @@ pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, } else { app.run("graph.annotation.select", json!({})); } - } else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. } | GraphDrag::Pin { delta, .. }) = &mut app.graph.drag { + } else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. }) = &mut app.graph.drag { *delta += motion; } @@ -38,11 +38,6 @@ pub(super) fn begin_comment(app: &mut MaterialCraftApp, id: u64) { app.graph.drag = Some(GraphDrag::Comment { id, delta: Vec2::ZERO }); } -pub(super) fn begin_pin(app: &mut MaterialCraftApp, id: u64) { - app.run("graph.annotation.select", json!({})); - app.graph.drag = Some(GraphDrag::Pin { id, delta: Vec2::ZERO }); -} - pub(super) fn begin_frame(app: &mut MaterialCraftApp, id: u64, resize: bool) { let contents = app .session @@ -72,13 +67,6 @@ pub(super) fn finish(app: &mut MaterialCraftApp, drag: GraphDrag) { app.run("graph.comment.edit", json!({"id": id, "at": position})); } } - GraphDrag::Pin { id, delta } if delta.length() > 0.5 => { - if let Some(pin) = app.session.graph().ok().and_then(|graph| graph.pins.iter().find(|pin| pin.id == id)) { - let moved = materialcraft_engine::graph_grid::snap_position([delta.x, delta.y], app.ui.prefs.snap_to_grid); - let position = [pin.pos[0] + moved[0], pin.pos[1] + moved[1]]; - app.run("graph.pin.edit", json!({"id": id, "at": position})); - } - } _ => {} } } diff --git a/crates/ui-egui/src/graph/auto_convert.rs b/crates/ui-egui/src/graph/auto_convert.rs deleted file mode 100644 index 492e26e..0000000 --- a/crates/ui-egui/src/graph/auto_convert.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! Preferences ▸ Graph ▸ "Automatically insert color/grayscale conversion node": a wire from a -//! color output to a grayscale input gets a Grayscale Conversion node in between, one from a -//! grayscale output to a color input a Gradient Map - -use materialcraft_engine::core::NodeId; -use materialcraft_engine::nodes::PortKind; -use serde_json::json; - -use crate::MaterialCraftApp; - -/// The node that converts the kinds between an output and an input (`None` = the kinds agree -/// or the preference is off) -fn conversion_node(app: &MaterialCraftApp, from: &(NodeId, String), to: NodeId, to_port: &str) -> Option<&'static str> { - if !app.ui.prefs.auto_convert { - return None; - } - let g = app.session.graph().ok()?; - let out_kind = materialcraft_engine::eval::ports(&app.session.pkg, g, g.node(from.0).ok()?).1.into_iter().find(|p| p.id == from.1)?.kind; - let in_kind = materialcraft_engine::eval::ports(&app.session.pkg, g, g.node(to).ok()?).0.into_iter().find(|p| p.id == to_port)?.kind; - match (out_kind, in_kind) { - (PortKind::Color, PortKind::Gray) => Some("grayscale_conversion"), - (PortKind::Gray, PortKind::Color) => Some("gradient_map"), - _ => None, - } -} - -/// Connect `from` to `to`'s input (detaching `detach` first), inserting a conversion node when -/// the preference asks for one. One undo step either way -pub(super) fn connect(app: &mut MaterialCraftApp, from: &(NodeId, String), to: NodeId, to_port: &str, detach: Option<&(NodeId, String)>) { - let Some(converter) = conversion_node(app, from, to, to_port) else { - let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": to.0, "toPort": to_port}); - if let Some((node, port)) = detach { - parameters["detach"] = json!({"to": node.0, "toPort": port}); - } - app.run("graph.connect", parameters); - return; - }; - let g = app.session.graph().ok(); - let pos = |id: NodeId| g.and_then(|g| g.node(id).ok()).map_or([0.0, 0.0], |n| n.pos); - let (pa, pb) = (pos(from.0), pos(to)); - let at = [(pa[0] + pb[0]) * 0.5, (pa[1] + pb[1]) * 0.5]; - let snap = app.ui.prefs.snap_to_grid; - let detach = detach.cloned(); - let from = from.clone(); - let to_port = to_port.to_string(); - let result = app.session.group("Connect", |session| { - if let Some((node, port)) = &detach { - materialcraft_engine::execute(session, "graph.disconnect", &json!({"to": node.0, "toPort": port}))?; - } - let added = materialcraft_engine::execute( - session, - "graph.node.add", - &json!({"def": converter, "at": at, "snapToGrid": snap, "connectFrom": {"node": from.0.0, "port": from.1}}), - )?; - let id = added - .get("id") - .and_then(serde_json::Value::as_u64) - .ok_or_else(|| materialcraft_engine::EngineError::Other("the conversion node was not added".into()))?; - materialcraft_engine::execute(session, "graph.connect", &json!({"from": id, "to": to.0, "toPort": to_port}))?; - Ok(()) - }); - if let Err(error) = result { - app.toast(error.to_string(), true); - } -} diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 0556813..cf2788e 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -56,12 +56,9 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Background and grid painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31)); let mut camera = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom }; - camera.zoom_from_input(ui, rect, app.ui.prefs.invert_zoom); + camera.zoom_from_input(ui, rect); app.ui.graph_camera = camera.state(); - super::wire_geometry::set_straight(app.ui.prefs.straight_wires); - if app.ui.prefs.show_grid { - super::grid::paint(&painter, &camera, rect); - } + super::grid::paint(&painter, &camera, rect); let pointer = ctx.input(|input| input.pointer.hover_pos()); let show_thumbnails = app.ui.prefs.thumbnails; @@ -183,6 +180,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let font = FontId::proportional((10.5 * camera.zoom).clamp(6.0, 16.0)); let small = FontId::proportional((9.0 * camera.zoom).clamp(5.5, 13.0)); let mut node_responses: Vec<(NodeId, egui::Response)> = Vec::new(); + let mut dot_grabs: Vec<Rect> = Vec::new(); for layout in &layouts { let Some(node) = index.node(layout.id) else { continue }; @@ -193,7 +191,12 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let selected = selection.contains(&node.id); let result = cooked.nodes.get(&node.id); let error = result.and_then(|r| r.error.as_ref()); - let resp = ui.interact(screen_rect, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); + // A dot is tiny, so its grab area keeps a minimum on-screen size + let grab = if node.def == "dot" { node_card::dot_grab(screen_rect) } else { screen_rect }; + if node.def == "dot" { + dot_grabs.push(grab); + } + let resp = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag()); crate::widgets::name(&resp, egui::Role::Button, &node_label(node)); if node.def == "dot" { node_card::paint_dot(&painter, screen_rect, if selected { theme.accent } else { Color32::from_gray(0xb4) }); @@ -246,12 +249,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { if node.def == "output" { painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE); } - if app.ui.prefs.node_timings - && let Some(r0) = result - { - let txt = if r0.cached { format!("{:.1} ms ({})", r0.ms, crate::i18n::tr("cached")) } else { format!("{:.1} ms", r0.ms) }; - painter.text(header.right_bottom() + vec2(-2.0, 2.0), Align2::RIGHT_TOP, txt, small.clone(), theme.warning); - } let outline = if error.is_some() { Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0)) } else if selected { @@ -275,10 +272,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera); app.graph.comments = comment_hits.clone(); - app.graph.pins = super::annotation_canvas::pins(app, ui, &graph.pins, &camera); + super::annotation_canvas::pins(app, ui, &graph.pins, &camera); // Ports (drawn last, interactable over the node cards) - let port_hover = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 9.0)).cloned(); + // except on a dot's body: its port hit circles would otherwise cover it and it could never be moved + let port_hover = pointer.filter(|p| !dot_grabs.iter().any(|grab| grab.contains(*p))).and_then(|p| nearest_port(&app.graph.ports, p, 9.0)).cloned(); for h in &app.graph.ports { if !rect.contains(h.pos) { continue; diff --git a/crates/ui-egui/src/graph/graph_camera.rs b/crates/ui-egui/src/graph/graph_camera.rs index 48e63ef..472969c 100644 --- a/crates/ui-egui/src/graph/graph_camera.rs +++ b/crates/ui-egui/src/graph/graph_camera.rs @@ -31,7 +31,7 @@ impl GraphCamera { Self { origin: view.min, pan, zoom } } - pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect, invert: bool) { + pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect) { self.zoom = self.zoom.clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); if !ui.rect_contains_pointer(view) { return; @@ -39,7 +39,7 @@ impl GraphCamera { let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|pointer| view.contains(*pointer)) else { return }; - let scroll = ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0) * if invert { -1.0 } else { 1.0 }; + let scroll = ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0); if scroll.is_finite() && scroll != 0.0 { let before = self.to_graph(pointer); self.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1); diff --git a/crates/ui-egui/src/graph/graph_drag.rs b/crates/ui-egui/src/graph/graph_drag.rs index 19bea8e..d2e73bb 100644 --- a/crates/ui-egui/src/graph/graph_drag.rs +++ b/crates/ui-egui/src/graph/graph_drag.rs @@ -3,7 +3,7 @@ use egui::{Pos2, Vec2}; use materialcraft_engine::core::NodeId; #[derive(Clone, Debug)] -pub(crate) enum GraphDrag { +pub(super) enum GraphDrag { Nodes { delta: Vec2, }, @@ -30,9 +30,4 @@ pub(crate) enum GraphDrag { id: u64, delta: Vec2, }, - /// A navigation pin being dragged to a new spot - Pin { - id: u64, - delta: Vec2, - }, } diff --git a/crates/ui-egui/src/graph/graph_view.rs b/crates/ui-egui/src/graph/graph_view.rs index 4283100..385faa2 100644 --- a/crates/ui-egui/src/graph/graph_view.rs +++ b/crates/ui-egui/src/graph/graph_view.rs @@ -13,10 +13,6 @@ pub struct GraphView { pub ports: Vec<PortHit>, pub frames: Vec<(u64, Rect)>, pub comments: Vec<(u64, Rect)>, - /// The navigation pins' screen rects this frame (icon and name) - pub pins: Vec<(u64, Rect)>, - /// The pin under the last right-click (its context menu) - pub(super) menu_pin: Option<u64>, /// The canvas rectangle last frame pub view: Rect, /// Graph point of the last right-click (context menu actions add things there) @@ -49,8 +45,6 @@ impl Default for GraphView { ports: Vec::new(), frames: Vec::new(), comments: Vec::new(), - pins: Vec::new(), - menu_pin: None, view: Rect::NOTHING, menu_at: Pos2::ZERO, framed_graph: None, diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index be14fa4..9092987 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -55,8 +55,6 @@ pub(super) fn handle( } else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) { app.graph.drag = Some(GraphDrag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) }); } - } else if let Some(id) = app.graph.pins.iter().rev().find(|(_, r)| r.contains(p)).map(|(id, _)| *id) { - super::annotation_input::begin_pin(app, id); } else if let Some((id, _)) = comments.iter().rev().find(|(_, r)| r.contains(p)) { super::annotation_input::begin_comment(app, *id); } else if let Some((id, _)) = nodes.iter().rev().find(|(_, r)| r.rect.contains(p)) { @@ -76,10 +74,7 @@ pub(super) fn handle( let d = ctx.input(|i| i.pointer.delta()) / zoom; app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y]; } - Some(GraphDrag::Nodes { delta }) - | Some(GraphDrag::Frame { delta, .. }) - | Some(GraphDrag::Comment { delta, .. }) - | Some(GraphDrag::Pin { delta, .. }) => *delta += motion, + Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion, Some(GraphDrag::WirePress { wire, start }) => { // Dragged far enough: a reroute dot where the press was, carried by the pointer if let Some(p) = pointer @@ -132,20 +127,26 @@ pub(super) fn handle( GraphDrag::Wire { from, detached } => { let target = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| !h.output).cloned(); match target { - Some(t) => super::auto_convert::connect(app, &from, t.node, &t.port, detached.as_ref()), + Some(t) => { + let mut parameters = json!({"from": from.0.0, "fromPort": from.1, "to": t.node.0, "toPort": t.port}); + if let Some((node, port)) = detached { + parameters["detach"] = json!({"to": node.0, "toPort": port}); + } + + app.run("graph.connect", parameters); + } None => { if let Some((n, p)) = &detached { app.run("graph.disconnect", json!({"to": n.0, "toPort": p})); } else if let Some(p) = pointer && rect.contains(p) - && app.ui.prefs.drag_create { open_search(app, cam.to_graph(p), Some(from)); } } } } - GraphDrag::Frame { .. } | GraphDrag::Comment { .. } | GraphDrag::Pin { .. } => super::annotation_input::finish(app, drag), + GraphDrag::Frame { .. } | GraphDrag::Comment { .. } => super::annotation_input::finish(app, drag), } } @@ -198,7 +199,6 @@ pub(super) fn handle( && let Some(p) = pointer { app.graph.menu_at = cam.to_graph(p); - app.graph.menu_pin = app.graph.pins.iter().rev().find(|(_, rect)| rect.contains(p)).map(|(id, _)| *id); if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(p)) { app.run("graph.annotation.select", json!({"kind": "comment", "id": id})); } else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(p)) { @@ -214,10 +214,9 @@ pub(super) fn handle( } } let at = app.graph.menu_at; - canvas.context_menu(|ui| match (app.graph.menu_pin, app.graph.menu_wire.clone()) { - (Some(pin), _) => super::pin_menu::show(app, ui, pin), - (None, Some(w)) => wire_menu(app, ui, w, at), - (None, None) => super::context_menu::show(app, ui, at, None), + canvas.context_menu(|ui| match app.graph.menu_wire.clone() { + Some(w) => wire_menu(app, ui, w, at), + None => super::context_menu::show(app, ui, at, None), }); // Library drops @@ -226,14 +225,17 @@ pub(super) fn handle( { let gp = cam.to_graph(p); let at = [gp.x - NODE_W * 0.5, gp.y - 20.0]; - crate::library::add_key(app, &payload.0, at); + match payload.0.strip_prefix('@') { + Some(graph) => app.run("graph.node.add", json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})), + None => app.run("graph.node.add", json!({"def": payload.0, "at": at})), + }; } // Keys over the canvas let hovered = pointer.is_some_and(|p| rect.contains(p)); if hovered && app.graph.search.is_none() { let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space)); - let tab = app.ui.prefs.tab_key_menu && !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); + let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab)); if (space || tab) && let Some(p) = pointer { diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index 7dc1894..0eca8e4 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -81,23 +81,6 @@ fn pin_navigation_wraps_and_thumbnail_commands_keep_the_document() { assert_eq!(original, app.session.pkg); } -#[test] -fn a_dragged_pin_moves_and_its_menu_renames_it() { - let mut app = MaterialCraftApp::headless(new_session(), UiState::default()); - app.ui.prefs.snap_to_grid = false; - let id = app.run("graph.pin.add", json!({"at": [100, 200], "name": "Start"})).unwrap()["id"].as_u64().unwrap(); - app.graph.drag = Some(crate::graph::GraphDrag::Pin { id, delta: vec2(30.0, -10.0) }); - let drag = app.graph.drag.take().unwrap(); - crate::graph::annotation_input::finish(&mut app, drag); - let pin = app.session.graph().unwrap().pins.iter().find(|p| p.id == id).cloned().unwrap(); - assert_eq!(pin.pos, [130.0, 190.0]); - app.run("graph.pin.edit", json!({"id": id, "name": " Middle "})); - assert_eq!(app.session.graph().unwrap().pins[0].name, "Middle"); - assert!(app.run("graph.pin.edit", json!({"id": id})).is_none(), "nothing to change is an error"); - app.session.undo(); - assert_eq!(app.session.graph().unwrap().pins[0].name, "Start"); -} - #[test] fn frame_drag_selects_the_border_and_moves_comments_and_nodes_together() { let mut frames = Frames::new(new_session()); @@ -547,3 +530,35 @@ fn box_selection_and_alt_panning_are_shared_by_every_canvas() { assert_eq!(frames.app.session.pkg, original, "{kind} navigation edited the document"); } } + +#[test] +fn dots_move_from_their_body_and_still_wire_from_just_outside_at_any_zoom() { + let mut frames = Frames::new(new_session()); + let ids: Vec<NodeId> = [[0, 0], [256, 0]] + .into_iter() + .map(|at| NodeId(frames.app.run("graph.node.add", json!({"def": "dot", "at": at})).unwrap()["id"].as_u64().unwrap())) + .collect(); + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + + // Zoomed in, at 100% and zoomed out: the dot's ports used to cover its whole body + for zoom in [2.0, 1.0, 0.5, 0.25] { + frames.app.ui.graph_camera.zoom = zoom; + frames.run(Vec::new(), Modifiers::NONE); + let before = frames.app.session.graph().unwrap().node(ids[0]).unwrap().pos; + let from = frames.center(ids[0]); + drag(&mut frames, from, from + vec2(40.0, 30.0)); + let graph = frames.app.session.graph().unwrap(); + assert_ne!(graph.node(ids[0]).unwrap().pos, before, "the dot did not move at zoom {zoom}"); + assert!(graph.connections.is_empty(), "pressing the dot started a wire at zoom {zoom}"); + } + + frames.app.ui.graph_camera.zoom = 1.0; + frames.run(Vec::new(), Modifiers::NONE); + let output = frames.app.graph.ports.iter().find(|port| port.node == ids[0] && port.output).unwrap().pos; + let input = frames.app.graph.ports.iter().find(|port| port.node == ids[1] && !port.output).unwrap().pos; + drag(&mut frames, output + vec2(6.0, 0.0), input); + let graph = frames.app.session.graph().unwrap(); + assert_eq!(graph.connections.len(), 1); + assert_eq!((graph.connections[0].from, graph.connections[0].to), (ids[0], ids[1])); +} diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index 8fd025b..fe7a93c 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -2,7 +2,6 @@ pub(crate) mod actions; pub(crate) mod add_node_menu; pub(crate) mod annotation_canvas; pub(crate) mod annotation_input; -mod auto_convert; pub(crate) mod canvas; mod context_menu; pub(crate) mod frame_hit; @@ -20,17 +19,16 @@ pub(crate) mod node_card; mod node_layout; mod node_search; pub(crate) mod node_selection; -mod pin_menu; pub(crate) mod port_hit; pub(crate) mod port_label; pub(crate) mod subgraph_navigation; pub use canvas::show; pub(crate) use graph_camera::GraphCamera; -pub(crate) use graph_drag::GraphDrag; +use graph_drag::GraphDrag; pub use graph_view::GraphView; pub use library_drag::LibraryDrag; -pub use navigation::{add_node_near_selection, view_center}; +pub use navigation::add_node_near_selection; use node_search::NodeSearch; pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color}; pub use port_hit::PortHit; @@ -46,7 +44,6 @@ mod node_style; mod search; pub(crate) mod selection_commands; pub(crate) mod toolbar; -mod toolbar_tools; mod wire_actions; pub(crate) mod wire_geometry; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs index ffee8d0..04d9f9e 100644 --- a/crates/ui-egui/src/graph/navigation.rs +++ b/crates/ui-egui/src/graph/navigation.rs @@ -3,8 +3,7 @@ use crate::MaterialCraftApp; use egui::{Pos2, Rect, pos2, vec2}; use serde_json::json; -/// The graph point at the middle of the view -pub fn view_center(app: &MaterialCraftApp) -> Pos2 { +pub(super) fn view_center(app: &MaterialCraftApp) -> Pos2 { let c = &app.ui.graph_camera; let v = app.graph.view; pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom) diff --git a/crates/ui-egui/src/graph/node_card.rs b/crates/ui-egui/src/graph/node_card.rs index 9bab166..6a65dc4 100644 --- a/crates/ui-egui/src/graph/node_card.rs +++ b/crates/ui-egui/src/graph/node_card.rs @@ -5,6 +5,8 @@ pub(crate) const HEADER_HEIGHT: f32 = 18.0; pub(crate) const FOOTER_HEIGHT: f32 = 14.0; const PORT_GAP: f32 = 18.0; const DOT_RADIUS: f32 = 7.0; +/// Smallest on-screen side of a dot's grab area, in points +const DOT_MIN_GRAB: f32 = 16.0; pub(crate) fn bounds(position: [f32; 2], inputs: usize, outputs: usize, previews: bool, dot: bool) -> Rect { let position = pos2(position[0], position[1]); @@ -17,6 +19,11 @@ pub(crate) fn bounds(position: [f32; 2], inputs: usize, outputs: usize, previews Rect::from_min_size(position, vec2(WIDTH, HEADER_HEIGHT + body + FOOTER_HEIGHT)) } +/// The on-screen area that picks up dot `bounds`: at least `DOT_MIN_GRAB` wide, so it stays easy to grab when zoomed out +pub(crate) fn dot_grab(bounds: Rect) -> Rect { + Rect::from_center_size(bounds.center(), bounds.size().max(vec2(DOT_MIN_GRAB, DOT_MIN_GRAB))) +} + pub(crate) fn port(bounds: Rect, index: usize, count: usize, output: bool, dot: bool) -> Pos2 { let x = if output { bounds.right() } else { bounds.left() }; if dot { diff --git a/crates/ui-egui/src/graph/pin_menu.rs b/crates/ui-egui/src/graph/pin_menu.rs deleted file mode 100644 index 6728892..0000000 --- a/crates/ui-egui/src/graph/pin_menu.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Right-click on a navigation pin: rename it in place, jump to it, delete it - -use egui::Ui; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; - -pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, pin: u64) { - ui.set_min_width(200.0); - let Some(current) = app.session.graph().ok().and_then(|graph| graph.pins.iter().find(|p| p.id == pin).cloned()) else { - ui.label(tr("The pin is gone")); - return; - }; - ui.label(egui::RichText::new(tr("Pin name")).small()); - let id = ui.make_persistent_id(("pin-rename", pin)); - let mut name: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| current.name.clone()); - let edit = ui.text_edit_singleline(&mut name); - crate::widgets::name(&edit, egui::Role::TextInput, "Pin name"); - if edit.changed() { - ui.data_mut(|d| d.insert_temp(id, name.clone())); - } - let apply = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); - if (apply || ui.button(tr("Rename")).clicked()) && name.trim() != current.name { - app.run("graph.pin.edit", json!({"id": pin, "name": name.trim()})); - ui.data_mut(|d| d.remove_temp::<String>(id)); - ui.close(); - } - ui.separator(); - if ui.button(tr("Go to pin")).clicked() { - let zoom = app.ui.graph_camera.zoom.max(0.01); - app.ui.graph_camera.pan = [current.pos[0] - app.graph.view.width() * 0.5 / zoom, current.pos[1] - app.graph.view.height() * 0.5 / zoom]; - ui.close(); - } - if ui.button(tr("Delete pin")).clicked() { - app.run("graph.pin.delete", json!({"id": pin})); - ui.close(); - } -} diff --git a/crates/ui-egui/src/graph/toolbar.rs b/crates/ui-egui/src/graph/toolbar.rs index 963d97d..086c66f 100644 --- a/crates/ui-egui/src/graph/toolbar.rs +++ b/crates/ui-egui/src/graph/toolbar.rs @@ -20,7 +20,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let owner = pattern.then(|| app.pattern_editor.as_ref().map(|editor| editor.node.0)).flatten(); row(ui, |ui| { let b = button; - if common(app, ui, selection.len(), pattern || function, || { + if common(app, ui, selection.len(), || { let mut parameters = json!({"graph": graph, "ids": selection}); if let Some(owner) = owner { parameters["pattern"] = json!(owner); @@ -48,7 +48,35 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } if !pattern && !function { - view_tools(app, ui); + // Quick insert of the atomic nodes + for (ic, def) in [ + (icon::IMAGE, "bitmap"), + (icon::PALETTE, "uniform"), + (icon::STACK, "blend"), + (icon::DROP, "blur"), + (icon::SHUFFLE, "channels_shuffle"), + (icon::CHART_LINE, "curve"), + (icon::WIND, "directional_blur"), + (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), + (icon::RULER, "distance"), + (icon::MOUNTAINS, "emboss"), + (icon::GRADIENT, "gradient_map"), + (icon::CIRCLE_HALF, "grayscale_conversion"), + (icon::SWATCHES, "hsl"), + (icon::SLIDERS_HORIZONTAL, "levels"), + (icon::CUBE, "normal"), + (icon::CODE, "pixel_processor"), + (icon::DIAMOND, "sharpen"), + (icon::ARROWS_CLOCKWISE, "transformation"), + (icon::WAVES, "warp"), + (icon::SIGN_IN, "input_grayscale"), + (icon::SIGN_OUT, "output"), + ] { + let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); + if b(ui, ic, label) { + add_node_near_selection(app, def); + } + } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if super::subgraph_navigation::can_return(app) { @@ -73,99 +101,6 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); }); - if pattern || function { - return; - } - // Row 2: quick insert of the atomic nodes and the annotations - row(ui, |ui| { - let b = button; - { - for (ic, def) in [ - (icon::IMAGE, "bitmap"), - (icon::BEZIER_CURVE, "svg"), - (icon::TEXT_T, "text"), - (icon::PALETTE, "uniform"), - (icon::STACK, "blend"), - (icon::DROP, "blur"), - (icon::SHUFFLE, "channels_shuffle"), - (icon::CHART_LINE, "curve"), - (icon::WIND, "directional_blur"), - (icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"), - (icon::RULER, "distance"), - (icon::MOUNTAINS, "emboss"), - (icon::GRADIENT, "gradient_map"), - (icon::ARROWS_LEFT_RIGHT, "gradient_dynamic"), - (icon::CIRCLE_HALF, "grayscale_conversion"), - (icon::SWATCHES, "hsl"), - (icon::SLIDERS_HORIZONTAL, "levels"), - (icon::FAST_FORWARD, "motion_blur"), - (icon::CUBE, "normal"), - (icon::CODE, "pixel_processor"), - (icon::FUNCTION, "value_processor"), - (icon::DIAMOND, "sharpen"), - (icon::ARROWS_CLOCKWISE, "transformation"), - (icon::WAVES, "warp"), - (icon::DICE_FIVE, "fx_map"), - (icon::SIGN_IN, "input_grayscale"), - (icon::PALETTE, "input_color"), - (icon::NUMBER_CIRCLE_ONE, "input_value"), - (icon::SIGN_OUT, "output"), - ] { - let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label); - if b(ui, ic, label) { - add_node_near_selection(app, def); - } - } - } - ui.separator(); - if b(ui, icon::DOT_OUTLINE, tr("Add dot (reroute)")) { - add_node_near_selection(app, "dot"); - } - }); -} - -/// Row 1 extras for the material graph: 1:1, screenshot, graph info, find, display toggles, -/// compute and clean-up -fn view_tools(app: &mut MaterialCraftApp, ui: &mut Ui) { - let toggle = |ui: &mut Ui, ic: &str, tip: &str, on: bool| crate::widgets::icon_button(ui, ic, tip, on, 22.0).clicked(); - if button(ui, icon::FRAME_CORNERS, tr("Actual size (1:1)")) { - super::toolbar_tools::zoom_to(app, 1.0); - } - if button(ui, icon::CAMERA, tr("Save a screenshot of the graph...")) { - super::toolbar_tools::screenshot(app, ui.ctx()); - } - let info = crate::widgets::icon_button(ui, icon::INFO, tr("Graph information"), false, 22.0); - egui::Popup::menu(&info).show(|ui| super::toolbar_tools::graph_info(app, ui)); - if button(ui, icon::MAGNIFYING_GLASS, tr("Find a node (Tab)")) { - let c = view_center(app); - super::search::open_search(app, c, None); - } - ui.separator(); - let timings = app.ui.prefs.node_timings; - if toggle(ui, icon::TIMER, tr("Show cook times on nodes"), timings) { - app.ui.prefs.node_timings = !timings; - } - let straight = app.ui.prefs.straight_wires; - if toggle( - ui, - if straight { icon::LINE_SEGMENT } else { icon::WAVE_SINE }, - if straight { tr("Wires: straight (click for curved)") } else { tr("Wires: curved (click for straight)") }, - straight, - ) { - app.ui.prefs.straight_wires = !straight; - } - let grid_on = app.ui.prefs.show_grid; - if toggle(ui, icon::DOTS_NINE, tr("Show the grid"), grid_on) { - app.ui.prefs.show_grid = !grid_on; - } - ui.separator(); - if button(ui, icon::ARROWS_CLOCKWISE, tr("Compute outputs")) { - app.cooker.hold = false; - app.session.dirty = true; - } - if button(ui, icon::BROOM, tr("Clean up: remove unconnected dots and disabled nodes with nothing attached")) { - super::toolbar_tools::clean_up(app); - } } fn row(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { @@ -182,10 +117,9 @@ fn button(ui: &mut Ui, icon: &str, tooltip: &str) -> bool { crate::widgets::icon_button(ui, icon, tooltip, false, 22.0).clicked() } -fn common(app: &mut MaterialCraftApp, ui: &mut Ui, selection_count: usize, embedded: bool, parameters: impl Fn() -> serde_json::Value) -> bool { +fn common(app: &mut MaterialCraftApp, ui: &mut Ui, selection_count: usize, parameters: impl Fn() -> serde_json::Value) -> bool { let frame = button(ui, icon::CORNERS_OUT, tr("Frame all (F)")); let can_align = selection_count > 1; - let stack = app.ui.stack_align; for (icon, mode, tooltip) in [ (icon::ALIGN_LEFT, "left", "Align left"), (icon::ALIGN_TOP, "top", "Align top"), @@ -197,25 +131,9 @@ fn common(app: &mut MaterialCraftApp, ui: &mut Ui, selection_count: usize, embed if ui.add_enabled_ui(can_align, |ui| button(ui, icon, tr(tooltip))).inner { let mut parameters = parameters(); parameters["mode"] = json!(mode); - app.run("graph.align", parameters.clone()); - // Stack: centring the nodes also closes the gaps between them - let also = match (stack, mode) { - (true, "hcenter") => Some("vdistribute"), - (true, "vcenter") => Some("hdistribute"), - _ => None, - }; - if let Some(mode) = also { - let mut again = parameters.clone(); - again["mode"] = json!(mode); - app.run("graph.align", again); - } + app.run("graph.align", parameters); } } - if !embedded { - let r = ui.checkbox(&mut app.ui.stack_align, tr("Stack")); - crate::widgets::name(&r, egui::Role::CheckBox, "Stack"); - r.on_hover_text(tr("Aligning the centers also closes the gaps between the nodes")); - } ui.separator(); if crate::widgets::icon_button(ui, icon::GRID_FOUR, tr("Snap to grid"), app.ui.prefs.snap_to_grid, 22.0).clicked() { crate::menus::invoke(app, ui.ctx(), "ui.graph.snapToGrid"); @@ -246,24 +164,10 @@ fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) { crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" }); }; - if crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset the parent size to 1024 x 1024"), false, 20.0).clicked() { - nw = 10; - nh = 10; - } combo(ui, "parent-h", &mut nh); - let link = app.ui.parent_link; - if crate::widgets::icon_button(ui, if link { icon::LINK } else { icon::LINK_BREAK }, tr("Link width and height"), link, 20.0).clicked() { - app.ui.parent_link = !link; - } + ui.label("x"); combo(ui, "parent-w", &mut nw); ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim)); - if app.ui.parent_link { - if nw != w { - nh = nw; - } else if nh != h { - nw = nh; - } - } if (nw, nh) != (w, h) { app.run("graph.size", json!({"log2": [nw, nh]})); } diff --git a/crates/ui-egui/src/graph/toolbar_tools.rs b/crates/ui-egui/src/graph/toolbar_tools.rs deleted file mode 100644 index c8e3a23..0000000 --- a/crates/ui-egui/src/graph/toolbar_tools.rs +++ /dev/null @@ -1,119 +0,0 @@ -//! The graph toolbar's view tools: actual-size zoom, a screenshot of the canvas, the graph -//! information popup and the clean-up action - -use egui::{RichText, Ui}; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// Zoom the graph camera to `zoom` around the view's center -pub(super) fn zoom_to(app: &mut MaterialCraftApp, zoom: f32) { - let c = super::view_center(app); - let v = app.graph.view; - let cam = &mut app.ui.graph_camera; - cam.zoom = zoom; - cam.pan = [c.x - v.width() * 0.5 / zoom, c.y - v.height() * 0.5 / zoom]; - *cam = cam.sanitized(); -} - -/// Save the graph panel as a PNG: a screenshot of the window, cropped to the canvas -pub(super) fn screenshot(app: &mut MaterialCraftApp, ctx: &egui::Context) { - #[cfg(not(target_arch = "wasm32"))] - { - let name = format!("{}_graph.png", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default())); - let Some(path) = crate::windows::dialog(app).set_file_name(name).add_filter("PNG", &["png"]).save_file() else { return }; - crate::windows::remember_dir(app, &path); - let view = app.graph.view; - let ppp = ctx.pixels_per_point(); - let repaint = ctx.clone(); - let callback = egui::ScreenshotCallback::new(move |img| { - let x0 = ((view.left() * ppp).max(0.0) as usize).min(img.size[0]); - let y0 = ((view.top() * ppp).max(0.0) as usize).min(img.size[1]); - let x1 = ((view.right() * ppp).max(0.0) as usize).clamp(x0, img.size[0]); - let y1 = ((view.bottom() * ppp).max(0.0) as usize).clamp(y0, img.size[1]); - let (w, h) = (x1 - x0, y1 - y0); - if w == 0 || h == 0 { - return; - } - let mut rgba = Vec::with_capacity(w * h * 4); - for y in y0..y1 { - for x in x0..x1 { - if let Some(px) = img.pixels.get(y * img.size[0] + x) { - rgba.extend_from_slice(&px.to_array()); - } - } - } - if let Some((_, _, png)) = crate::control::encode_png(w as u32, h as u32, rgba) - && let Err(e) = std::fs::write(&path, png) - { - log::warn!("could not save the graph screenshot {}: {e}", path.display()); - } - repaint.request_repaint(); - }); - ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); - app.toast(tr("Saving a screenshot of the graph"), false); - } - #[cfg(target_arch = "wasm32")] - { - let _ = ctx; - app.toast(tr("Screenshots are saved from the desktop app"), true); - } -} - -/// The ⓘ popup: what the graph is, how big and how long it takes -pub(super) fn graph_info(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let Ok(g) = app.session.graph() else { return }; - let [w, h] = g.size_px(); - let outputs = g.nodes.iter().filter(|n| n.def == "output").count(); - let errors = app.session.cooked.nodes.values().filter(|r| r.error.is_some()).count(); - let ms: f32 = app.session.cooked.nodes.values().map(|r| r.ms).sum(); - ui.set_min_width(220.0); - ui.label(RichText::new(&g.name).strong()); - ui.label(RichText::new(format!("{} ({})", app.session.pkg.name, app.session.path.as_deref().unwrap_or(tr("not saved yet")))).small().color(tk.text_dim)); - ui.separator(); - egui::Grid::new("graph-info").num_columns(2).spacing([12.0, 2.0]).show(ui, |ui| { - ui.label(tr("Size")); - ui.label(format!("{w} x {h}")); - ui.end_row(); - ui.label(tr("Format")); - ui.label(format!("{} bits", g.format.bits())); - ui.end_row(); - ui.label(tr("Nodes")); - ui.label(format!("{} ({} {})", g.nodes.len(), outputs, tr("outputs"))); - ui.end_row(); - ui.label(tr("Wires")); - ui.label(g.connections.len().to_string()); - ui.end_row(); - ui.label(tr("Last cook")); - ui.label(if errors > 0 { format!("{ms:.0} ms, {errors} {}", tr("error(s)")) } else { format!("{ms:.0} ms") }); - ui.end_row(); - ui.label(tr("Exposed")); - ui.label(g.exposed.len().to_string()); - ui.end_row(); - }); - ui.separator(); - if ui.button(tr("Graph attributes...")).clicked() { - app.run("edit.selectNone", json!({})); - app.ui.dock.focus(crate::docking::Panel::Properties); - ui.close(); - } -} - -/// Remove reroute dots nothing uses and disabled nodes with no wires -pub(super) fn clean_up(app: &mut MaterialCraftApp) { - let Ok(g) = app.session.graph() else { return }; - let wired = |id: materialcraft_engine::core::NodeId| g.connections.iter().any(|c| c.from == id || c.to == id); - let ids: Vec<u64> = - g.nodes.iter().filter(|n| (n.def == "dot" && !g.connections.iter().any(|c| c.from == n.id)) || (n.disabled && !wired(n.id))).map(|n| n.id.0).collect(); - if ids.is_empty() { - app.toast(tr("Nothing to clean up"), false); - return; - } - let n = ids.len(); - if app.run("graph.select", json!({"ids": ids})).is_some() && app.run("edit.delete", json!({})).is_some() { - app.toast(format!("{} {n}", tr("Removed nodes:")), false); - } -} diff --git a/crates/ui-egui/src/graph/wire_geometry.rs b/crates/ui-egui/src/graph/wire_geometry.rs index bf93f12..7bfb10a 100644 --- a/crates/ui-egui/src/graph/wire_geometry.rs +++ b/crates/ui-egui/src/graph/wire_geometry.rs @@ -4,23 +4,11 @@ use egui::{Color32, Pos2, Rect, Stroke, pos2}; /// Pointer distance in points within which a wire is hit pub(super) const WIRE_HIT: f32 = 5.0; -/// Wires are drawn straight this frame (the graph toolbar's wire style) -static STRAIGHT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Choose straight or curved wires for the frames that follow -pub(crate) fn set_straight(straight: bool) { - STRAIGHT.store(straight, std::sync::atomic::Ordering::Relaxed); -} - pub(crate) fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] { curve_points(a, b, egui::Vec2::X) } pub(crate) fn curve_points(source: Pos2, destination: Pos2, axis: egui::Vec2) -> [Pos2; 4] { - if STRAIGHT.load(std::sync::atomic::Ordering::Relaxed) { - let d = (destination - source) / 3.0; - return [source, source + d, source + d * 2.0, destination]; - } let offset = axis * ((destination - source).dot(axis).abs() * 0.5).max(30.0); [source, source + offset, destination - offset, destination] } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4d15138..d3878b4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,7 +17,6 @@ mod material_preview_menu; mod menu_item; pub mod menus; mod new_graph_dialog; -pub mod plugins; pub mod preferences; mod preview_resolution; #[path = "property/mod.rs"] @@ -25,13 +24,11 @@ pub mod properties; pub mod state; pub mod theme; pub mod thumbs; -pub mod tool_windows; pub mod toolbar; pub mod unsaved; mod value_input_editor; pub mod view2d; pub mod view3d; -pub mod view3d_props; pub mod web_files; pub mod widgets; pub mod windows; diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index 5f6dd8f..7815eba 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -1,8 +1,6 @@ -//! The library: a category tree on the left, the matching entries as preview tiles (or a list) -//! on the right, with search and favorites. Drag a tile into the graph, or double-click it to -//! add it next to the selection. Entries are the native primitives, graph items (frame, -//! comment, pin), function operations (for the function editor), the package's own graphs and -//! the graphs of loaded library packages (plugins), filed under their category attribute +//! The library: a category tree on the left, the matching nodes as preview tiles (or a list) on +//! the right, with search. Drag a tile into the graph, or double-click it to add it next to the +//! selection. use egui::{Color32, Rect, RichText, Sense, Ui, vec2}; use egui_phosphor::regular as icon; @@ -12,201 +10,34 @@ use crate::graph::{LibraryDrag, header_color}; use crate::i18n::tr; use crate::theme::Tokens; -/// The favorites pseudo-category -pub const FAVORITES: &str = "@favorites"; - -/// Where an entry comes from, and so what adding it does -#[derive(Clone, Debug, PartialEq)] -pub enum Kind { - /// A node of the catalog (`id` is its definition) - Node, - /// A frame, comment or navigation pin: `id` is the engine command - GraphItem, - /// A function operation for the function editor: `id` is the op - FnOp, - /// A graph of the open package: `id` is its name - PackageGraph, - /// A graph of a loaded library package: `id` is the graph, `package` the file it lives in - PluginGraph { package: String }, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Entry { - pub id: String, - pub label: String, - pub category: String, - pub kind: Kind, -} - -impl Entry { - fn new(id: impl Into<String>, label: impl Into<String>, category: impl Into<String>, kind: Kind) -> Entry { - Entry { id: id.into(), label: label.into(), category: category.into(), kind } - } - - /// The key favorites and drags use - pub fn key(&self) -> String { - match &self.kind { - Kind::Node => self.id.clone(), - Kind::GraphItem => format!("!{}", self.id), - Kind::FnOp => format!("fn:{}", self.id), - Kind::PackageGraph => format!("@{}", self.id), - Kind::PluginGraph { package } => format!("+{package}\n{}", self.id), - } - } - - /// The definition whose header colour the tile borrows - fn color_def(&self) -> &str { - match self.kind { - Kind::Node => &self.id, - Kind::GraphItem => "dot", - Kind::FnOp => "pixel_processor", - Kind::PackageGraph | Kind::PluginGraph { .. } => "graph_instance", - } - } -} - -/// The groups of the reference library, in order, with the sub-groups that exist before any -/// library package fills them (empty ones show greyed with a zero count) -const PLANNED: [(&str, &[&str]); 13] = [ - ("Graph items", &[]), - ("Atomic nodes", &[]), - ("FxMap nodes", &[]), - ("Function nodes", &[]), - ("Texture generators", &["Texture generators/Noises", "Texture generators/Patterns"]), - ( - "Filters", - &[ - "Filters/Adjustments", - "Filters/Blending", - "Filters/Blurs", - "Filters/Channels", - "Filters/Effects", - "Filters/Normal map", - "Filters/Tiling", - "Filters/Transforms", - ], - ), - ( - "Material filters", - &[ - "Material filters/1-click", - "Material filters/Effects", - "Material filters/Transforms", - "Material filters/Blending", - "Material filters/PBR utilities", - "Material filters/Scan processing", - ], - ), - ("Mesh-based generators", &[]), - ("Spline & Path tools", &[]), - ("MCF functions", &[]), - ("Functions", &[]), - ("PBR materials", &["PBR materials/This package", "PBR materials/Plugins"]), - ("Values", &["Values/Constant"]), -]; - -/// The tree in display order: (top level, sub-categories as full paths) -pub fn tree(entries: &[Entry]) -> Vec<(String, Vec<String>)> { - let mut out: Vec<(String, Vec<String>)> = PLANNED.iter().map(|(t, subs)| (t.to_string(), subs.iter().map(|s| s.to_string()).collect())).collect(); - let mut place = |cat: &str| { - let top = cat.split('/').next().unwrap_or(cat).to_string(); +/// The tree: (top level, its sub-categories as full category paths). +fn tree() -> Vec<(&'static str, Vec<&'static str>)> { + let mut out: Vec<(&'static str, Vec<&'static str>)> = Vec::new(); + for (cat, _) in materialcraft_engine::nodes::categories() { + let top = cat.split('/').next().unwrap_or(cat); match out.iter_mut().find(|(t, _)| *t == top) { Some((_, subs)) => { - if cat != top && !subs.iter().any(|s| s == cat) { - subs.push(cat.to_string()); + if cat != top { + subs.push(cat); } } - None => out.push((top.clone(), if cat != top { vec![cat.to_string()] } else { Vec::new() })), + None => out.push((top, if cat != top { vec![cat] } else { Vec::new() })), } - }; - for e in entries { - place(&e.category); } out } -/// The library path of a function operation group: constants are values, the rest function nodes -fn fn_path(group: &str) -> String { - if group == "Constant" { "Values/Constant".to_string() } else { format!("Function nodes/{group}") } -} - -/// The library path of a library package graph: its category attribute, else the plugins group -fn plugin_path(category: &str) -> String { - let c = category.trim(); - if c.is_empty() { "PBR materials/Plugins".to_string() } else { c.to_string() } -} - fn category_icon(top: &str) -> &'static str { match top { "Atomic nodes" => icon::CUBE, "Graph items" => icon::FLOW_ARROW, - "FxMap nodes" => icon::DICE_FIVE, - "Function nodes" | "Values" => icon::FUNCTION, - "Texture generators" => icon::WAVES, + "Texture generators" => icon::DICE_FIVE, "Filters" => icon::FADERS, "Material filters" => icon::SPHERE, - "Mesh-based generators" => icon::CUBE_TRANSPARENT, - "Spline & Path tools" => icon::BEZIER_CURVE, - "MCF functions" => icon::CIRCLES_THREE, - "Functions" => icon::GRAPH, - "PBR materials" => icon::PAINT_BUCKET, _ => icon::FOLDER_OPEN, } } -/// Every entry the library can show (unfiltered) -pub fn all_entries(app: &mut MaterialCraftApp) -> Vec<Entry> { - let mut out: Vec<Entry> = vec![ - Entry::new("graph.comment.add", tr("Comment"), "Graph items", Kind::GraphItem), - Entry::new("graph.frame.add", tr("Frame"), "Graph items", Kind::GraphItem), - Entry::new("graph.pin.add", tr("Pin"), "Graph items", Kind::GraphItem), - ]; - for d in materialcraft_engine::nodes::catalog() { - if d.id == "graph_instance" { - continue; - } - let category = if d.id == "fx_map" { "FxMap nodes" } else { d.category }; - out.push(Entry::new(d.id, d.label, category, Kind::Node)); - } - for op in materialcraft_engine::nodes::function::FUNCTIONS { - out.push(Entry::new(op.id, op.label, fn_path(op.category), Kind::FnOp)); - } - let open = app.session.graph; - for (i, g) in app.session.pkg.graphs.iter().enumerate() { - if i == open { - continue; - } - let cat = match g.kind() { - materialcraft_engine::core::GraphKind::Function => "Functions".to_string(), - materialcraft_engine::core::GraphKind::Material => { - let c = g.attributes.category.trim(); - if c.is_empty() { "PBR materials/This package".to_string() } else { c.to_string() } - } - }; - out.push(Entry::new(&g.name, &g.name, cat, Kind::PackageGraph)); - } - for (plugin, package, graph, category) in app.plugin_graphs() { - out.push(Entry::new(&graph, format!("{graph} · {plugin}"), plugin_path(&category), Kind::PluginGraph { package })); - } - out -} - -fn in_category(e: &Entry, cat: &str) -> bool { - cat.is_empty() || e.category == cat || e.category.starts_with(&format!("{cat}/")) -} - -/// Library entries for the current filter -fn entries(app: &mut MaterialCraftApp, all: &[Entry]) -> Vec<Entry> { - let search = app.ui.library_search.to_ascii_lowercase(); - let cat = app.ui.library_category.clone(); - let favs = &app.ui.library_favorites; - all.iter() - .filter(|e| if cat == FAVORITES { favs.contains(&e.key()) } else { in_category(e, &cat) }) - .filter(|e| search.is_empty() || e.label.to_ascii_lowercase().contains(&search) || e.id.to_ascii_lowercase().contains(&search)) - .cloned() - .collect() -} - pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { match crate::graph::editor_target::EditorTarget::resolve(app) { crate::graph::editor_target::EditorTarget::Function => { @@ -223,49 +54,34 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 130.0).max(40.0))); + let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 56.0).max(40.0))); crate::widgets::name(&r, egui::Role::SearchInput, "Search the library"); - if !app.ui.library_search.is_empty() && crate::widgets::icon_button(ui, icon::X, tr("Clear search"), false, 20.0).clicked() { - app.ui.library_search.clear(); - } - let fav = app.ui.library_category == FAVORITES; - if crate::widgets::icon_button(ui, icon::STAR, tr("Favorites"), fav, 20.0).clicked() { - app.ui.library_category = if fav { String::new() } else { FAVORITES.into() }; - } if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 20.0).clicked() { app.ui.prefs.library_list = false; } if crate::widgets::icon_button(ui, icon::LIST, tr("List"), app.ui.prefs.library_list, 20.0).clicked() { app.ui.prefs.library_list = true; } - if !app.ui.prefs.library_list { - ui.add(egui::Slider::new(&mut app.ui.prefs.library_tile, 56.0..=160.0).show_value(false)).on_hover_text(tr("Tile size")); - } }); ui.add_space(2.0); - let all = all_entries(app); let avail = ui.available_size(); - let tree_w = (avail.x * 0.36).clamp(90.0, 190.0); + let tree_w = (avail.x * 0.36).clamp(90.0, 170.0); let top_down = egui::Layout::top_down(egui::Align::Min); ui.horizontal_top(|ui| { ui.allocate_ui_with_layout(vec2(tree_w, avail.y), top_down, |ui| { - egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui, &all)); + egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui)); }); ui.separator(); ui.allocate_ui_with_layout(vec2(ui.available_width(), avail.y), top_down, |ui| { - egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all)); + egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui)); }); }); } -fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, all: &[Entry]) { +fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - let count = |cat: &str| all.iter().filter(|e| in_category(e, cat)).count(); - let mut select: Option<String> = None; - let mut toggle: Option<String> = None; - let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32, n: Option<usize>, arrow: Option<bool>| { + let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32| { let on = app.ui.library_category == path; - let empty = n == Some(0); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); crate::widgets::name(&resp, egui::Role::TreeItem, &text); if on { @@ -273,107 +89,83 @@ fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, all: &[Entry]) { } else if resp.hovered() { ui.painter().rect_filled(r, 4.0, tk.row_hover); } - let color = if empty { - tk.text_dim - } else if on { - tk.text_strong - } else { - tk.text - }; - let mut arrow_w = 0.0; - if let Some(open) = arrow { - arrow_w = 14.0; - let a = Rect::from_min_size(r.min + vec2(indent - 2.0, 0.0), vec2(14.0, r.height())); - ui.painter().text( - a.center(), - egui::Align2::CENTER_CENTER, - if open { icon::CARET_DOWN } else { icon::CARET_RIGHT }, - egui::FontId::proportional(10.0), - tk.text_dim, - ); - if resp.clicked() && resp.interact_pointer_pos().is_some_and(|p| a.contains(p)) { - toggle = Some(path.to_string()); - } else if resp.clicked() { - select = Some(path.to_string()); - } - } else if resp.clicked() { - select = Some(path.to_string()); - } - let label = match n { - Some(n) if n == 0 || indent > 10.0 => format!("{text} ({n})"), - _ => text, - }; - let g = crate::widgets::elided(ui.painter(), label, 11.5, color, r.width() - indent - arrow_w - 4.0); - ui.painter().galley(r.left_center() + vec2(indent + arrow_w, -g.size().y * 0.5), g, color); - if resp.double_clicked() && arrow.is_some() { - toggle = Some(path.to_string()); - } - if empty { - resp.on_hover_text(tr("Empty: library packages (Tools > Plugin Manager) fill this group with their graphs")); + let g = crate::widgets::elided(ui.painter(), text, 11.5, if on { tk.text_strong } else { tk.text }, r.width() - indent - 4.0); + ui.painter().galley(r.left_center() + vec2(indent, -g.size().y * 0.5), g, tk.text); + if resp.clicked() { + app.ui.library_category = path.to_string(); } }; - row(ui, format!("{} {}", icon::SQUARES_FOUR, tr("All nodes")), "", 4.0, None, None); - row(ui, format!("{} {}", icon::STAR, tr("Favorites")), FAVORITES, 4.0, Some(app.ui.library_favorites.len()), None); - for (top, subs) in tree(all) { - let open = !app.ui.library_collapsed.contains(&top); - let n = count(&top); - row(ui, format!("{} {}", category_icon(&top), tr(&top)), &top, 4.0, Some(n), if subs.is_empty() { None } else { Some(open) }); - if open { - for sub in subs { - let name = sub.rsplit('/').next().unwrap_or(&sub); - row(ui, tr(name).to_string(), &sub, 24.0, Some(count(&sub)), None); - } - } + row(ui, format!("{} {}", icon::SQUARES_FOUR, tr("All nodes")), "", 4.0); + if app.session.pkg.graphs.len() > 1 { + row(ui, format!("{} {}", icon::TREE_STRUCTURE, tr("This package")), "@package", 4.0); } - if let Some(p) = select { - app.ui.library_category = p; - } - if let Some(t) = toggle { - if app.ui.library_collapsed.contains(&t) { - app.ui.library_collapsed.retain(|c| *c != t); - } else { - app.ui.library_collapsed.push(t); + for (top, subs) in tree() { + row(ui, format!("{} {}", category_icon(top), tr(top)), top, 4.0); + for sub in subs { + let name = sub.rsplit('/').next().unwrap_or(sub); + row(ui, tr(name).to_string(), sub, 22.0); } } } -fn items(app: &mut MaterialCraftApp, ui: &mut Ui, all: &[Entry]) { +/// Library entries for the current filter: (id, label, category, is a package graph). +fn entries(app: &MaterialCraftApp) -> Vec<(String, String, &'static str, bool)> { + let search = app.ui.library_search.to_ascii_lowercase(); + let cat = &app.ui.library_category; + let mut out: Vec<(String, String, &'static str, bool)> = Vec::new(); + if cat == "@package" || !search.is_empty() { + for (i, g) in app.session.pkg.graphs.iter().enumerate() { + if i != app.session.graph && (search.is_empty() || g.name.to_ascii_lowercase().contains(&search)) { + out.push((g.name.clone(), g.name.clone(), "This package", true)); + } + } + if cat == "@package" { + return out; + } + } + for d in materialcraft_engine::nodes::catalog() { + if d.id == "graph_instance" { + continue; + } + if !(cat.is_empty() || d.category == cat || d.category.starts_with(&format!("{cat}/"))) { + continue; + } + if !(search.is_empty() || d.label.to_ascii_lowercase().contains(&search) || d.id.contains(&search)) { + continue; + } + out.push((d.id.to_string(), d.label.to_string(), d.category, false)); + } + out +} + +fn items(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let list = entries(app, all); + let list = entries(app); if list.is_empty() { - let hint = if app.ui.library_category == FAVORITES { - tr("No favorites yet: right-click a tile and choose Add to favorites") - } else if app.ui.library_search.is_empty() { - tr("Nothing here yet: library packages (Tools > Plugin Manager) fill this group with their graphs") - } else { - tr("Nothing matches") - }; - ui.label(RichText::new(hint).color(tk.text_dim)); + ui.label(RichText::new(tr("Nothing matches")).color(tk.text_dim)); return; } let as_list = app.ui.prefs.library_list; - let side = app.ui.prefs.library_tile.clamp(56.0, 160.0); - let tile = vec2(side, side + 20.0); + let tile = vec2(78.0, 98.0); let cols = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize }; - let mut add: Option<Entry> = None; - let mut star: Option<(String, bool)> = None; + let mut add: Option<(String, bool)> = None; for chunk in list.chunks(cols) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); - for e in chunk { + for (id, label, cat, is_graph) in chunk { let size = if as_list { vec2(ui.available_width(), 26.0) } else { tile }; let (r, resp) = ui.allocate_exact_size(size, Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::ListItem, &e.label); - let def_id = e.color_def(); + crate::widgets::name(&resp, egui::Role::ListItem, label); + let def_id = if *is_graph { "graph_instance" } else { id.as_str() }; if resp.hovered() { ui.painter().rect_filled(r, 6.0, tk.row_hover); } - let tex = if e.kind == Kind::Node { app.thumbs.library(&ctx, &e.id) } else { None }; + let tex = if *is_graph { None } else { app.thumbs.library(&ctx, id) }; let img_rect = if as_list { Rect::from_min_size(r.min + vec2(2.0, 2.0), vec2(22.0, 22.0)) } else { - Rect::from_min_size(r.min + vec2(5.0, 4.0), vec2(side - 10.0, side - 10.0)) + Rect::from_min_size(r.min + vec2(5.0, 4.0), vec2(68.0, 68.0)) }; match tex { Some(t) => { @@ -381,165 +173,42 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui, all: &[Entry]) { } None => { ui.painter().rect_filled(img_rect, 4.0, header_color(def_id).gamma_multiply(0.7)); - let glyph = match &e.kind { - Kind::Node => icon::CUBE, - Kind::GraphItem => icon::NOTE_PENCIL, - Kind::FnOp => icon::FUNCTION, - Kind::PackageGraph => icon::TREE_STRUCTURE, - Kind::PluginGraph { .. } => icon::PUZZLE_PIECE, - }; ui.painter().text( img_rect.center(), egui::Align2::CENTER_CENTER, - glyph, + if *is_graph { icon::TREE_STRUCTURE } else { icon::CUBE }, egui::FontId::proportional(img_rect.height() * 0.4), Color32::WHITE, ); } } - // The category color as a strip, like the node headers + // The category color as a strip, like the node headers. let strip = Rect::from_min_size(img_rect.left_bottom() - vec2(0.0, 3.0), vec2(img_rect.width(), 3.0)); ui.painter().rect_filled(strip, 0.0, header_color(def_id)); - let key = e.key(); - let starred = app.ui.library_favorites.contains(&key); - if starred { - ui.painter().text( - img_rect.right_top() + vec2(-3.0, 3.0), - egui::Align2::RIGHT_TOP, - icon::STAR, - egui::FontId::proportional(11.0), - Color32::from_rgb(0xf5, 0xc5, 0x42), - ); - } if as_list { - let g = crate::widgets::elided(ui.painter(), e.label.clone(), 11.5, tk.text, r.width() - 34.0); + let g = crate::widgets::elided(ui.painter(), label.clone(), 11.5, tk.text, r.width() - 34.0); ui.painter().galley(r.left_center() + vec2(30.0, -g.size().y * 0.5), g, tk.text); } else { - let galley = ui.painter().layout(e.label.clone(), egui::FontId::proportional(10.5), tk.text, tile.x - 4.0); + let galley = ui.painter().layout(label.clone(), egui::FontId::proportional(10.5), tk.text, tile.x - 4.0); let pos = egui::pos2(r.center().x - galley.size().x * 0.5, img_rect.bottom() + 3.0); ui.painter().galley(pos, galley, tk.text); } - let hint = match &e.kind { - Kind::FnOp => format!("{}\n{}\n{}", e.label, e.category, tr("Function operation: for the function editor")), - Kind::PluginGraph { package } => format!("{}\n{}\n{package}", e.label, e.category), - _ => format!("{}\n{}", e.label, e.category), - }; - let resp = resp.on_hover_text(hint); + let resp = resp.on_hover_text(format!("{label}\n{cat}")); if resp.drag_started() { - egui::DragAndDrop::set_payload(&ctx, LibraryDrag(key.clone())); + let payload = if *is_graph { format!("@{id}") } else { id.clone() }; + egui::DragAndDrop::set_payload(&ctx, LibraryDrag(payload)); } if resp.double_clicked() { - add = Some(e.clone()); + add = Some((id.clone(), *is_graph)); } - resp.context_menu(|ui| { - if ui.button(tr("Add to graph")).clicked() { - add = Some(e.clone()); - ui.close(); - } - let label = if starred { tr("Remove from favorites") } else { tr("Add to favorites") }; - if ui.button(label).clicked() { - star = Some((key.clone(), !starred)); - ui.close(); - } - }); } }); } - if let Some((key, on)) = star { - app.ui.library_favorites.retain(|k| *k != key); - if on { - app.ui.library_favorites.push(key); - app.ui.library_favorites.truncate(500); + if let Some((id, is_graph)) = add { + if is_graph { + app.run("graph.node.add", serde_json::json!({"def": "graph_instance", "params": {"graph": id}})); + } else { + crate::graph::add_node_near_selection(app, &id); } } - if let Some(e) = add { - add_entry(app, &e, None); - } -} - -/// Add a library entry to the graph (double-click, context menu), or at `at` (a drop) -pub fn add_entry(app: &mut MaterialCraftApp, e: &Entry, at: Option<[f32; 2]>) { - match &e.kind { - Kind::Node => match at { - Some(at) => { - app.run("graph.node.add", serde_json::json!({"def": e.id, "at": at})); - } - None => crate::graph::add_node_near_selection(app, &e.id), - }, - Kind::GraphItem => add_graph_item(app, &e.id, at), - Kind::FnOp => app.toast(tr("Function operations go into a function graph: open one from a Pixel Processor or Value Processor first"), true), - Kind::PackageGraph => { - let mut p = serde_json::json!({"def": "graph_instance", "params": {"graph": e.id}}); - if let Some(at) = at { - p["at"] = serde_json::json!(at); - } - app.run("graph.node.add", p); - } - Kind::PluginGraph { package } => app.add_plugin_graph(package, &e.id, at), - } -} - -/// A frame (around the selection, or an empty one at `at`), a comment or a pin -fn add_graph_item(app: &mut MaterialCraftApp, cmd: &str, at: Option<[f32; 2]>) { - let c = crate::graph::view_center(app); - let at = at.unwrap_or([c.x - 60.0, c.y - 20.0]); - let params = match cmd { - "graph.frame.add" if app.session.selection.is_empty() => serde_json::json!({"rect": [at[0], at[1], 320.0, 200.0]}), - "graph.frame.add" => serde_json::json!({}), - _ => serde_json::json!({"at": at}), - }; - app.run(cmd, params); -} - -/// Add whatever a library drag key names at `at` (the graph view's drop handler) -pub fn add_key(app: &mut MaterialCraftApp, key: &str, at: [f32; 2]) { - if let Some(cmd) = key.strip_prefix('!') { - add_graph_item(app, cmd, Some(at)); - } else if key.starts_with("fn:") { - app.toast(tr("Function operations go into a function graph: open one from a Pixel Processor or Value Processor first"), true); - } else if let Some(plugin) = key.strip_prefix('+') { - if let Some((pkg, graph)) = plugin.split_once('\n') { - app.add_plugin_graph(pkg, graph, Some(at)); - } - } else if let Some(graph) = key.strip_prefix('@') { - app.run("graph.node.add", serde_json::json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})); - } else { - app.run("graph.node.add", serde_json::json!({"def": key, "at": at})); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_tree_lists_every_catalog_category_once_and_the_planned_groups() { - let entries: Vec<Entry> = materialcraft_engine::nodes::catalog().iter().map(|d| Entry::new(d.id, d.label, d.category, Kind::Node)).collect(); - let t = tree(&entries); - for (cat, _) in materialcraft_engine::nodes::categories() { - let top = cat.split('/').next().unwrap_or(cat); - let hits = t.iter().filter(|(c, subs)| c == top && (cat == top || subs.iter().any(|s| s == cat))).count(); - assert_eq!(hits, 1, "{cat} appears once"); - } - let tops: Vec<_> = t.iter().map(|(c, _)| c.clone()).collect(); - let mut dedup = tops.clone(); - dedup.dedup(); - assert_eq!(tops, dedup, "no duplicate top-level groups"); - assert!(tops.iter().any(|t| t == "Texture generators")); - // A library package graph with a category attribute lands in that group - let plugin = Entry::new("Clouds", "Clouds", plugin_path("Texture generators/Noises"), Kind::PluginGraph { package: "x.sbs".into() }); - let t = tree(&[plugin]); - assert!(t.iter().any(|(c, subs)| c == "Texture generators" && subs.iter().any(|s| s == "Texture generators/Noises"))); - assert_eq!(plugin_path(" "), "PBR materials/Plugins"); - } - - #[test] - fn keys_round_trip_through_the_drop_handler_prefixes() { - let plugin = Entry::new("Rust", "Rust", "PBR materials/Plugins", Kind::PluginGraph { package: "C:/p/x.sbs".into() }); - assert_eq!(plugin.key(), "+C:/p/x.sbs\nRust"); - assert_eq!(Entry::new("blur", "Blur", "Atomic nodes", Kind::Node).key(), "blur"); - assert_eq!(Entry::new("Base", "Base", "PBR materials/This package", Kind::PackageGraph).key(), "@Base"); - assert_eq!(Entry::new("add", "Add", "Function nodes/Operator", Kind::FnOp).key(), "fn:add"); - assert_eq!(Entry::new("graph.pin.add", "Pin", "Graph items", Kind::GraphItem).key(), "!graph.pin.add"); - } } diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 65ad44f..360aa06 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -15,6 +15,7 @@ pub struct MaterialCraftApp { pub cooker: cook::Cooker, /// Node output thumbnails and library previews pub thumbs: thumbs::Thumbs, + pub(crate) template_previews: windows::TemplatePreviews, /// The graph editor's gesture state pub graph: graph::GraphView, pub view3d: view3d::View3dState, @@ -22,21 +23,6 @@ pub struct MaterialCraftApp { /// Embedded graph editors in the main graph panel pub pattern_editor: Option<pattern::PatternEditor>, pub function_editor: Option<function::FunctionEditor>, - /// The plugins folder's packages (Tools ▸ Plugin Manager) - pub plugins: crate::plugins::Plugins, - /// A graph copied in the explorer - pub explorer_clipboard: crate::explorer::GraphClipboard, - /// The explorer's rename-in-place field - pub explorer_rename: crate::explorer::Rename, - /// Import graph: the package file picked and its graphs, waiting for a choice - pub import_pick: Option<(String, Vec<String>)>, - /// The 3D view property page shown in the Properties panel, and the selection when it opened - /// (selecting a node closes it) - pub props3d: Option<(view3d::Page3d, Vec<materialcraft_engine::core::NodeId>)>, - /// The Preferences window's working copy - pub prefs_editor: crate::preferences::PrefsEditor, - /// The cache size last pushed into the session (MB; preferences) - applied_cache_mb: u32, pub(crate) graph_parents: Vec<graph::graph_parent::GraphParent>, /// Synthetic input from the control channel, fed to egui on the next frames pub input_queue: VecDeque<control::Scripted>, @@ -68,17 +54,6 @@ impl MaterialCraftApp { i18n::set_language(&app.ui.prefs.language); app.fonts_ready = true; app.ui.windows.home = app.ui.prefs.show_home; - // The 3D view's saved default state, else the default lighting preference - match app.ui.view3d_default.clone() { - Some(state) => { - app.run("view.3d.loadState", serde_json::json!({"state": state})); - } - None => { - let [ambient, p1, p2] = app.ui.prefs.default_lights; - app.run("view.3d", serde_json::json!({"lights": {"ambientOn": ambient, "point": [{"on": p1}, {"on": p2}]}})); - } - } - app.view3d.show_env = !app.ui.prefs.env_hidden; app } @@ -94,17 +69,11 @@ impl MaterialCraftApp { toasts: Vec::new(), cooker: cook::Cooker::default(), thumbs: thumbs::Thumbs::default(), + template_previews: windows::TemplatePreviews::default(), graph: graph::GraphView::default(), view3d: view3d::View3dState::default(), view2d: view2d::View2dState::default(), function_editor: None, - plugins: crate::plugins::Plugins::default(), - explorer_clipboard: crate::explorer::GraphClipboard::default(), - explorer_rename: crate::explorer::Rename::default(), - import_pick: None, - props3d: None, - prefs_editor: crate::preferences::PrefsEditor::default(), - applied_cache_mb: u32::MAX, graph_parents: Vec::new(), pattern_editor: None, input_queue: VecDeque::new(), @@ -128,14 +97,6 @@ impl MaterialCraftApp { /// Push the preferences that live in the session (preview size, 3D camera) pub fn apply_prefs(&mut self) { - self.cooker.threads = self.ui.prefs.cook_threads; - let p = &self.ui.prefs; - if self.session.max_undo != p.history_size as usize || self.session.cook_limit.unwrap_or(0) != p.cook_limit || p.cache_mb != self.applied_cache_mb { - self.applied_cache_mb = p.cache_mb; - let settings = serde_json::json!({"historySize": p.history_size.clamp(1, 10_000), "cacheMb": if p.cache_mb == 0 { 1024 } else { p.cache_mb }, "cookLimit": p.cook_limit}); - let _ = materialcraft_engine::execute(&mut self.session, "session.settings", &settings); - } - self.ui.recent.truncate(self.ui.prefs.recent_count.clamp(1, 50) as usize); if self.session.camera != self.ui.prefs.camera.sanitized() { self.session.set_camera_prefs(self.ui.prefs.camera); } @@ -167,7 +128,6 @@ impl MaterialCraftApp { } } - let graph_before = (self.session.graph, self.session.pkg.graphs.len()); match cook::execute_guarded(&mut self.session, id, ¶ms) { Ok(v) => { if id == "view.previewSize" { @@ -177,17 +137,6 @@ impl MaterialCraftApp { if matches!(id, "view.3d.assign" | "view.3d.outputs") { self.ui.dock.focus(docking::Panel::View3d); } - if id == "graph.node.add" && self.ui.prefs.auto_display_new_node { - // Preferences ▸ Graph: a new node shows in the 2D view - if let Some(n) = v.get("id").and_then(Value::as_u64) { - let _ = cook::execute_guarded(&mut self.session, "view.2d", &serde_json::json!({"node": n, "port": 0})); - } - } - if (self.session.graph, self.session.pkg.graphs.len()) != graph_before - && matches!(id, "graph.open" | "file.new" | "file.open" | "file.newPackage" | "file.importGraph" | "graph.add" | "graph.duplicate") - { - self.graph_opened(); - } Some(v) } Err(e) => { @@ -197,20 +146,6 @@ impl MaterialCraftApp { } } - /// Preferences ▸ Graph: what happens when a graph opens (3D view, 2D view, frame all) - fn graph_opened(&mut self) { - self.ui.frame_all = true; - if self.ui.prefs.view_3d_on_open && !self.ui.dock.is_open(docking::Panel::View3d) { - self.ui.dock.toggle(docking::Panel::View3d); - } - let output = self.session.graph().ok().and_then(|g| g.nodes.iter().find(|n| n.def == "output").map(|n| n.id.0)); - if self.ui.prefs.view_2d_on_open - && let Some(out) = output - { - let _ = cook::execute_guarded(&mut self.session, "view.2d", &serde_json::json!({"node": out, "port": 0})); - } - } - pub(crate) fn close_subgraph_after(&mut self, command: &str) { if command.starts_with("file.new") || matches!(command, "file.open" | "graph.open" | "graph.delete" | "graph.duplicate") { self.graph.inspected_node = None; @@ -255,20 +190,10 @@ impl MaterialCraftApp { return; } self.next_autosave = now + period; - let dir = if self.ui.prefs.temp_dir.trim().is_empty() { user_dir("autosave") } else { std::path::PathBuf::from(self.ui.prefs.temp_dir.trim()) }; - let stem = materialcraft_engine::formats::safe_file_name(&self.session.pkg.name); - let path = dir.join(format!("{stem}.sbs")); - let versions = self.ui.prefs.backup_versions.clamp(1, 50) as usize; + let dir = user_dir("autosave"); + let path = dir.join(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name))); let pkg = self.session.pkg.clone(); let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || { - // Older backups shift down one slot: name.sbs, name.1.sbs, name.2.sbs, … - let slot = |i: usize| if i == 0 { dir.join(format!("{stem}.sbs")) } else { dir.join(format!("{stem}.{i}.sbs")) }; - for i in (1..versions).rev() { - if slot(i - 1).exists() { - let _ = std::fs::rename(slot(i - 1), slot(i)); - } - } - let _ = std::fs::remove_file(slot(versions)); let result = std::fs::create_dir_all(&dir) .map_err(|e| e.to_string()) .and_then(|_| materialcraft_engine::formats::sbs::write_sbs(&pkg).map_err(|e| e.to_string())) @@ -363,9 +288,7 @@ impl MaterialCraftApp { // Tab can focus a menu or toolbar button while drawing; preserve keyboard ownership self.graph.keyboard_was_focused = ctx.egui_wants_keyboard_input(); menus::menu_bar(self, ui); - if self.ui.prefs.show_main_toolbar { - toolbar::main_toolbar(self, ui); - } + toolbar::main_toolbar(self, ui); toolbar::status_bar(self, ui); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); windows::show(self, &ctx); diff --git a/crates/ui-egui/src/material_craft_app.test.rs b/crates/ui-egui/src/material_craft_app.test.rs index 27fe46b..70d337d 100644 --- a/crates/ui-egui/src/material_craft_app.test.rs +++ b/crates/ui-egui/src/material_craft_app.test.rs @@ -46,7 +46,7 @@ mod unsaved_state_tests { let mut a = app(false); guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() }); assert!(a.ui.windows.unsaved.is_none()); - assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("Material_Graph"), "the empty package replaced it"); + assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("New_graph"), "the empty package replaced it"); } #[test] diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5818a79..b8e1aa8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -23,11 +23,6 @@ const fn sep(menu: &'static str) -> MenuItem { pub const TOP: [&str; 5] = ["File", "Edit", "Tools", "Windows", "Help"]; -/// MaterialCraft's page on the ArtCraft site (downloads, requirements, documentation) -pub const WEBSITE: &str = "https://getartcraft.com/apps/materialcraft"; -/// The ArtCraft community -pub const DISCORD: &str = "https://discord.gg/artcraft"; - /// The menu catalog (the target menu tree with our ids) pub const CATALOG: &[MenuItem] = &[ sub("File", "New", "Graph...", "ui.newGraph", Some("Ctrl+N")), @@ -37,14 +32,9 @@ pub const CATALOG: &[MenuItem] = &[ sep("File"), it("File", "Save", "file.save", Some("Ctrl+S")), it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")), - it("File", "Save a copy as...", "file.saveCopy", None), - it("File", "Save all", "ui.saveAll", None), - it("File", "Export with dependencies...", "file.exportWithDependencies", None), it("File", "Close all", "ui.closeAll", None), sep("File"), it("File", "Import bitmap...", "file.importBitmap", None), - it("File", "Link bitmap...", "file.linkBitmap", None), - it("File", "Import graph from a package...", "file.importGraph", None), it("File", "Export outputs...", "ui.export", Some("Ctrl+Shift+E")), it("File", "Export material...", "file.exportMaterial", None), it("File", "Send to TextureCraft", "file.sendToTextureCraft", None), @@ -73,10 +63,6 @@ pub const CATALOG: &[MenuItem] = &[ it("Tools", "Next pin", "ui.graph.nextPin", Some("F2")), it("Tools", "View outputs in 3D view", "ui.graph.viewOutputs", None), it("Tools", "Reset and view outputs in 3D view", "ui.graph.resetViewOutputs", None), - sep("Tools"), - it("Tools", "Switch engine...", "ui.switchEngine", Some("F9")), - it("Tools", "Cancel rendering", "ui.cancelRender", Some("Escape")), - it("Tools", "Suspend engine", "ui.suspendEngine", None), it("Tools", "Clear cache", "ui.clearCache", None), sub("Tools", "Preview size", "256 px", "ui.preview.256", None), sub("Tools", "Preview size", "512 px", "ui.preview.512", None), @@ -84,8 +70,6 @@ pub const CATALOG: &[MenuItem] = &[ sub("Tools", "Preview size", "2048 px", "ui.preview.2048", None), sub("Tools", "Preview size", "Full size", "ui.preview.0", None), it("Tools", "Create graph from selection", "graph.createFromSelection", None), - sep("Tools"), - it("Tools", "Plugin Manager...", "ui.pluginManager", None), it("Windows", "Explorer", "ui.view.explorer", None), it("Windows", "Graph", "ui.view.graph", None), it("Windows", "Properties", "ui.view.properties", None), @@ -94,30 +78,16 @@ pub const CATALOG: &[MenuItem] = &[ it("Windows", "2D View", "ui.view.2d", None), it("Windows", "Library", "ui.view.library", None), it("Windows", "History", "ui.view.history", None), - it("Windows", "Dependency Manager", "ui.view.dependencies", None), sep("Windows"), - it("Windows", "Main toolbar", "ui.view.mainToolbar", None), - sub("Windows", "New", "Explorer", "ui.new.explorer", None), - sub("Windows", "New", "3D View", "ui.new.3d", None), - sub("Windows", "New", "Library", "ui.new.library", None), - sep("Windows"), - it("Windows", "Unmaximize panel", "ui.unmaximize", Some("Shift+Space")), + it("Windows", "Restore panel layout", "ui.unmaximize", Some("Shift+Space")), it("Windows", "Reset layout", "ui.resetLayout", None), it("Help", "Home screen...", "ui.home", None), it("Help", "Documentation...", "ui.help.docs", None), - it("Help", "Tutorials...", "ui.help.tutorials", None), it("Help", "Shortcuts list...", "ui.help.shortcuts", None), sep("Help"), - it("Help", "Release notes...", "ui.help.releaseNotes", None), - it("Help", "What's new (ArtCraft news)...", "ui.help.whatsNew", None), - it("Help", "System requirements (FAQ)...", "ui.help.requirements", None), - it("Help", "Automation (control protocol)...", "ui.help.automation", None), - sep("Help"), it("Help", "Join the community (Discord)...", "ui.help.discord", None), - it("Help", "MaterialCraft on getartcraft.com...", "ui.help.website", None), - it("Help", "Support and feedback...", "ui.help.feedback", None), - it("Help", "Report a bug (GitHub)...", "ui.help.bug", None), - it("Help", "Export log...", "ui.help.exportLog", None), + it("Help", "ArtCraft website...", "ui.help.website", None), + it("Help", "Report a bug...", "ui.help.bug", None), sep("Help"), it("Help", "About MaterialCraft...", "ui.about", None), ]; @@ -141,11 +111,7 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool { } if is_ui(id) { - return match id { - "ui.cancelRender" => app.cooker.busy(), - "ui.unmaximize" => app.ui.dock.maximized.is_some(), - _ => true, - }; + return id != "ui.unmaximize" || app.ui.dock.maximized().is_some(); } materialcraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok()) } @@ -183,64 +149,24 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), "ui.preferences" => app.ui.windows.preferences = true, - "ui.pluginManager" => app.ui.windows.plugin_manager = true, - "ui.switchEngine" => app.ui.windows.switch_engine = true, - "ui.view.dependencies" => app.ui.windows.dependencies = !app.ui.windows.dependencies, - "ui.view.mainToolbar" => app.ui.prefs.show_main_toolbar = !app.ui.prefs.show_main_toolbar, - "ui.saveAll" => invoke(app, ctx, "file.save"), - "ui.cancelRender" => crate::cook::cancel(app), - "ui.suspendEngine" => { - app.cooker.suspended = !app.cooker.suspended; - if !app.cooker.suspended { - app.session.dirty = true; - } - let msg = if app.cooker.suspended { tr("Engine suspended: nothing computes until it is resumed") } else { tr("Engine resumed") }; - app.toast(msg, false); - } - "ui.new.explorer" => app.ui.dock.focus(crate::docking::Panel::Explorer), - "ui.new.3d" => app.ui.dock.focus(crate::docking::Panel::View3d), - "ui.new.library" => app.ui.dock.focus(crate::docking::Panel::Library), - "ui.unmaximize" => app.ui.dock.maximized = None, - "ui.view.graph" => {} + "ui.view.graph" => app.ui.dock.focus(crate::docking::Panel::Graph), + "ui.unmaximize" => app.ui.dock.restore(), "ui.resetLayout" => app.ui.dock = crate::docking::Dock::default(), - // These replace the open package: ask first when it has unsaved changes. + // Replacing the open package needs confirmation for unsaved changes "ui.closeAll" | "file.newPackage" => crate::unsaved::guard(app, crate::unsaved::Guarded::Menu { id: id.to_string() }), - "ui.clearCache" => { + "ui.reloadResources" | "ui.clearCache" => { if let Ok(mut c) = app.session.cache.lock() { c.clear(); } app.session.dirty = true; } - "ui.reloadResources" => { - if let Some(r) = app.run("file.reloadResources", Value::Null) { - let n = r["reloaded"].as_array().map_or(0, Vec::len); - let missing = r["missing"].as_array().map_or(0, Vec::len); - if let Ok(mut c) = app.session.cache.lock() { - c.clear(); - } - app.session.dirty = true; - let msg = match (n, missing) { - (0, 0) => tr("Resources reloaded: nothing had changed").to_string(), - (n, 0) => format!("{} {n}", tr("Resources reloaded:")), - (n, m) => format!("{} {n}, {} {m} ({})", tr("Resources reloaded:"), tr("missing:"), tr("see the Console")), - }; - app.toast(msg, missing > 0); - } - } "ui.home" => app.ui.windows.home = true, "ui.help.shortcuts" => app.ui.windows.shortcuts = true, "ui.about" => app.ui.windows.about = true, - "ui.help.discord" => ctx.open_url(egui::OpenUrl::new_tab(DISCORD)), - "ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab(WEBSITE)), - "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab(WEBSITE)), - "ui.help.tutorials" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/tutorials")), - "ui.help.releaseNotes" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/releases")), - "ui.help.whatsNew" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/news")), - "ui.help.requirements" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/faq")), - "ui.help.automation" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/blob/main/docs/control-protocol.md")), - "ui.help.feedback" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/support")), + "ui.help.discord" => ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft")), + "ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/apps/materialcraft")), + "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft#readme")), "ui.help.bug" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/issues")), - "ui.help.exportLog" => crate::tool_windows::export_log(app), _ => { if crate::windows::file_action(app, ctx, id) { return; @@ -314,9 +240,6 @@ fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, let checked = match item.id { "ui.view.graph" => Some(true), "ui.graph.snapToGrid" => Some(app.ui.prefs.snap_to_grid), - "ui.view.mainToolbar" => Some(app.ui.prefs.show_main_toolbar), - "ui.view.dependencies" => Some(app.ui.windows.dependencies), - "ui.suspendEngine" => Some(app.cooker.suspended), id if id.starts_with("ui.preview.") => id.strip_prefix("ui.preview.").and_then(|s| s.parse::<u32>().ok()).map(|s| s == app.ui.prefs.preview_size), id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)), }; @@ -366,9 +289,9 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { } } - let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect(); - // A disabled item leaves its key alone (Escape closes dialogs unless a cook is running) - table.retain(|(id, _)| !is_ui(id) || enabled(app, id)); + // The dock handles Shift+Space with the current panel's hit test + let mut table: Vec<(&'static str, KeyboardShortcut)> = + CATALOG.iter().filter(|item| item.id != "ui.unmaximize").filter_map(|item| Some((item.id, parse_shortcut(item.shortcut?)?))).collect(); for c in materialcraft_engine::command_specs() { if table.iter().any(|(id, _)| *id == c.id) { continue; @@ -391,30 +314,6 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { for id in fire { invoke(app, ctx, id); } - // Node creation shortcuts (Preferences ▸ Shortcuts): add the node next to the selection - let node_keys: Vec<(String, KeyboardShortcut)> = app.ui.node_shortcuts.iter().filter_map(|(def, sc)| Some((def.clone(), parse_shortcut(sc)?))).collect(); - let mut add: Vec<String> = Vec::new(); - ctx.input_mut(|i| { - for (def, sc) in &node_keys { - if i.consume_shortcut(sc) { - add.push(def.clone()); - } - } - }); - for def in add { - if app.ui.dock.is_open(crate::docking::Panel::Graph) { - crate::graph::add_node_near_selection(app, &def); - } - } -} - -/// A context-menu row with an optional shortcut hint on the right -pub fn menu_row(ui: &mut egui::Ui, label: &str, key: &str, enabled: bool) -> egui::Response { - let mut b = egui::Button::new(label); - if !key.is_empty() { - b = b.shortcut_text(key); - } - ui.add_enabled(enabled, b) } /// Menu items for `ui.menu.list` diff --git a/crates/ui-egui/src/new_graph_dialog.rs b/crates/ui-egui/src/new_graph_dialog.rs index a2e7d67..f845d5b 100644 --- a/crates/ui-egui/src/new_graph_dialog.rs +++ b/crates/ui-egui/src/new_graph_dialog.rs @@ -1,136 +1,48 @@ -//! File ▸ New ▸ Graph: template tiles by category (the starters, and the graphs of loaded -//! library packages), a template description, the name, a linked width/height and the package -//! the graph goes into - -use egui::{Color32, RichText, vec2}; +use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as icon; +use materialcraft_engine::{core::GraphKind, samples::TEMPLATES}; use serde_json::json; -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; -/// One tile of the dialog -#[derive(Clone, Debug, PartialEq)] -struct Template { - /// A starter template id, or `+<package>\n<graph>` for a library package graph - id: String, - label: String, - group: String, - info: String, -} - -/// What a starter template holds (the ⓘ on its tile) -fn starter_info(id: &str) -> &'static str { - match id { - "empty" => "A graph with no nodes: start from the library.", - "pbr" => { - "The material outputs (Base Color, Normal, Roughness, Metallic, Height, Ambient Occlusion) with uniform colors wired in; the normal is derived from the height." - } - "atomics" => "The atomic sample: a value input, a function, a pixel processor, an FX-Map pattern and a blur, with an image and a value output.", - _ => "A graph template.", - } -} - -fn templates(app: &mut MaterialCraftApp) -> Vec<Template> { - let mut out: Vec<Template> = materialcraft_engine::samples::TEMPLATES - .iter() - .map(|(id, label)| Template { id: id.to_string(), label: label.to_string(), group: "Starter".into(), info: starter_info(id).into() }) - .collect(); - for (plugin, package, graph, category) in app.plugin_graphs() { - let group = if category.trim().is_empty() { plugin.clone() } else { category.clone() }; - out.push(Template { - id: format!("+{package}\n{graph}"), - label: graph.clone(), - group, - info: format!( - "{} {plugin}: {}", - tr("From the library package"), - tr("the graph is copied into your package with the graphs it instances and the bitmaps it uses.") - ), - }); - } - out -} - -pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { - use materialcraft_engine::core::GraphKind; +pub(crate) fn show(app: &mut MaterialCraftApp, context: &egui::Context) { let mut open = true; let mut create = false; - let list = templates(app); - let groups: Vec<String> = { - let mut g: Vec<String> = Vec::new(); - for t in &list { - if !g.contains(&t.group) { - g.push(t.group.clone()); - } - } - g - }; - crate::windows::modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(700.0, 520.0), |ui| { - let tk = Tokens::get(ui.ctx()); + crate::windows::modal(context, "new-graph", tr("New graph"), &mut open, vec2(660.0, 330.0), |ui| { ui.horizontal(|ui| { ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Material, tr("Graph")); ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Function, tr("Function Graph")); }); - ui.add_space(6.0); + ui.add_space(10.0); ui.horizontal_top(|ui| { if app.ui.new_graph_kind == GraphKind::Material { ui.vertical(|ui| { - ui.set_width(430.0); + ui.set_width(320.0); + ui.label(RichText::new(tr("Templates")).strong()); ui.horizontal(|ui| { - ui.label(RichText::new(tr("Category")).strong()); - let shown = if app.ui.new_graph_category.is_empty() { tr("All").to_string() } else { tr(&app.ui.new_graph_category).to_string() }; - let r = egui::ComboBox::from_id_salt("new-category").selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(&mut app.ui.new_graph_category, String::new(), tr("All")); - for g in &groups { - ui.selectable_value(&mut app.ui.new_graph_category, g.clone(), tr(g)); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Category"); - }); - ui.add_space(4.0); - egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| { - for group in &groups { - if !app.ui.new_graph_category.is_empty() && app.ui.new_graph_category != *group { - continue; - } - ui.label(RichText::new(tr(group)).small().strong().color(tk.text_dim)); - let tiles: Vec<&Template> = list.iter().filter(|t| t.group == *group).collect(); - for row in tiles.chunks(4) { - ui.horizontal(|ui| { - for t in row { - tile(app, ui, t, &mut create); - } - }); - } - ui.add_space(6.0); + for (template, label) in TEMPLATES { + template_tile(app, ui, template, label); } }); + ui.add_space(8.0); + ui.label(tr(template_description(&app.ui.new_graph_template))); }); ui.separator(); } ui.vertical(|ui| { + ui.set_width(280.0); ui.label(RichText::new(tr("Graph name")).strong()); let name = ui.text_edit_singleline(&mut app.ui.new_graph_name); crate::widgets::name(&name, egui::Role::TextInput, "Graph name"); if app.ui.new_graph_kind == GraphKind::Material { - ui.add_space(8.0); - ui.label(RichText::new(tr("Size")).strong()); - sizes(app, ui); + ui.add_space(10.0); + dimensions(app, ui); } - ui.add_space(8.0); - ui.label(RichText::new(tr("Create graph in")).strong()); - let r = egui::ComboBox::from_id_salt("new-package").selected_text(&app.session.pkg.name).show_ui(ui, |ui| { - let _ = ui.selectable_label(true, &app.session.pkg.name); - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Create graph in"); - ui.label(RichText::new(tr("The open package (File > New > Empty package starts another)")).small().color(tk.text_dim)); - ui.add_space(20.0); + ui.add_space(12.0); + ui.label(format!("{}: {}", tr("Package"), app.session.pkg.name)); + ui.add_space(16.0); ui.horizontal(|ui| { - if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() { - create = true; - } + create = ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked(); if ui.button(tr("Cancel")).clicked() { app.ui.windows.new_graph = false; } @@ -138,123 +50,87 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { }); }); }); - if create && self::create(app) { - open = false; + + if create { + let mut parameters = json!({ + "kind": app.ui.new_graph_kind, + "template": app.ui.new_graph_template, + "name": app.ui.new_graph_name, + "size": app.ui.new_graph_size, + }); + if app.ui.new_graph_kind == GraphKind::Material { + let height = if app.ui.new_graph_link { app.ui.new_graph_size } else { app.ui.new_graph_height }; + parameters["height"] = json!(height); + } + if app.run("file.new", parameters).is_some() { + app.ui.frame_all = true; + open = false; + } } if !open { app.ui.windows.new_graph = false; } } -/// Width and height pickers with a link between them -fn sizes(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { - let sizes = [16u32, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192]; +fn dimensions(app: &mut MaterialCraftApp, ui: &mut Ui) { + if app.ui.new_graph_link { + app.ui.new_graph_height = app.ui.new_graph_size; + } ui.horizontal(|ui| { - let r = egui::ComboBox::from_id_salt("new-size").width(90.0).selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| { - for s in sizes { - ui.selectable_value(&mut app.ui.new_graph_size, s, format!("{s} px")); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Size"); - let link = app.ui.new_graph_link; - if crate::widgets::icon_button(ui, if link { icon::LINK } else { icon::LINK_BREAK }, tr("Link width and height"), link, 20.0).clicked() { - app.ui.new_graph_link = !link; - if !app.ui.new_graph_link && app.ui.new_graph_height == 0 { - app.ui.new_graph_height = app.ui.new_graph_size; - } + size_picker(ui, "Width", &mut app.ui.new_graph_size); + let linked = app.ui.new_graph_link; + if crate::widgets::icon_button(ui, if linked { icon::LINK } else { icon::LINK_BREAK }, tr("Link width and height"), linked, 22.0).clicked() { + app.ui.new_graph_link = !linked; } - let height = if app.ui.new_graph_link || app.ui.new_graph_height == 0 { app.ui.new_graph_size } else { app.ui.new_graph_height }; - ui.add_enabled_ui(!app.ui.new_graph_link, |ui| { - let r = egui::ComboBox::from_id_salt("new-height").width(90.0).selected_text(format!("{height} px")).show_ui(ui, |ui| { - for s in sizes { - ui.selectable_value(&mut app.ui.new_graph_height, s, format!("{s} px")); - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Height"); - }); + if app.ui.new_graph_link { + app.ui.new_graph_height = app.ui.new_graph_size; + } + ui.add_enabled_ui(!app.ui.new_graph_link, |ui| size_picker(ui, "Height", &mut app.ui.new_graph_height)); }); - ui.label(RichText::new(tr("width × height")).small().color(Tokens::get(ui.ctx()).text_dim)); } -fn tile(app: &mut MaterialCraftApp, ui: &mut egui::Ui, t: &Template, create: &mut bool) { - let tk = Tokens::get(ui.ctx()); - let on = app.ui.new_graph_template == t.id; - let (r, resp) = ui.allocate_exact_size(vec2(100.0, 124.0), egui::Sense::click()); - crate::widgets::name(&resp, egui::Role::ListItem, &t.label); - if on { - ui.painter().rect_filled(r, 6.0, tk.row_selected); - ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Inside); - } else if resp.hovered() { - ui.painter().rect_filled(r, 6.0, tk.row_hover); - } - let img = egui::Rect::from_min_size(r.min + vec2(10.0, 6.0), vec2(80.0, 80.0)); - let preview = if t.id.starts_with('+') { None } else { crate::windows::template_preview(ui.ctx(), &t.id) }; - match preview { - Some(tex) => { - ui.painter().image(tex, img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); - } - None => { - ui.painter().circle_filled(img.center(), 36.0, tk.row); - ui.painter().text( - img.center(), - egui::Align2::CENTER_CENTER, - if t.id.starts_with('+') { icon::PUZZLE_PIECE } else { icon::TREE_STRUCTURE }, - egui::FontId::proportional(28.0), - tk.text_dim, - ); - } - } - // ⓘ in the corner: what the template holds - let info = egui::Rect::from_center_size(img.right_top() + vec2(-8.0, 8.0), vec2(16.0, 16.0)); - let info_resp = ui.interact(info, resp.id.with("info"), egui::Sense::hover()); - ui.painter().text( - info.center(), - egui::Align2::CENTER_CENTER, - icon::INFO, - egui::FontId::proportional(13.0), - if info_resp.hovered() { tk.text_strong } else { tk.text_dim }, - ); - info_resp.on_hover_text(tr(&t.info)); - let g = ui.painter().layout(tr(&t.label).to_string(), egui::FontId::proportional(11.0), tk.text, 96.0); - ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text); - if resp.clicked() { - app.ui.new_graph_template = t.id.clone(); - app.ui.new_graph_name = t.label.replace(' ', "_"); - } - if resp.double_clicked() { - *create = true; +fn size_picker(ui: &mut Ui, label: &str, pixels: &mut u32) { + ui.vertical(|ui| { + ui.label(tr(label)); + let response = egui::ComboBox::from_id_salt(label).width(100.0).selected_text(format!("{pixels} px")).show_ui(ui, |ui| { + for size in [16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192] { + ui.selectable_value(pixels, size, format!("{size} px")); + } + }); + crate::widgets::name(&response.response, egui::Role::ComboBox, label); + }); +} + +fn template_description(template: &str) -> &'static str { + match template { + "empty" => "Start with an empty graph and add nodes from the library.", + "pbr" => "Uniform inputs connected to six material outputs: base color, normal, roughness, metallic, height and ambient occlusion.", + "atomics" => "An original sample combining a value input, function, pixel processor, pattern graph and blur.", + _ => "Choose a graph template.", } } -/// Make the graph; true when it was created -fn create(app: &mut MaterialCraftApp) -> bool { - use materialcraft_engine::core::GraphKind; - let template = app.ui.new_graph_template.clone(); - if app.ui.new_graph_kind == GraphKind::Material - && let Some(plugin) = template.strip_prefix('+') - && let Some((package, graph)) = plugin.split_once('\n') - { - let Some(r) = app.run("file.importGraph", json!({"path": package, "graph": graph})) else { return false }; - let name = r["name"].as_str().unwrap_or(graph).to_string(); - let wanted = app.ui.new_graph_name.trim().to_string(); - if !wanted.is_empty() && wanted != name { - app.run("graph.rename", json!({"graph": name, "name": wanted})); - } - app.ui.frame_all = true; - return true; +fn template_tile(app: &mut MaterialCraftApp, ui: &mut Ui, template: &str, label: &str) { + let tokens = Tokens::get(ui.ctx()); + let selected = app.ui.new_graph_template == template; + let (rectangle, response) = ui.allocate_exact_size(vec2(100.0, 124.0), egui::Sense::click()); + crate::widgets::name(&response, egui::Role::ListItem, label); + if selected || response.hovered() { + ui.painter().rect_filled(rectangle, 6.0, if selected { tokens.row_selected } else { tokens.row_hover }); } - let template = if materialcraft_engine::samples::TEMPLATES.iter().any(|(id, _)| *id == template) { template } else { "empty".to_string() }; - let parameters = json!({"kind": app.ui.new_graph_kind, "template": template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size}); - if app.run("file.new", parameters).is_none() { - return false; + if selected { + ui.painter().rect_stroke(rectangle, 6.0, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Inside); } - if app.ui.new_graph_kind == GraphKind::Material - && !app.ui.new_graph_link - && app.ui.new_graph_height != 0 - && app.ui.new_graph_height != app.ui.new_graph_size - { - app.run("graph.size", json!({"width": app.ui.new_graph_size, "height": app.ui.new_graph_height})); + let image = egui::Rect::from_min_size(rectangle.min + vec2(10.0, 6.0), vec2(80.0, 80.0)); + if let Some(texture) = crate::windows::template_preview(app, ui.ctx(), template) { + ui.painter().image(texture, image, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); + } else { + ui.painter().circle_filled(image.center(), 36.0, tokens.row); + ui.painter().text(image.center(), egui::Align2::CENTER_CENTER, icon::TREE_STRUCTURE, egui::FontId::proportional(28.0), tokens.text_dim); + } + let caption = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tokens.text, 96.0); + ui.painter().galley(egui::pos2(rectangle.center().x - caption.size().x * 0.5, image.bottom() + 6.0), caption, tokens.text); + if response.clicked() { + app.ui.new_graph_template = template.into(); } - app.ui.frame_all = true; - true } diff --git a/crates/ui-egui/src/pattern/canvas.rs b/crates/ui-egui/src/pattern/canvas.rs index 5b162fb..296eb3a 100644 --- a/crates/ui-egui/src/pattern/canvas.rs +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -69,7 +69,7 @@ fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Opt } let mut camera = GraphCamera { origin: bounds.min, pan: editor.pan, zoom: editor.zoom }; - camera.zoom_from_input(ui, bounds, app.ui.prefs.invert_zoom); + camera.zoom_from_input(ui, bounds); editor.pan = camera.pan; editor.zoom = camera.zoom; crate::graph::grid::paint(&painter, &camera, bounds); diff --git a/crates/ui-egui/src/plugins.rs b/crates/ui-egui/src/plugins.rs deleted file mode 100644 index 2ded2c9..0000000 --- a/crates/ui-egui/src/plugins.rs +++ /dev/null @@ -1,342 +0,0 @@ -//! Plugins (Tools ▸ Plugin Manager): packages dropped in the plugins folder whose graphs the -//! library offers (filed under each graph's category attribute). A plugin is a package file (`.sbs`) in `Documents/MaterialCraft/plugins`, -//! or a folder there holding package files and an optional `plugin.json` -//! (`{"name", "version", "author", "description"}`). Loaded plugins are remembered per user. - -use std::path::{Path, PathBuf}; - -use egui::{RichText, vec2}; -use egui_phosphor::regular as icon; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// One plugin: a package file or a folder of them. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Plugin { - /// The plugin's key in the loaded list: its file or folder path. - pub path: String, - pub name: String, - pub version: String, - pub author: String, - pub description: String, - /// The package files and the graphs each one holds: (path, [(graph name, category attribute)]). - pub packages: Vec<(String, Vec<(String, String)>)>, - /// Why a package could not be read, if any. - pub error: Option<String>, -} - -impl Plugin { - /// Every graph of the plugin: (package path, graph name, category attribute). - pub fn graphs(&self) -> impl Iterator<Item = (&str, &str, &str)> { - self.packages.iter().flat_map(|(p, gs)| gs.iter().map(move |(g, c)| (p.as_str(), g.as_str(), c.as_str()))) - } -} - -/// The plugins found in the plugins folder (scanned on first use and on Refresh). -#[derive(Default)] -pub struct Plugins { - pub list: Vec<Plugin>, - scanned: bool, - pub filter: String, -} - -/// The plugins folder. -pub fn folder() -> PathBuf { - #[cfg(not(target_arch = "wasm32"))] - { - crate::user_dir("plugins") - } - #[cfg(target_arch = "wasm32")] - { - PathBuf::from("plugins") - } -} - -fn is_package(path: &Path) -> bool { - path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("sbs")) -} - -/// The graphs of a package file, read without opening it: (name, category attribute). -#[cfg(not(target_arch = "wasm32"))] -fn graphs_of(path: &Path) -> Result<Vec<(String, String)>, String> { - const MAX_PLUGIN_BYTES: u64 = 256 * 1024 * 1024; - let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len(); - if len > MAX_PLUGIN_BYTES { - return Err(format!("{} is larger than {} MB", path.display(), MAX_PLUGIN_BYTES / (1024 * 1024))); - } - let bytes = std::fs::read(path).map_err(|e| e.to_string())?; - let name = path.display().to_string(); - let linked = materialcraft_engine::file_cmds::linked_files(&name); - let pkg = crate::cook::guard("plugin", || materialcraft_engine::resource_cmds::load_bytes(&bytes, &name, &linked).map_err(|e| e.to_string()))?; - Ok(pkg.graphs.iter().map(|g| (g.name.clone(), g.attributes.category.clone())).collect()) -} - -#[cfg(target_arch = "wasm32")] -fn graphs_of(_: &Path) -> Result<Vec<(String, String)>, String> { - Err("the browser has no plugins folder".into()) -} - -/// `plugin.json` next to a folder plugin's packages. -#[derive(Default, serde::Deserialize)] -#[serde(default)] -struct Manifest { - name: String, - version: String, - author: String, - description: String, -} - -fn read_plugin(path: &Path) -> Plugin { - let key = path.display().to_string(); - let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("plugin").to_string(); - let mut plugin = Plugin { path: key, name: stem, ..Plugin::default() }; - let mut files: Vec<PathBuf> = Vec::new(); - if path.is_dir() { - if let Ok(text) = std::fs::read_to_string(path.join("plugin.json")) - && let Ok(m) = serde_json::from_str::<Manifest>(&text) - { - if !m.name.trim().is_empty() { - plugin.name = m.name.trim().chars().take(80).collect(); - } - plugin.version = m.version.chars().take(32).collect(); - plugin.author = m.author.chars().take(80).collect(); - plugin.description = m.description.chars().take(400).collect(); - } - if let Ok(rd) = std::fs::read_dir(path) { - files.extend(rd.flatten().map(|e| e.path()).filter(|p| p.is_file() && is_package(p))); - } - files.sort(); - } else { - files.push(path.to_path_buf()); - } - for f in files { - match graphs_of(&f) { - Ok(graphs) => plugin.packages.push((f.display().to_string(), graphs)), - Err(e) => plugin.error = Some(e), - } - } - if plugin.packages.is_empty() && plugin.error.is_none() { - plugin.error = Some(tr("No package files (.sbs) in this plugin").to_string()); - } - plugin -} - -impl Plugins { - /// Read the plugins folder again. - pub fn refresh(&mut self) { - self.scanned = true; - self.list.clear(); - let Ok(rd) = std::fs::read_dir(folder()) else { return }; - let mut paths: Vec<PathBuf> = rd.flatten().map(|e| e.path()).filter(|p| p.is_dir() || is_package(p)).collect(); - paths.sort(); - self.list = paths.iter().take(500).map(|p| read_plugin(p)).collect(); - } - - /// Scan once, on first use. - pub fn ensure(&mut self) { - if !self.scanned { - self.refresh(); - } - } -} - -impl MaterialCraftApp { - /// Is the plugin at `path` loaded (its graphs in the library)? - pub fn plugin_loaded(&self, path: &str) -> bool { - self.ui.plugins_loaded.iter().any(|p| p == path) - } - - /// The graphs of every loaded plugin: (plugin name, package path, graph name, category). - pub fn plugin_graphs(&mut self) -> Vec<(String, String, String, String)> { - self.plugins.ensure(); - let loaded = &self.ui.plugins_loaded; - self.plugins - .list - .iter() - .filter(|p| loaded.contains(&p.path)) - .flat_map(|p| p.graphs().map(|(pkg, g, c)| (p.name.clone(), pkg.to_string(), g.to_string(), c.to_string())).collect::<Vec<_>>()) - .collect() - } - - /// Put a plugin graph into the open package and add an instance of it (library drop/double-click). - pub fn add_plugin_graph(&mut self, package: &str, graph: &str, at: Option<[f32; 2]>) { - let Some(v) = self.run("file.importGraph", serde_json::json!({"path": package, "graph": graph})) else { return }; - let name = v.get("name").and_then(|n| n.as_str()).unwrap_or(graph).to_string(); - let mut p = serde_json::json!({"def": "graph_instance", "params": {"graph": name}}); - if let Some(at) = at { - p["at"] = serde_json::json!(at); - } - self.run("graph.node.add", p); - } -} - -/// Copy the picked package files (or a folder) into the plugins folder. -#[cfg(not(target_arch = "wasm32"))] -fn install(app: &mut MaterialCraftApp) { - let Some(files) = rfd::FileDialog::new().add_filter("Packages", &["sbs"]).pick_files() else { return }; - let dir = folder(); - if let Err(e) = std::fs::create_dir_all(&dir) { - app.toast(format!("{}: {e}", tr("Could not create the plugins folder")), true); - return; - } - let mut n = 0; - for f in files { - let Some(name) = f.file_name() else { continue }; - match std::fs::copy(&f, dir.join(name)) { - Ok(_) => n += 1, - Err(e) => app.toast(format!("{}: {e}", f.display()), true), - } - } - app.plugins.refresh(); - app.toast(format!("{n} {}", tr("plugin file(s) installed")), false); -} - -/// Open the plugins folder in the system's file browser. -#[cfg(not(target_arch = "wasm32"))] -fn browse(app: &mut MaterialCraftApp) { - let dir = folder(); - if let Err(e) = std::fs::create_dir_all(&dir) { - app.toast(format!("{}: {e}", tr("Could not create the plugins folder")), true); - return; - } - let program = if cfg!(target_os = "windows") { - "explorer" - } else if cfg!(target_os = "macos") { - "open" - } else { - "xdg-open" - }; - match std::process::Command::new(program).arg(&dir).spawn() { - Ok(_) => app.toast(format!("{} {}", tr("Plugins folder:"), dir.display()), false), - Err(e) => app.toast(format!("{} {} ({e})", tr("Plugins folder:"), dir.display()), true), - } -} - -/// Tools ▸ Plugin Manager. -pub fn window(app: &mut MaterialCraftApp, ctx: &egui::Context) { - if !app.ui.windows.plugin_manager { - return; - } - app.plugins.ensure(); - let mut open = true; - let mut toggle: Option<(String, bool)> = None; - let mut action: Option<&'static str> = None; - crate::windows::modal(ctx, "plugin-manager", tr("Plugin Manager"), &mut open, vec2(640.0, 400.0), |ui| { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim)); - ui.add(egui::TextEdit::singleline(&mut app.plugins.filter).hint_text(tr("Filter")).desired_width(220.0)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Refresh")).clicked() { - action = Some("refresh"); - } - if ui.button(tr("Install...")).clicked() { - action = Some("install"); - } - if ui.button(tr("Browse...")).on_hover_text(tr("Open the plugins folder")).clicked() { - action = Some("browse"); - } - }); - }); - ui.add_space(4.0); - let filter = app.plugins.filter.to_ascii_lowercase(); - let shown: Vec<Plugin> = app - .plugins - .list - .iter() - .filter(|p| filter.is_empty() || p.name.to_ascii_lowercase().contains(&filter) || p.path.to_ascii_lowercase().contains(&filter)) - .cloned() - .collect(); - egui::ScrollArea::vertical().max_height(270.0).auto_shrink([false, false]).show(ui, |ui| { - egui::Grid::new("plugins-grid").num_columns(5).striped(true).spacing([12.0, 4.0]).show(ui, |ui| { - ui.label(RichText::new(tr("Loaded")).strong()); - ui.label(RichText::new(tr("Plugin")).strong()); - ui.label(RichText::new(tr("Version")).strong()); - ui.label(RichText::new(tr("Graphs")).strong()); - ui.label(RichText::new(tr("Location")).strong()); - ui.end_row(); - for p in &shown { - let mut on = app.plugin_loaded(&p.path); - let usable = p.error.is_none(); - if ui.add_enabled(usable, egui::Checkbox::without_text(&mut on)).changed() { - toggle = Some((p.path.clone(), on)); - } - let name = ui.label(&p.name); - if !p.description.is_empty() || !p.author.is_empty() { - name.on_hover_text(format!("{}\n{}", p.description, p.author)); - } - ui.label(if p.version.is_empty() { "—".to_string() } else { p.version.clone() }); - match &p.error { - Some(e) => { - ui.label(RichText::new(format!("{} {}", icon::WARNING, tr("unreadable"))).color(tk.danger)).on_hover_text(e); - } - None => { - let n = p.graphs().count(); - ui.label(n.to_string()).on_hover_text(p.graphs().map(|(_, g, _)| g).collect::<Vec<_>>().join("\n")); - } - } - ui.label(RichText::new(&p.path).color(tk.text_dim).small()); - ui.end_row(); - } - }); - if shown.is_empty() { - ui.add_space(8.0); - ui.label(RichText::new(format!("{} {}", tr("No plugins. Drop package files into"), folder().display())).color(tk.text_dim)); - } - }); - ui.add_space(6.0); - ui.label( - RichText::new(tr("Loaded plugins add their graphs to the library (Plugins category); adding one copies the graph into your package.")) - .small() - .color(tk.text_dim), - ); - }); - if let Some((path, on)) = toggle { - app.ui.plugins_loaded.retain(|p| *p != path); - if on { - app.ui.plugins_loaded.push(path); - } - } - match action { - Some("refresh") => app.plugins.refresh(), - #[cfg(not(target_arch = "wasm32"))] - Some("install") => install(app), - #[cfg(not(target_arch = "wasm32"))] - Some("browse") => browse(app), - _ => {} - } - if !open { - app.ui.windows.plugin_manager = false; - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_folder_without_packages_reports_an_error_not_a_panic() { - let dir = std::env::temp_dir().join(format!("mc-plugin-test-{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let _ = std::fs::write(dir.join("plugin.json"), "{\"name\": \"Test\", \"version\": \"1.0\"}"); - let p = read_plugin(&dir); - assert_eq!(p.name, "Test"); - assert_eq!(p.version, "1.0"); - assert!(p.error.is_some()); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn a_garbage_manifest_keeps_the_folder_name() { - let dir = std::env::temp_dir().join(format!("mc-plugin-garbage-{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let _ = std::fs::write(dir.join("plugin.json"), "{not json"); - let _ = std::fs::write(dir.join("broken.sbs"), "<xml"); - let p = read_plugin(&dir); - assert_eq!(Some(p.name.as_str()), dir.file_name().and_then(|s| s.to_str())); - assert!(p.error.is_some(), "a broken package is reported"); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/ui-egui/src/preferences.rs b/crates/ui-egui/src/preferences.rs index f80c10c..7809bf4 100644 --- a/crates/ui-egui/src/preferences.rs +++ b/crates/ui-egui/src/preferences.rs @@ -1,522 +1,79 @@ -//! Edit ▸ Preferences: a tabbed window (General, Projects, Graph, 3D View, Bakers, Library, -//! Shortcuts) edited on a copy of the preferences; OK and Apply push the copy into the app. +mod preference_tab; +pub use preference_tab::PreferenceTab; -use egui::{RichText, Ui, vec2}; -use egui_phosphor::regular as icon; +use egui::{Ui, vec2}; -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::state::Prefs; -use crate::theme::{Accent, Brightness, Tokens}; +use crate::{ + MaterialCraftApp, + i18n::tr, + state::Prefs, + theme::{Accent, Brightness}, +}; -/// The tabs, in order. -const TABS: [&str; 7] = ["General", "Projects", "Graph", "3D View", "Bakers", "Library", "Shortcuts"]; - -/// The window's working copy and tab (kept while it is open). -#[derive(Default)] -pub struct PrefsEditor { - draft: Option<Prefs>, - /// The preferences when the window opened (Cancel restores the live-previewed ones). - original: Option<Prefs>, - tab: usize, - shortcut_search: String, - shortcut_key_search: String, - /// Node shortcuts being edited: def id → shortcut text. - node_shortcuts: Vec<(String, String)>, - /// The shortcut field waiting for a key press. - capturing: Option<String>, -} - -fn heading(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.add_space(8.0); - ui.label(RichText::new(text.to_uppercase()).size(12.5).color(tk.text_strong)); - ui.add_space(2.0); -} - -fn sub_heading(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.add_space(4.0); - ui.label(RichText::new(text.to_uppercase()).size(11.0).color(tk.text_dim)); -} - -/// A numeric field with a unit: "[ 10 ] Files". -fn number(ui: &mut Ui, label: &str, value: &mut u32, range: std::ops::RangeInclusive<u32>, unit: &str) -> bool { - let mut changed = false; - ui.horizontal(|ui| { - ui.label(label); - let r = ui.add(egui::DragValue::new(value).range(range).speed(1.0)); - crate::widgets::name(&r, egui::Role::SpinButton, label); - changed = r.changed(); - ui.label(unit); - }); - changed -} - -/// A folder field with reset, browse and "use" buttons. -fn folder_field(ui: &mut Ui, label: &str, value: &mut String, default_hint: &str) { - ui.label(label); - ui.horizontal(|ui| { - let r = ui.add(egui::TextEdit::singleline(value).hint_text(default_hint).desired_width(ui.available_width() - 60.0)); - crate::widgets::name(&r, egui::Role::TextInput, label); - if crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset to the default"), false, 20.0).clicked() { - value.clear(); - } - #[cfg(not(target_arch = "wasm32"))] - if crate::widgets::icon_button(ui, icon::DOTS_THREE, tr("Browse..."), false, 20.0).clicked() - && let Some(p) = rfd::FileDialog::new().pick_folder() - { - *value = p.display().to_string(); - } - }); -} - -pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { - if app.prefs_editor.draft.is_none() { - app.prefs_editor.draft = Some(app.ui.prefs.clone()); - app.prefs_editor.original = Some(app.ui.prefs.clone()); - app.prefs_editor.node_shortcuts = app.ui.node_shortcuts.clone(); - } +pub(crate) fn show(app: &mut MaterialCraftApp, context: &egui::Context) { let mut open = true; - let mut action: Option<&str> = None; - egui::Window::new(tr("Preferences")) - .id(egui::Id::unique("preferences")) - .open(&mut open) - .collapsible(false) - .resizable(true) - .default_size(vec2(760.0, 560.0)) - .show(ctx, |ui| { - let tk = Tokens::get(ui.ctx()); - let total = ui.available_height() - 36.0; - ui.horizontal_top(|ui| { - // Tabs down the left. - ui.allocate_ui_with_layout(vec2(150.0, total), egui::Layout::top_down(egui::Align::Min), |ui| { - ui.painter().rect_filled(ui.max_rect(), 0.0, tk.panel); - ui.add_space(6.0); - for (i, tab) in TABS.iter().enumerate() { - let on = app.prefs_editor.tab == i; - let (r, resp) = ui.allocate_exact_size(vec2(146.0, 32.0), egui::Sense::click()); - crate::widgets::name(&resp, egui::Role::Tab, tab); - if on { - ui.painter().rect_filled(r, 3.0, tk.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(r, 3.0, tk.row_hover); - } - ui.painter().text( - r.left_center() + vec2(10.0, 0.0), - egui::Align2::LEFT_CENTER, - tr(tab).to_uppercase(), - egui::FontId::proportional(13.0), - if on { tk.text_strong } else { tk.text }, - ); - if resp.clicked() { - app.prefs_editor.tab = i; - } - } - }); - ui.separator(); - ui.allocate_ui_with_layout(vec2(ui.available_width(), total), egui::Layout::top_down(egui::Align::Min), |ui| { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.set_width(ui.available_width() - 8.0); - let tab = app.prefs_editor.tab; - match tab { - 0 => general(app, ui), - 1 => projects(app, ui), - 2 => graph(app, ui), - 3 => view3d(app, ui), - 4 => bakers(app, ui), - 5 => library(app, ui), - _ => shortcuts(app, ui), - } - }); - }); + crate::windows::modal(context, "prefs", tr("Preferences"), &mut open, vec2(560.0, 360.0), |ui| { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(110.0); + for tab in PreferenceTab::ALL { + let response = ui.selectable_value(&mut app.ui.preferences_tab, tab, tr(tab.label())); + crate::widgets::name(&response, egui::Role::Tab, tab.label()); + } }); ui.separator(); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(egui::Button::new(tr("APPLY")).min_size(vec2(90.0, 24.0))).clicked() { - action = Some("apply"); - } - if ui.add(egui::Button::new(tr("CANCEL")).min_size(vec2(90.0, 24.0))).clicked() { - action = Some("cancel"); - } - if ui.add(crate::widgets::primary_button(ui, tr("OK")).min_size(vec2(90.0, 24.0))).clicked() { - action = Some("ok"); + ui.vertical(|ui| { + ui.set_width(410.0); + match app.ui.preferences_tab { + PreferenceTab::General => general(&mut app.ui.prefs, ui), + PreferenceTab::Graph => graph(&mut app.ui.prefs, ui), + PreferenceTab::View3d => view3d(&mut app.ui.prefs, ui), } }); }); - // Appearance previews live while the window is open (Cancel puts it back). - if let Some(d) = &app.prefs_editor.draft { - app.ui.prefs.ui_scale = d.ui_scale; - app.ui.prefs.brightness = d.brightness; - app.ui.prefs.accent = d.accent; - } - match action { - Some("apply") => apply(app), - Some("ok") => { - apply(app); - open = false; - } - Some("cancel") => { - if let Some(o) = app.prefs_editor.original.take() { - app.ui.prefs.ui_scale = o.ui_scale; - app.ui.prefs.brightness = o.brightness; - app.ui.prefs.accent = o.accent; - } - open = false; - } - _ => {} - } + }); if !open { app.ui.windows.preferences = false; - app.prefs_editor.draft = None; - app.prefs_editor.original = None; - app.prefs_editor.capturing = None; } } -/// Push the draft into the live preferences. -fn apply(app: &mut MaterialCraftApp) { - let Some(draft) = app.prefs_editor.draft.clone() else { return }; - app.ui.prefs = draft; - app.ui.node_shortcuts = app.prefs_editor.node_shortcuts.clone(); - crate::i18n::set_language(&app.ui.prefs.language); - app.apply_prefs(); - app.toast(tr("Preferences applied"), false); -} - -fn draft(app: &mut MaterialCraftApp) -> &mut Prefs { - app.prefs_editor.draft.get_or_insert_with(Prefs::default) -} - -fn general(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let cache_used = app.session.cache.lock().map(|c| c.bytes() >> 20).unwrap_or(0); - let cache_cap = app.session.cache.lock().map(|c| c.cap() >> 20).unwrap_or(0); - let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); - let p = draft(app); - heading(ui, tr("Recent documents")); - number(ui, tr("Recent documents list contains:"), &mut p.recent_count, 1..=50, tr("Files")); - heading(ui, tr("History")); - number(ui, tr("History stack size:"), &mut p.history_size, 1..=10_000, tr("States")); - heading(ui, tr("Language")); - ui.label(tr("Choose the language of the application:")); - crate::widgets::combo(ui, "", crate::i18n::LANGUAGES.iter().find(|l| l.code == p.language).map_or("English", |l| l.name), |ui| { - for l in crate::i18n::LANGUAGES.iter().filter(|l| l.code == "en") { - if ui.selectable_label(p.language == l.code, l.name).clicked() { - p.language = l.code.to_owned(); +fn general(preferences: &mut Prefs, ui: &mut Ui) { + let current_language = crate::i18n::current(); + crate::widgets::combo(ui, tr("Language"), current_language.name, |ui| { + for language in &crate::i18n::LANGUAGES { + if ui.selectable_label(preferences.language == language.code, language.name).clicked() { + preferences.language = language.code.to_owned(); + crate::i18n::set_language(&preferences.language); } } }); - ui.label(RichText::new(tr("More languages arrive in a later version.")).small().color(tk.text_dim)); - heading(ui, tr("Appearance")); - crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| { - for b in Brightness::ALL { - ui.selectable_value(&mut p.brightness, b, tr(b.label())); + crate::widgets::combo(ui, tr("Brightness"), tr(preferences.brightness.label()), |ui| { + for brightness in Brightness::ALL { + ui.selectable_value(&mut preferences.brightness, brightness, tr(brightness.label())); } }); - crate::widgets::combo(ui, tr("Accent color"), tr(p.accent.label()), |ui| { - for a in Accent::ALL { - ui.selectable_value(&mut p.accent, a, tr(a.label())); + crate::widgets::combo(ui, tr("Accent color"), tr(preferences.accent.label()), |ui| { + for accent in Accent::ALL { + ui.selectable_value(&mut preferences.accent, accent, tr(accent.label())); } }); - crate::widgets::slider(ui, tr("Interface scale"), &mut p.ui_scale, 0.75..=2.0, 2); - ui.checkbox(&mut p.show_home, tr("Show the home screen at start")); - heading(ui, tr("Views")); - ui.checkbox(&mut p.invert_zoom, tr("Invert zoom in views")); - heading(ui, tr("Paths")); - ui.label(tr("Save/Export Path:")); - let modes = [("last", "Last path"), ("package", "The package's folder"), ("custom", "A fixed folder")]; - let cur = modes.iter().find(|(id, _)| *id == p.save_path_mode).map_or("Last path", |(_, l)| l); - crate::widgets::combo(ui, "", tr(cur), |ui| { - for (id, label) in modes { - if ui.selectable_label(p.save_path_mode == id, tr(label)).clicked() { - p.save_path_mode = id.into(); - } - } - }); - if p.save_path_mode == "custom" { - folder_field(ui, tr("Fixed folder:"), &mut p.save_path, ""); + crate::widgets::slider(ui, tr("Interface scale"), &mut preferences.ui_scale, 0.75..=2.0, 2); + let mut autosave_minutes = preferences.autosave_minutes as f32; + if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut autosave_minutes, 0.0..=60.0, 0).changed() { + preferences.autosave_minutes = autosave_minutes.round() as u32; } - folder_field(ui, tr("Temporary folder (auto backups):"), &mut p.temp_dir, &crate::user_dir("autosave").display().to_string()); - heading(ui, tr("Memory")); - sub_heading(ui, tr("Image cache")); - ui.label(format!("{}: {cache_used} MB {} {cache_cap} MB", tr("Current memory used"), tr("of"))); - ui.label(tr("Memory Budget:")); - ui.horizontal(|ui| { - let auto = p.cache_mb == 0; - let r = egui::ComboBox::from_id_salt("cache-mode").selected_text(if auto { tr("Automatic") } else { tr("Fixed") }).show_ui(ui, |ui| { - if ui.selectable_label(auto, tr("Automatic")).clicked() { - p.cache_mb = 0; - } - if ui.selectable_label(!auto, tr("Fixed")).clicked() && auto { - p.cache_mb = 1024; - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Memory budget"); - if !auto { - let r = ui.add(egui::DragValue::new(&mut p.cache_mb).range(16..=65_536).speed(16.0).suffix(" MB")); - crate::widgets::name(&r, egui::Role::SpinButton, "Cache MB"); - } else { - ui.label(RichText::new("1024 MB").color(tk.text_dim)); - } - }); - sub_heading(ui, tr("Job scheduler")); - ui.label(format!("{}: {cores}", tr("Cores on this machine"))); - let mut threads = p.cook_threads as u32; - if number(ui, tr("Cook threads (0 = every core):"), &mut threads, 0..=256, tr("threads")) { - p.cook_threads = threads as usize; - } - heading(ui, tr("Auto backup")); - let mut backup_on = p.autosave_minutes > 0; - if ui.checkbox(&mut backup_on, tr("Auto backup")).changed() { - p.autosave_minutes = if backup_on { 5 } else { 0 }; - } - ui.add_enabled_ui(backup_on, |ui| { - let mut m = p.autosave_minutes.max(1); - if number(ui, tr("Auto backup every:"), &mut m, 1..=120, tr("minutes")) { - p.autosave_minutes = m; - } - number(ui, tr("Keep up to:"), &mut p.backup_versions, 1..=50, tr("versions")); - }); - ui.label( - RichText::new(tr("Backups are written to the temporary folder above; open one with File > Open and save it over the original.")) - .small() - .color(tk.text_dim), - ); - heading(ui, tr("Cooker")); - ui.horizontal(|ui| { - ui.label(tr("Cooking size limit:")); - let mut v = (31 - p.cook_limit.clamp(256, 8192).leading_zeros()) as f32; - if ui.add(egui::Slider::new(&mut v, 8.0..=13.0).show_value(false).step_by(1.0)).changed() { - p.cook_limit = 1 << (v as u32); - } - ui.label(format!("{} {}", p.cook_limit, tr("pixels"))); - }); - ui.label( - RichText::new(tr("Caps every cook, exports included. Preview size while editing is set in the 3D view's Display menu.")).small().color(tk.text_dim), - ); + ui.checkbox(&mut preferences.show_home, tr("Show at startup")); } -fn projects(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - heading(ui, tr("Configuration")); - ui.horizontal(|ui| { - ui.label(tr("Preferences file:")); - ui.label(RichText::new(tr("kept by the app in its settings store")).color(tk.text_dim)); +fn graph(preferences: &mut Prefs, ui: &mut Ui) { + crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(preferences.preview_size), |ui| { + crate::preview_resolution::choices(ui, &mut preferences.preview_size); }); - ui.horizontal(|ui| { - ui.label(tr("Plugins folder:")); - ui.label(RichText::new(crate::plugins::folder().display().to_string()).color(tk.text_dim)); - if ui.small_button(tr("Plugin Manager...")).clicked() { - app.ui.windows.plugin_manager = true; - } - }); - ui.horizontal(|ui| { - ui.label(tr("Backups folder:")); - let dir = if app.ui.prefs.temp_dir.is_empty() { crate::user_dir("autosave").display().to_string() } else { app.ui.prefs.temp_dir.clone() }; - ui.label(RichText::new(dir).color(tk.text_dim)); - }); - heading(ui, tr("Project")); - sub_heading(ui, tr("3D View")); - ui.horizontal(|ui| { - ui.label(tr("Default State File:")); - let has = app.ui.view3d_default.is_some(); - ui.label(RichText::new(if has { tr("saved (Scene > Save Current State As Default)") } else { tr("none: the built-in state") }).color(tk.text_dim)); - if has && ui.small_button(tr("Clear")).clicked() { - app.ui.view3d_default = None; - } - if ui.small_button(tr("Save the current 3D view as the default")).clicked() { - app.ui.view3d_default = app.run("view.3d.state", serde_json::json!({})); - } - }); - let p = draft(app); - ui.label(tr("Default Lighting State (if not set by Default State File):")); - ui.indent("lights", |ui| { - ui.checkbox(&mut p.default_lights[0], tr("Ambient Light")); - ui.checkbox(&mut p.default_lights[1], tr("Point Light 1")); - ui.checkbox(&mut p.default_lights[2], tr("Point Light 2")); - }); - sub_heading(ui, tr("Library")); - ui.checkbox(&mut p.library_list, tr("Show the library as a list")); - crate::widgets::slider(ui, tr("Library tile size"), &mut p.library_tile, 56.0..=160.0, 0); - sub_heading(ui, tr("General")); - crate::widgets::combo( - ui, - tr("Preview size while editing"), - if p.preview_size == 0 { tr("Full size").to_string() } else { format!("{} px", p.preview_size) }, - |ui| { - for s in [256u32, 512, 1024, 2048, 4096, 0] { - let label = if s == 0 { tr("Full size").to_string() } else { format!("{s} px") }; - ui.selectable_value(&mut p.preview_size, s, label); - } - }, - ); - crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut p.camera.pan_limit, 0.0..=20.0, 1); - crate::widgets::slider(ui, tr("3D pan speed"), &mut p.camera.pan_speed, 0.1..=4.0, 2); + ui.checkbox(&mut preferences.thumbnails, tr("Show node thumbnails")); + ui.checkbox(&mut preferences.snap_to_grid, tr("Snap to grid")); } -fn graph(app: &mut MaterialCraftApp, ui: &mut Ui) { - let p = draft(app); - heading(ui, tr("Common")); - ui.checkbox(&mut p.tab_key_menu, tr("Tab key shows node menu")); - ui.checkbox(&mut p.drag_create, tr("Enable creation of nodes by click-dragging connectors")); - ui.checkbox(&mut p.view_3d_on_open, tr("View outputs in 3D view when opening a graph")); - heading(ui, tr("Material graph")); - ui.checkbox(&mut p.thumbnails, tr("Automatically compute all nodes thumbnails when opening a graph")); - ui.checkbox(&mut p.view_2d_on_open, tr("View output in 2D view when opening a graph")); - ui.checkbox(&mut p.auto_display_new_node, tr("Automatically display newly created node")); - ui.checkbox(&mut p.auto_convert, tr("Automatically insert color/grayscale conversion node")); - heading(ui, tr("Graph toolbar")); - ui.checkbox(&mut p.show_grid, tr("Show the grid")); - ui.checkbox(&mut p.snap_to_grid, tr("Snap nodes to the grid")); - ui.checkbox(&mut p.straight_wires, tr("Straight wires")); - ui.checkbox(&mut p.node_timings, tr("Show cook times on nodes")); -} - -fn view3d(app: &mut MaterialCraftApp, ui: &mut Ui) { - let p = draft(app); - heading(ui, tr("Misc")); - ui.checkbox(&mut p.env_hidden, tr("Environment hidden by default")); - crate::widgets::combo( - ui, - tr("Viewport Scaling"), - if p.viewport_scale <= 0.0 { tr("Auto").to_string() } else { format!("{:.0} %", p.viewport_scale * 100.0) }, - |ui| { - if ui.selectable_label(p.viewport_scale <= 0.0, tr("Auto")).clicked() { - p.viewport_scale = 0.0; - } - for s in [0.5f32, 0.75, 1.0, 1.5, 2.0] { - if ui.selectable_label((p.viewport_scale - s).abs() < 1e-3, format!("{:.0} %", s * 100.0)).clicked() { - p.viewport_scale = s; - } - } - }, - ); - heading(ui, tr("Renderer")); - sub_heading(ui, tr("Shading")); - let labels = [(1u32, "Low (1 spp)"), (2, "Medium (4 spp)"), (3, "High (9 spp)"), (4, "Very high (16 spp)")]; - let cur = labels.iter().find(|(n, _)| *n == p.sample_count).map_or("Medium (4 spp)", |(_, l)| l); - crate::widgets::combo(ui, tr("Sample Count"), tr(cur), |ui| { - for (n, label) in labels { - if ui.selectable_label(p.sample_count == n, tr(label)).clicked() { - p.sample_count = n; - } - } - }); - ui.label( - RichText::new(tr("Samples per pixel of the resting frame; the renderer settings of a session can override it.")) - .small() - .color(Tokens::get(ui.ctx()).text_dim), - ); -} - -fn bakers(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let p = draft(app); - heading(ui, tr("Bakers")); - let mut threads = p.bake_threads; - if number(ui, tr("Baking threads (0 = every core):"), &mut threads, 0..=256, tr("threads")) { - p.bake_threads = threads; - } - ui.label(RichText::new(tr("Mesh maps bake on the CPU ray tracer; GPU ray tracing arrives with the GPU renderer.")).small().color(tk.text_dim)); -} - -fn library(app: &mut MaterialCraftApp, ui: &mut Ui) { - heading(ui, tr("Library")); - if ui.add(egui::Button::new(tr("Rebuild Thumbnails")).min_size(vec2(260.0, 24.0))).clicked() { - app.thumbs.rebuild_library(); - app.toast(tr("Library thumbnails are being rebuilt"), false); - } - ui.add_space(6.0); - if ui.add(egui::Button::new(tr("Clear the cooked image cache")).min_size(vec2(260.0, 24.0))).clicked() { - if let Ok(mut c) = app.session.cache.lock() { - c.clear(); - } - app.session.dirty = true; - } -} - -fn shortcuts(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - heading(ui, tr("Node creation shortcuts")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::icon_button(ui, icon::ARROWS_CLOCKWISE, tr("Clear every shortcut"), false, 22.0).clicked() { - app.prefs_editor.node_shortcuts.clear(); - } - }); - }); - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut app.prefs_editor.shortcut_search).hint_text(tr("Search")).desired_width(220.0)); - ui.add(egui::TextEdit::singleline(&mut app.prefs_editor.shortcut_key_search).hint_text(tr("Search by shortcut")).desired_width(160.0)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let n = app.prefs_editor.node_shortcuts.len(); - ui.label(RichText::new(format!("{n} {}", tr("assigned"))).color(tk.text_dim)); - }); - }); - ui.label(RichText::new(tr("Click a field and press the keys (Escape clears). The node is added next to the selection.")).small().color(tk.text_dim)); - let search = app.prefs_editor.shortcut_search.to_ascii_lowercase(); - let key_search = app.prefs_editor.shortcut_key_search.to_ascii_lowercase(); - // Capture a chord for the field that waits for one. - if let Some(def) = app.prefs_editor.capturing.clone() { - let pressed = ui.input(|i| { - if i.key_pressed(egui::Key::Escape) { - return Some(String::new()); - } - i.events.iter().find_map(|e| match e { - egui::Event::Key { key, pressed: true, modifiers, .. } if !matches!(key, egui::Key::Escape) => { - let mut parts = Vec::new(); - if modifiers.ctrl || modifiers.command { - parts.push("Ctrl"); - } - if modifiers.shift { - parts.push("Shift"); - } - if modifiers.alt { - parts.push("Alt"); - } - let name = key.name(); - parts.push(name); - Some(parts.join("+")) - } - _ => None, - }) - }); - if let Some(chord) = pressed { - app.prefs_editor.node_shortcuts.retain(|(d, _)| *d != def); - if !chord.is_empty() { - // One chord per node: the previous owner loses it. - app.prefs_editor.node_shortcuts.retain(|(_, c)| *c != chord); - app.prefs_editor.node_shortcuts.push((def, chord)); - } - app.prefs_editor.capturing = None; - } - } - egui::Grid::new("node-shortcuts").num_columns(2).striped(true).spacing([16.0, 4.0]).show(ui, |ui| { - for d in materialcraft_engine::nodes::catalog() { - if d.id == "graph_instance" { - continue; - } - let current = app.prefs_editor.node_shortcuts.iter().find(|(def, _)| *def == d.id).map(|(_, c)| c.clone()).unwrap_or_default(); - if !search.is_empty() && !d.label.to_ascii_lowercase().contains(&search) && !d.id.contains(&search) { - continue; - } - if !key_search.is_empty() && !current.to_ascii_lowercase().contains(&key_search) { - continue; - } - ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::hover()); - ui.painter().rect_filled(r, 3.0, crate::graph::header_color(d.id)); - ui.label(d.label); - }); - let capturing = app.prefs_editor.capturing.as_deref() == Some(d.id); - let text = if capturing { tr("Press keys...").to_string() } else { current.clone() }; - let b = ui.add(egui::Button::new(if text.is_empty() { " ".to_string() } else { text }).min_size(vec2(200.0, 20.0)).selected(capturing)); - crate::widgets::name(&b, egui::Role::TextInput, d.label); - if b.clicked() { - app.prefs_editor.capturing = Some(d.id.to_string()); - } - ui.end_row(); - } - }); +fn view3d(preferences: &mut Prefs, ui: &mut Ui) { + crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut preferences.camera.pan_limit, 0.0..=20.0, 1); + crate::widgets::slider(ui, tr("3D pan speed"), &mut preferences.camera.pan_speed, 0.1..=4.0, 2); } diff --git a/crates/ui-egui/src/preferences/preference_tab.rs b/crates/ui-egui/src/preferences/preference_tab.rs new file mode 100644 index 0000000..f5b2224 --- /dev/null +++ b/crates/ui-egui/src/preferences/preference_tab.rs @@ -0,0 +1,19 @@ +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PreferenceTab { + #[default] + General, + Graph, + View3d, +} + +impl PreferenceTab { + pub const ALL: [Self; 3] = [Self::General, Self::Graph, Self::View3d]; + + pub fn label(self) -> &'static str { + match self { + Self::General => "General", + Self::Graph => "Graph", + Self::View3d => "3D View", + } + } +} diff --git a/crates/ui-egui/src/property/graph.rs b/crates/ui-egui/src/property/graph.rs index 166b627..8613cdb 100644 --- a/crates/ui-egui/src/property/graph.rs +++ b/crates/ui-egui/src/property/graph.rs @@ -5,8 +5,26 @@ use egui_phosphor::regular as icon; use materialcraft_engine::core::{Graph, OutputFormat, Resource, Value}; use serde_json::{Value as JsonValue, json}; +/// A one-line field for a value the engine holds: what is typed stays between frames, and the text +/// comes back when the field loses focus with something new in it. A change to the value from +/// elsewhere (undo) drops the draft. +fn draft_field(ui: &mut Ui, salt: String, current: &str, label: &str) -> Option<String> { + let id = ui.make_persistent_id(salt); + let draft: Option<(String, String)> = ui.data(|data| data.get_temp(id)); + let mut text = draft.filter(|(seen, _)| seen == current).map_or_else(|| current.to_string(), |(_, text)| text); + let response = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, label); + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(id, (current.to_string(), text.clone()))); + } else { + ui.data_mut(|data| data.remove_temp::<(String, String)>(id)); + } + (response.lost_focus() && text != current).then_some(text) +} + pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); + let graph_index = app.session.graph; let Ok(graph) = app.session.graph() else { ui.label(tr("No graph is open")); return; @@ -17,10 +35,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { section(ui, "graph-base", tr("Base parameters"), |ui| { ui.horizontal(|ui| { ui.label(tr("Name")); - let mut name = graph.name.clone(); - let response = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width())); - crate::widgets::name(&response, egui::Role::TextInput, "Graph name"); - if response.lost_focus() && name != graph.name { + if let Some(name) = draft_field(ui, format!("graph-name-{graph_index}"), &graph.name, "Graph name") { emit("graph.rename", json!({"name": name})); } }); @@ -57,10 +72,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ] { ui.horizontal(|ui| { ui.label(tr(label)); - let mut edited = current.clone(); - let response = ui.add(egui::TextEdit::singleline(&mut edited).desired_width(ui.available_width())); - crate::widgets::name(&response, egui::Role::TextInput, label); - if response.lost_focus() && edited != *current { + if let Some(edited) = draft_field(ui, format!("graph-attribute-{graph_index}-{key}"), current, label) { emit("graph.attributes", json!({key: edited})); } }); diff --git a/crates/ui-egui/src/property/mod.rs b/crates/ui-egui/src/property/mod.rs index d1be9b2..89e6720 100644 --- a/crates/ui-egui/src/property/mod.rs +++ b/crates/ui-egui/src/property/mod.rs @@ -15,9 +15,6 @@ use egui::Ui; /// The panel title: "<node> - Properties" or "<graph> - Properties" pub fn title(app: &MaterialCraftApp) -> String { - if let Some((page, _)) = &app.props3d { - return crate::view3d_props::title(*page); - } match EditorTarget::resolve(app) { EditorTarget::Pattern => return crate::pattern::properties::title(app), EditorTarget::Function if !EditorTarget::annotation_active(app) => { @@ -41,18 +38,6 @@ pub fn title(app: &MaterialCraftApp) -> String { } pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - // A 3D view page stays until the user selects something else in the graph - if let Some((page, sel)) = app.props3d.clone() { - if sel != app.session.selection { - app.props3d = None; - } else { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.push_id(("props3d", page.title()), |ui| crate::view3d_props::show(app, ui, page)); - }); - return; - } - } egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.set_width(ui.available_width()); match EditorTarget::resolve(app) { diff --git a/crates/ui-egui/src/property/parameter.rs b/crates/ui-egui/src/property/parameter.rs index f0ce608..6d253e5 100644 --- a/crates/ui-egui/src/property/parameter.rs +++ b/crates/ui-egui/src/property/parameter.rs @@ -49,7 +49,8 @@ pub(super) fn param_row( ui.close(); } if ui.button(tr("Expose as graph input")).clicked() { - app.run("graph.exposed.add", json!({"id": parameter.id, "label": parameter.label, "bind": {"node": node.0, "param": parameter.id}})); + // No `id`: the engine names the input after the parameter and keeps it unique when another node exposed it too + app.run("graph.exposed.add", json!({"label": parameter.label, "bind": {"node": node.0, "param": parameter.id}})); ui.close(); } if !exposed.is_empty() { diff --git a/crates/ui-egui/src/state/prefs.rs b/crates/ui-egui/src/state/prefs.rs index 5598c5a..2a6e0c5 100644 --- a/crates/ui-egui/src/state/prefs.rs +++ b/crates/ui-egui/src/state/prefs.rs @@ -25,57 +25,6 @@ pub struct Prefs { pub show_home: bool, /// 3D view camera: pan limit and speed pub camera: CameraPrefs, - /// Show the main toolbar under the menu bar (Windows ▸ Main toolbar) - pub show_main_toolbar: bool, - /// Worker threads the cook may use (Tools ▸ Switch engine; 0 = every core) - pub cook_threads: usize, - /// Library tile size (icons view), 56..160 px - pub library_tile: f32, - /// Graph toolbar: show each node's cook time - pub node_timings: bool, - /// Graph toolbar: straight wires instead of curves - pub straight_wires: bool, - /// Graph toolbar: draw the background grid - pub show_grid: bool, - /// General: how many recent packages the File menu keeps - pub recent_count: u32, - /// General: undo steps kept - pub history_size: u32, - /// General: wheel zooms the other way in every view - pub invert_zoom: bool, - /// General: where file dialogs open: `last`, `package` or `custom` (`save_path`) - pub save_path_mode: String, - pub save_path: String, - /// General: the auto-backup folder (empty = Documents/MaterialCraft/autosave) - pub temp_dir: String, - /// General: the cooked image cache's size in MB (0 = automatic) - pub cache_mb: u32, - /// General: auto-backup versions kept per package - pub backup_versions: u32, - /// General: cap on every cook's larger side in px (0 = none) - pub cook_limit: u32, - /// Projects: lights on in a new session when no default 3D state is saved (ambient, point 1, point 2) - pub default_lights: [bool; 3], - /// Graph: Tab opens the node search - pub tab_key_menu: bool, - /// Graph: dragging a wire into empty space opens the node search - pub drag_create: bool, - /// Graph: show the 3D view when a graph opens - pub view_3d_on_open: bool, - /// Graph: show the graph's output in the 2D view when it opens - pub view_2d_on_open: bool, - /// Graph: show a newly added node in the 2D view - pub auto_display_new_node: bool, - /// Graph: insert a conversion node when a color wire meets a grayscale input (or the reverse) - pub auto_convert: bool, - /// 3D view: the environment is hidden behind the mesh by default - pub env_hidden: bool, - /// 3D view: default viewport render scale (0 = auto) - pub viewport_scale: f32, - /// 3D view: default samples per pixel of the resting frame (n × n) - pub sample_count: u32, - /// Bakers: worker threads (0 = every core) - pub bake_threads: u32, } impl Default for Prefs { @@ -92,32 +41,6 @@ impl Default for Prefs { library_list: false, show_home: true, camera: CameraPrefs::default(), - show_main_toolbar: true, - cook_threads: 0, - library_tile: 78.0, - node_timings: false, - straight_wires: false, - show_grid: true, - recent_count: 12, - history_size: 200, - invert_zoom: false, - save_path_mode: "last".into(), - save_path: String::new(), - temp_dir: String::new(), - cache_mb: 0, - backup_versions: 6, - cook_limit: 8192, - default_lights: [true, false, false], - tab_key_menu: true, - drag_create: true, - view_3d_on_open: true, - view_2d_on_open: true, - auto_display_new_node: true, - auto_convert: false, - env_hidden: true, - viewport_scale: 0.0, - sample_count: 2, - bake_threads: 0, } } } diff --git a/crates/ui-egui/src/state/ui_state.rs b/crates/ui-egui/src/state/ui_state.rs index f10403b..8bd6a75 100644 --- a/crates/ui-egui/src/state/ui_state.rs +++ b/crates/ui-egui/src/state/ui_state.rs @@ -14,35 +14,17 @@ pub struct UiState { /// Library: the selected category path ("" = all) and the search text pub library_category: String, pub library_search: String, - /// Library entries starred by the user (node ids, `@graph`, `fn:op`) - pub library_favorites: Vec<String>, - /// Library tree groups that are folded shut - pub library_collapsed: Vec<String>, /// Recently opened or saved packages, newest first pub recent: Vec<String>, - /// Plugins (file or folder paths in the plugins folder) whose graphs the library offers - pub plugins_loaded: Vec<String>, - /// 3D view ▸ Scene ▸ Save Current State As Default: the state new sessions and Reset Scene use - pub view3d_default: Option<serde_json::Value>, - /// The folder the last file dialog ended in (Preferences ▸ Save/Export path: Last path) - pub last_dir: String, - /// Preferences ▸ Shortcuts: node creation shortcuts, def id → shortcut ("Ctrl+Shift+B") - pub node_shortcuts: Vec<(String, String)>, /// New graph dialog fields pub new_graph_kind: materialcraft_engine::core::GraphKind, pub new_graph_template: String, pub new_graph_name: String, pub new_graph_size: u32, - /// New graph height when the two sizes are unlinked (0 = same as the width) pub new_graph_height: u32, - /// Keep width and height the same in the new graph dialog pub new_graph_link: bool, - /// Template category shown in the new graph dialog (empty = all) - pub new_graph_category: String, - /// Graph toolbar: the parent size's width and height change together - pub parent_link: bool, - /// Graph toolbar: the align buttons also stack the nodes (no gaps) - pub stack_align: bool, + #[serde(skip)] + pub preferences_tab: crate::preferences::PreferenceTab, /// Export dialog fields pub export_dir: String, pub export_format: String, @@ -65,22 +47,14 @@ impl Default for UiState { image_camera: ImageCamera::default(), library_category: String::new(), library_search: String::new(), - library_favorites: Vec::new(), - library_collapsed: Vec::new(), recent: Vec::new(), - plugins_loaded: Vec::new(), - view3d_default: None, - last_dir: String::new(), - node_shortcuts: Vec::new(), new_graph_kind: materialcraft_engine::core::GraphKind::Material, new_graph_template: "pbr".into(), - new_graph_name: "Material_Graph".into(), + new_graph_name: "New_graph".into(), new_graph_size: 1024, - new_graph_height: 0, + new_graph_height: 1024, new_graph_link: true, - new_graph_category: String::new(), - parent_link: true, - stack_align: true, + preferences_tab: crate::preferences::PreferenceTab::default(), export_dir: String::new(), export_format: "png".into(), export_depth: 0, @@ -96,6 +70,6 @@ impl UiState { pub fn add_recent(&mut self, path: &str) { self.recent.retain(|p| p != path); self.recent.insert(0, path.to_string()); - self.recent.truncate(self.prefs.recent_count.clamp(1, 50) as usize); + self.recent.truncate(12); } } diff --git a/crates/ui-egui/src/state/windows.rs b/crates/ui-egui/src/state/windows.rs index 60aa445..a3638ad 100644 --- a/crates/ui-egui/src/state/windows.rs +++ b/crates/ui-egui/src/state/windows.rs @@ -10,10 +10,6 @@ pub struct Windows { pub preferences: bool, pub shortcuts: bool, pub home: bool, - pub plugin_manager: bool, - pub switch_engine: bool, - /// The Dependency Manager window (Windows menu) - pub dependencies: bool, #[serde(skip_deserializing)] pub unsaved: Option<crate::unsaved::Guarded>, } diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 241c497..9b16b40 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -17,45 +17,11 @@ pub struct Thumbs { /// (cook key, port) → texture and the frame it was last used nodes: HashMap<(u64, usize), (TextureHandle, u64)>, library: HashMap<String, TextureHandle>, - /// Environment previews by id (the equirectangular map, tone mapped) - environments: HashMap<String, TextureHandle>, library_rx: Option<Receiver<Previews>>, library_started: bool, frame: u64, } -impl Thumbs { - /// A small picture of a 3D view environment (rendered once per id) - pub fn environment(&mut self, ctx: &egui::Context, id: &str) -> Option<egui::TextureId> { - if let Some(t) = self.environments.get(id) { - return Some(t.id()); - } - let env = materialcraft_render::ibl::environment(materialcraft_render::ibl::by_id(id), 256); - let (w, h) = (env.width as usize, env.height as usize); - let mut rgba = Vec::with_capacity(w * h * 4); - for px in &env.data { - for c in px { - // Exposure down a stop and a gamma: bright skies stay readable - let v = materialcraft_engine::image::linear_to_srgb((c * 0.5).min(1.0)); - rgba.push((v * 255.0 + 0.5) as u8); - } - rgba.push(255); - } - let img = ColorImage::from_rgba_unmultiplied([w, h], &rgba); - let t = ctx.load_texture(format!("env-{id}"), img, TextureOptions::LINEAR); - let tid = t.id(); - self.environments.insert(id.to_string(), t); - Some(tid) - } - - /// Drop the library previews and generate them again (Preferences ▸ Library ▸ Rebuild Thumbnails) - pub fn rebuild_library(&mut self) { - self.library.clear(); - self.library_rx = None; - self.library_started = false; - } -} - /// An image as an egui texture image (sRGB display, `side` px) pub fn color_image(img: &Image, side: u32) -> ColorImage { let small = img.resize(side, side, true); diff --git a/crates/ui-egui/src/tool_windows.rs b/crates/ui-egui/src/tool_windows.rs deleted file mode 100644 index bee07ac..0000000 --- a/crates/ui-egui/src/tool_windows.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Tools and Windows menu dialogs: the engine switch, the dependency manager and the log export. - -use egui::{RichText, Ui, vec2}; -use egui_phosphor::regular as icon; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -/// The engines the cook can run on: worker thread counts (0 = every core). -fn engines() -> Vec<(usize, String)> { - let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); - let mut out = vec![(0, format!("{} ({cores} {})", tr("CPU, all cores"), tr("threads")))]; - if cores > 2 { - out.push((cores / 2, format!("{} ({} {})", tr("CPU, half the cores"), cores / 2, tr("threads")))); - } - out.push((1, tr("CPU, one thread (leaves the machine responsive)").to_string())); - out -} - -/// The engine's name for the status bar. -pub fn engine_label(app: &MaterialCraftApp) -> String { - let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); - let n = if app.cooker.threads == 0 { cores } else { app.cooker.threads.min(cores) }; - if app.cooker.suspended { format!("CPU ({n} {}, {})", tr("threads"), tr("suspended")) } else { format!("CPU ({n} {})", tr("threads")) } -} - -/// Tools ▸ Switch engine (F9): pick how many threads the cook may use. -pub fn switch_engine(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let mut open = true; - let mut chosen: Option<usize> = None; - crate::windows::modal(ctx, "switch-engine", tr("Switch engine"), &mut open, vec2(420.0, 200.0), |ui| { - ui.label(tr("Every graph computes on the CPU through the content-addressed cache. Choose how much of the machine it may use:")); - ui.add_space(6.0); - for (threads, label) in engines() { - if ui.radio(app.cooker.threads == threads, label).clicked() { - chosen = Some(threads); - } - } - ui.add_space(8.0); - ui.label(RichText::new(tr("The next compute uses the new setting; a running one finishes first.")).small().color(Tokens::get(ui.ctx()).text_dim)); - }); - if let Some(t) = chosen { - app.cooker.threads = t; - app.ui.prefs.cook_threads = t; - app.session.dirty = true; - open = false; - } - if !open { - app.ui.windows.switch_engine = false; - } -} - -/// Everything the open package depends on: its bitmap resources (embedded or linked to a file) -/// and the graphs its graph instances point at. -pub fn dependencies(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let mut open = true; - let mut relink: Option<usize> = None; - let mut reload = false; - crate::windows::modal(ctx, "dependencies", tr("Dependency Manager"), &mut open, vec2(620.0, 380.0), |ui| { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(tr("RESOURCES")).small().color(tk.text_dim)); - if app.session.pkg.resources.is_empty() { - ui.label(RichText::new(tr("No bitmap resources: Tools > Import bitmap... embeds one, Link bitmap... keeps it on disk.")).color(tk.text_dim)); - } - egui::Grid::new("deps-resources").num_columns(4).striped(true).spacing([12.0, 4.0]).show(ui, |ui| { - ui.label(RichText::new(tr("Name")).strong()); - ui.label(RichText::new(tr("Source")).strong()); - ui.label(RichText::new(tr("Size")).strong()); - ui.label(""); - ui.end_row(); - for (i, r) in app.session.pkg.resources.iter().enumerate() { - ui.label(&r.name); - match &r.link { - Some(path) => { - let exists = std::path::Path::new(path).exists(); - let text = RichText::new(format!("{} {path}", icon::LINK)); - ui.label(if exists { text } else { text.color(tk.danger) }).on_hover_text(if exists { - tr("Linked file") - } else { - tr("Linked file not found") - }); - } - None => { - ui.label(RichText::new(format!("{} {}", icon::PACKAGE, tr("embedded in the package"))).color(tk.text_dim)); - } - } - ui.label(format!("{} KB", r.bytes.as_slice().len() / 1024)); - ui.horizontal(|ui| { - if r.link.is_some() && ui.small_button(tr("Relink...")).clicked() { - relink = Some(i); - } - }); - ui.end_row(); - } - }); - ui.add_space(10.0); - ui.label(RichText::new(tr("GRAPH INSTANCES")).small().color(tk.text_dim)); - let mut rows: Vec<(String, String, bool)> = Vec::new(); - for g in &app.session.pkg.graphs { - for n in g.nodes.iter().filter(|n| n.def == "graph_instance") { - let target = match n.params.get("graph") { - Some(materialcraft_engine::core::Value::Text(t)) => t.clone(), - _ => String::new(), - }; - let found = app.session.pkg.graphs.iter().any(|x| x.name == target); - rows.push((g.name.clone(), target, found)); - } - } - if rows.is_empty() { - ui.label(RichText::new(tr("No graph instances: every graph of this package stands on its own.")).color(tk.text_dim)); - } else { - egui::Grid::new("deps-graphs").num_columns(3).striped(true).spacing([12.0, 4.0]).show(ui, |ui| { - ui.label(RichText::new(tr("Graph")).strong()); - ui.label(RichText::new(tr("Uses")).strong()); - ui.label(RichText::new(tr("State")).strong()); - ui.end_row(); - for (from, to, found) in rows { - ui.label(from); - ui.label(if to.is_empty() { tr("(not set)").to_string() } else { to }); - if found { - ui.label(RichText::new(tr("found")).color(tk.text_dim)); - } else { - ui.label(RichText::new(tr("missing")).color(tk.danger)); - } - ui.end_row(); - } - }); - } - ui.add_space(10.0); - ui.horizontal(|ui| { - if ui.button(tr("Reload linked files")).clicked() { - reload = true; - } - }); - }); - #[cfg(not(target_arch = "wasm32"))] - if let Some(i) = relink - && let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - && let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) - { - app.run("file.linkBitmap", serde_json::json!({"path": p.display().to_string(), "name": name})); - } - #[cfg(target_arch = "wasm32")] - let _ = relink; - if reload { - crate::menus::invoke(app, ctx, "ui.reloadResources"); - } - if !open { - app.ui.windows.dependencies = false; - } -} - -/// Import graph: which graph of the picked package to copy into this one. -pub fn import_pick(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let Some((path, graphs)) = app.import_pick.clone() else { return }; - let mut open = true; - let mut chosen: Option<String> = None; - crate::windows::modal(ctx, "import-graph", tr("Import graph"), &mut open, vec2(420.0, 260.0), |ui| { - ui.label(RichText::new(&path).small().color(Tokens::get(ui.ctx()).text_dim)); - ui.add_space(4.0); - egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| { - for g in &graphs { - if ui.button(format!("{} {g}", icon::TREE_STRUCTURE)).clicked() { - chosen = Some(g.clone()); - } - } - }); - }); - if let Some(g) = chosen { - if let Some(r) = app.run("file.importGraph", serde_json::json!({"path": path, "graph": g})) { - app.toast(format!("{} {}", tr("Imported graph"), r["name"].as_str().unwrap_or_default()), false); - } - open = false; - } - if !open { - app.import_pick = None; - } -} - -/// Help ▸ Export log: the session's log as a text file. -pub fn export_log(app: &mut MaterialCraftApp) { - let text = app.session.log.join("\n"); - #[cfg(not(target_arch = "wasm32"))] - { - let Some(p) = rfd::FileDialog::new().set_file_name("materialcraft-log.txt").add_filter("Text", &["txt"]).save_file() else { return }; - match std::fs::write(&p, text) { - Ok(()) => app.toast(format!("{} {}", tr("Log saved to"), p.display()), false), - Err(e) => app.toast(format!("{}: {e}", tr("Could not save the log")), true), - } - } - #[cfg(target_arch = "wasm32")] - { - match crate::web_files::download("materialcraft-log.txt", text.as_bytes()) { - Ok(()) => app.toast(tr("Log downloaded"), false), - Err(e) => app.toast(format!("{}: {e}", tr("Could not save the log")), true), - } - } -} - -/// A small heading row used by the dialogs (title left, hint right). -pub fn heading(ui: &mut Ui, title: &str) { - let tk = Tokens::get(ui.ctx()); - ui.add_space(4.0); - ui.label(RichText::new(title).small().strong().color(tk.text_dim)); -} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 6608f88..8288e6f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -48,11 +48,12 @@ pub fn status_bar(app: &mut MaterialCraftApp, ui: &mut Ui) { } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let cache = app.session.cache.lock().map(|c| c.bytes()).unwrap_or(0); - let engine = crate::tool_windows::engine_label(app); + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); let preview = app.session.preview_size.map_or_else(|| tr("full size").to_string(), |p| format!("{p} px")); let text = format!( - "{}: {engine} | {}: {:.0} ms | {}: {preview} | {}: {} MB | {} {}", - tr("MC Engine"), + "{}: CPU ({threads} {}) | {}: {:.0} ms | {}: {preview} | {}: {} MB | {} {}", + tr("Engine"), + tr("threads"), tr("Last compute"), app.session.cooked.ms, tr("Preview"), diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 4357c88..70bb3ac 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -13,8 +13,6 @@ use crate::theme::Tokens; #[derive(Default)] pub struct View2dState { tex: Option<(u64, TextureHandle)>, - /// Draw the 3D scene's UV layout over the image (3D view ▸ Scene ▸ Display UVs in 2D View) - pub show_uvs: bool, /// The last shown image (RGBA8, for `view.screenshot`). pub shown: Option<(u32, u32, Vec<u8>)>, /// Per-channel histograms of `shown` (R, G, B; one channel for gray), keyed like `tex`. @@ -23,34 +21,6 @@ pub struct View2dState { const BINS: usize = 64; -/// The 3D scene's UV triangles over the image (the 0..1 tile is `tile`), clipped to `clip` -fn draw_uvs(app: &MaterialCraftApp, p: &egui::Painter, tile: Rect, clip: Rect) { - let v = &app.session.view3d; - let mesh = match (&*v.scene, &app.session.custom_mesh) { - ("custom", Some((_, m))) => (**m).clone(), - _ => materialcraft_render::builtin_mesh(&v.scene), - }; - const MAX_EDGES: usize = 300_000; - let to_screen = |uv: materialcraft_engine::geom::glam::Vec2| pos2(tile.left() + uv.x * tile.width(), tile.top() + uv.y * tile.height()); - let stroke = egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(0x40, 0xc0, 0xff, 170)); - let mut drawn = 0; - for t in 0..mesh.triangle_count() { - let Some([a, b, c]) = mesh.tri(t) else { break }; - let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; - let pts = [to_screen(*ua), to_screen(*ub), to_screen(*uc)]; - if pts.iter().all(|q| !clip.contains(*q)) { - continue; - } - p.line_segment([pts[0], pts[1]], stroke); - p.line_segment([pts[1], pts[2]], stroke); - p.line_segment([pts[2], pts[0]], stroke); - drawn += 3; - if drawn > MAX_EDGES { - break; - } - } -} - /// Histograms of the displayed 8-bit values: one for gray or isolated channels, else R, G and B. fn histogram(px: &[u8], channels: usize) -> Vec<[u32; BINS]> { let mut h = vec![[0u32; BINS]; channels]; @@ -125,6 +95,8 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let texture_limit = ctx.input(|i| i.max_texture_side).max(1); let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key) ^ (texture_limit as u64).rotate_left(32) + ^ (img.w as u64).rotate_left(16) + ^ img.h as u64 ^ (app.session.view2d.port as u64).wrapping_mul(0x9e37) ^ (app.session.view2d.channel.len() as u64 * 31) ^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64; @@ -156,7 +128,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { cam.offset = [0.0, 0.0]; } if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y) * if app.ui.prefs.invert_zoom { -1.0 } else { 1.0 }; + let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll.abs() > 0.0 { cam.fit = false; let old = cam.zoom; @@ -202,10 +174,6 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { p.rect_stroke(Rect::from_center_size(center, size), 0.0, egui::Stroke::new(1.0, Color32::from_white_alpha(60)), egui::StrokeKind::Outside); } } - let zoom = cam.zoom; - if app.view2d.show_uvs { - draw_uvs(app, &p, Rect::from_center_size(center, size), rect); - } if app.session.view2d.histogram { let single = img.is_gray() || app.session.view2d.channel != "rgba"; draw_histogram(&mut app.view2d, &p, rect, key, single); @@ -220,9 +188,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { g.node(id).ok().map(|n| if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }) }) .unwrap_or("16"); - let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, zoom * 100.0); + let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); if let Some(ptr) = resp.hover_pos() { - let local = (ptr - (center - size * 0.5)) / zoom; + let local = (ptr - (center - size * 0.5)) / cam.zoom; let (x, y) = (local.x.floor() as i64, local.y.floor() as i64); let v = img.get(x, y, true); if img.is_gray() { diff --git a/crates/ui-egui/src/view3d.rs b/crates/ui-egui/src/view3d.rs index e6e186c..af0f89b 100644 --- a/crates/ui-egui/src/view3d.rs +++ b/crates/ui-egui/src/view3d.rs @@ -1,8 +1,7 @@ //! The 3D view: assigned material channels on a built-in scene, rendered by //! `materialcraft-render` (one ray per pixel at half resolution while the camera moves, 2×2 //! supersampled when it rests). Left-drag orbits, Alt+drag or middle-drag pans, the wheel zooms, -//! Shift+drag turns the light and a double-click resets the camera. Over the view, F frames the -//! mesh, R resets the camera position and Alt+S saves a render. +//! Shift+drag turns the light and a double-click resets the camera. //! //! The full-quality frame waits until the view's size and the camera have rested for [`SETTLE`] //! (a panel, divider or window drag changes the size on every step), then renders on a worker @@ -18,7 +17,7 @@ use std::time::Duration; use egui::{Color32, ColorImage, Rect, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2}; use egui_phosphor::regular as icon; -use materialcraft_engine::view_cmds::SCENES; +use materialcraft_engine::view_cmds::{ENVIRONMENTS, SCENES}; use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings}; use serde_json::json; @@ -56,8 +55,7 @@ pub struct View3dState { pub renders: u64, /// The last frame shown (RGBA8, for `view.screenshot`). pub shown: Option<(u32, u32, Vec<u8>)>, - /// Paint the environment behind the mesh (Display ▸ Environment background) - pub show_env: bool, + show_env: bool, } impl View3dState { @@ -90,15 +88,8 @@ impl Drop for Job { } } -mod actions; -mod menus; -mod overlays; mod relief_job; -pub mod settings; -mod side_strip; -pub use actions::{Page3d, copy_render, edit_properties, frame, reset_all, save_render}; use relief_job::ReliefJob; -pub use settings::settings_of; pub fn scene_label(app: &MaterialCraftApp) -> String { let id = &app.session.view3d.scene; @@ -110,14 +101,118 @@ pub fn scene_label(app: &MaterialCraftApp) -> String { SCENES.iter().find(|(s, _)| s == id).map_or(id.as_str(), |(_, l)| l).to_string() } +fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) { + let tk = Tokens::get(ui.ctx()); + egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(4, 1)).show(ui, |ui| { + egui::MenuBar::new().ui(ui, |ui| { + ui.menu_button(tr("Material"), |ui| { + let sources = app.session.material_preview.sources(&app.session.pkg); + for channel in materialcraft_engine::core::MaterialChannel::ALL { + let source = sources.get(&channel); + let label = source + .and_then(|source| { + let graph = app.session.pkg.graphs.get(source.graph)?; + let node = graph.node(source.node).ok()?; + Some(format!("{} / {}", graph.name, crate::graph::node_label(node))) + }) + .unwrap_or_else(|| tr("Unassigned").to_string()); + ui.label(format!("{}: {label}", tr(channel.label()))); + } + ui.separator(); + if ui.button(tr("Clear material assignments")).clicked() { + app.run("view.3d.clear", json!({})); + ui.close(); + } + }); + ui.menu_button(tr("Scene"), |ui| { + for (id, label) in SCENES { + if ui.selectable_label(app.session.view3d.scene == *id, tr(label)).clicked() { + app.run("view.3d", json!({"scene": id})); + ui.close(); + } + } + ui.separator(); + if ui.button(tr("Load mesh...")).clicked() { + crate::web_files::load_mesh(app, ui.ctx()); + ui.close(); + } + if app.session.custom_mesh.is_some() && ui.selectable_label(app.session.view3d.scene == "custom", scene_label_custom(app)).clicked() { + app.run("view.3d", json!({"scene": "custom"})); + ui.close(); + } + ui.separator(); + if ui.button(tr("Reset scene")).clicked() { + app.run("view.3d.reset", json!({})); + ui.close(); + } + }); + ui.menu_button(tr("Camera"), |ui| { + for (label, yaw, pitch) in [("Default", 35.0, 25.0), ("Front", 0.0, 0.0), ("Top", 0.0, 89.0), ("Side", 90.0, 0.0)] { + if ui.button(tr(label)).clicked() { + app.run("view.3d", json!({"yaw": yaw, "pitch": pitch, "distance": 3.2, "target": [0.0, 0.0, 0.0]})); + ui.close(); + } + } + }); + ui.menu_button(tr("Environment"), |ui| { + for (id, label) in ENVIRONMENTS { + if ui.selectable_label(app.session.view3d.environment == *id, tr(label)).clicked() { + app.run("view.3d", json!({"environment": id})); + ui.close(); + } + } + ui.separator(); + let mut rot = app.session.view3d.env_rotation; + if crate::widgets::slider(ui, tr("Rotation"), &mut rot, 0.0..=360.0, 0).changed() { + app.run("view.3d", json!({"envRotation": rot})); + } + let mut exp = app.session.view3d.exposure; + if crate::widgets::slider(ui, tr("Exposure"), &mut exp, -4.0..=4.0, 2).changed() { + app.run("view.3d", json!({"exposure": exp})); + } + }); + ui.menu_button(tr("Display"), |ui| { + crate::preview_resolution::show(app, ui); + ui.separator(); + let mut flip = app.session.view3d.normal_y_flip; + if ui.checkbox(&mut flip, tr("Flip normal map Y (DirectX)")).changed() { + app.run("view.3d", json!({"normalYFlip": flip})); + } + ui.separator(); + ui.checkbox(&mut app.view3d.show_env, tr("Environment background")); + ui.separator(); + let mut t = app.session.view3d.transparency; + if ui.checkbox(&mut t, tr("Transparency (alpha)")).changed() { + app.run("view.3d", json!({"transparency": t})); + } + let mut a = app.session.view3d.alpha_view; + if ui.checkbox(&mut a, tr("Show alpha channel")).changed() { + app.run("view.3d", json!({"alphaView": a})); + } + }); + ui.menu_button(tr("Renderer"), |ui| { + let mut depth_percent = app.session.view3d.height_scale * 100.0; + if crate::widgets::slider(ui, tr("Height depth (% of the mesh size)"), &mut depth_percent, 0.0..=20.0, 1).changed() { + app.run("view.3d", json!({"heightScale": depth_percent / 100.0})); + } + let mut level = app.session.view3d.height_level; + if crate::widgets::slider(ui, tr("Height level (0 = rises out of the surface)"), &mut level, 0.0..=1.0, 2).changed() { + app.run("view.3d", json!({"heightLevel": level})); + } + let mut t = app.session.view3d.tiling; + if crate::widgets::slider(ui, tr("Tiling"), &mut t, 0.25..=8.0, 2).changed() { + app.run("view.3d", json!({"tiling": t})); + } + }); + }); + }); +} + pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - menus::show(app, ui); + menus(app, ui); let avail = ui.available_size(); - let (whole, _) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::hover()); - let strip = Rect::from_min_size(whole.min, vec2(side_strip::WIDTH, whole.height())); - let rect = Rect::from_min_max(pos2(whole.left() + side_strip::WIDTH, whole.top()), whole.max); - let resp = ui.interact(rect, ui.scope_id().with("view3d-canvas"), Sense::click_and_drag()); + let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::click_and_drag()); crate::widgets::name(&resp, egui::Role::Image, "3D view"); let graph_hover = resp.dnd_hover_payload::<crate::graph_drag_payload::GraphDragPayload>().is_some(); if let Some(graph) = crate::widgets::dnd_release::<crate::graph_drag_payload::GraphDragPayload>(&resp) { @@ -147,26 +242,14 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { moving = true; } if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y) * if app.ui.prefs.invert_zoom { -1.0 } else { 1.0 }; + let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll.abs() > 0.0 { app.session.view3d.distance = (app.session.view3d.distance * (-scroll * 0.002).exp()).clamp(1.2, 20.0); moving = true; } } if resp.double_clicked() { - actions::reset_position(app); - } - if resp.hovered() && !ui.ctx().egui_wants_keyboard_input() { - let (f, r, alt_s) = ui.input(|i| (i.key_pressed(egui::Key::F), i.key_pressed(egui::Key::R), i.modifiers.alt && i.key_pressed(egui::Key::S))); - if f { - frame(app); - } - if r { - actions::reset_position(app); - } - if alt_s { - save_render(app); - } + app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2, "target": [0.0, 0.0, 0.0]})); } render(app, ui.ctx(), rect, moving || resp.is_pointer_button_down_on()); let p = ui.painter_at(rect); @@ -186,7 +269,6 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { tk.viewport_text, ); } - overlays::paint(app, &p, rect); p.text( rect.right_bottom() - vec2(8.0, 6.0), egui::Align2::RIGHT_BOTTOM, @@ -205,9 +287,8 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { ); } - side_strip::show(app, ui, strip); // Bottom bar - let bar = Rect::from_min_size(pos2(whole.left(), whole.bottom()), vec2(whole.width(), 22.0)); + let bar = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 22.0)); ui.scope_builder(egui::UiBuilder::new().max_rect(bar), |ui| { ui.painter().rect_filled(bar, 0.0, tk.panel); ui.horizontal_centered(|ui| { @@ -259,26 +340,10 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool, relief_sh for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale, v.height_level] { f.to_bits().hash(&mut hs); } - // Camera, lights, material, renderer and display settings: hashed through their JSON. - serde_json::to_string(&(&v.camera, &v.lights, &v.material, &v.renderer, &v.display, v.env_enabled)).unwrap_or_default().hash(&mut hs); app.session.material_key().hash(&mut hs); hs.finish() } -/// A frame at the camera's render resolution (else the shown frame's size), for Save Render -fn render_offscreen(app: &mut MaterialCraftApp) -> Option<(u32, u32, Vec<u8>)> { - let cam = app.session.view3d.camera.clone(); - let (w, h) = if cam.override_resolution { - let k = cam.resolution_scale; - (((cam.resolution[0] as f32 * k) as u32).clamp(16, 4096), ((cam.resolution[1] as f32 * k) as u32).clamp(16, 4096)) - } else { - app.view3d.shown.as_ref().map_or((1280, 720), |(w, h, _)| (*w, *h)) - }; - let (scene, light, maps, settings) = inputs(app, 2)?; - let px = materialcraft_render::render(&scene, &maps, &light, &settings, w, h); - Some((w, h, px)) -} - /// Keep the 3D view's texture up to date: a quick frame right away while the camera moves, the /// full-quality one once the view's size and the camera have rested for [`SETTLE`]. fn render(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, moving: bool) { @@ -356,7 +421,7 @@ fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option<u6 use std::hash::{DefaultHasher, Hash, Hasher}; let v = &app.session.view3d; - if maps.height.is_none() || v.height_scale <= 0.0 || !v.material.use_map.height { + if maps.height.is_none() || v.height_scale <= 0.0 { return None; } @@ -365,8 +430,8 @@ fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option<u6 let height_cook = app.session.material_source_key(height_source); let mut hasher = DefaultHasher::new(); - (scene_key, height_cook, maps.normal.is_some() && v.material.use_map.normal).hash(&mut hasher); - for f in [v.height_scale, v.height_level, v.tiling, v.material.tessellation, v.material.uv_scale[0]] { + (scene_key, height_cook, maps.normal.is_some()).hash(&mut hasher); + for f in [v.height_scale, v.height_level, v.tiling] { f.to_bits().hash(&mut hasher); } Some(hasher.finish()) @@ -396,27 +461,19 @@ fn update_relief(app: &mut MaterialCraftApp, ctx: &egui::Context) -> Option<u64> if app.view3d.relief_job.is_none() { let v = &app.session.view3d; let relief = Relief { depth: v.height_scale, level: v.height_level }; - let budget = ((RELIEF_TRIANGLES as f32) * v.material.tessellation.clamp(0.1, 4.0)) as usize; - let tiling = v.tiling * v.material.uv_scale[0].max(0.01); - // With the normal map switched off (Material > Use maps), the relief shades from its own geometry - let mut maps = maps; - if !v.material.use_map.normal { - maps.normal = None; - } - start_relief(app, ctx, wanted, base, maps, relief, tiling, budget); + start_relief(app, ctx, wanted, base, maps, relief, v.tiling); } None } -/// Build the displaced scene on a worker thread, within `budget` triangles. +/// Build the displaced scene on a worker thread. #[cfg(not(target_arch = "wasm32"))] -#[allow(clippy::too_many_arguments)] -fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32, budget: usize) { +fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32) { let (tx, rx) = std::sync::mpsc::channel(); let (repaint, viewport) = (ctx.clone(), ctx.viewport_id()); let (thread_base, thread_maps) = (base.clone(), maps.clone()); let spawned = std::thread::Builder::new().name("materialcraft-relief".into()).spawn(move || { - let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, budget).map(Arc::new)); + let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, RELIEF_TRIANGLES).map(Arc::new)); repaint.request_repaint_of(viewport); }); @@ -424,16 +481,15 @@ fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Ok(_) => app.view3d.relief_job = Some(ReliefJob { key, rx }), Err(e) => { log::warn!("could not start a 3D view relief thread ({e}); building it here"); - app.view3d.displaced = base.with_relief(&maps, relief, tiling, budget).map(|scene| (key, Arc::new(scene))); + app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene))); } } } /// The browser has no threads: the displaced scene builds here (the page pauses). #[cfg(target_arch = "wasm32")] -#[allow(clippy::too_many_arguments)] -fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32, budget: usize) { - app.view3d.displaced = base.with_relief(&maps, relief, tiling, budget).map(|scene| (key, Arc::new(scene))); +fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32) { + app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene))); } /// The scene, lighting, maps and settings of the current view: the displaced scene when it is current, else the plain one. @@ -444,7 +500,21 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A app.view3d.light = Some(Arc::new(Lighting::new(&v.environment))); } - let settings = settings_of(&v, app.view3d.show_env, supersample); + let settings = Settings { + yaw: v.yaw, + pitch: v.pitch, + distance: v.distance, + target: v.target, + tiling: v.tiling, + exposure: v.exposure, + env_rotation: v.env_rotation, + normal_y_flip: v.normal_y_flip, + show_env: app.view3d.show_env, + supersample, + transparency: v.transparency, + alpha_view: v.alpha_view, + ..Settings::default() + }; let maps = Maps::from_usages(app.session.material_maps()); let wanted = relief_key(app, &scene_key, &maps); let scene = match &app.view3d.displaced { @@ -472,9 +542,8 @@ fn render_now(app: &mut MaterialCraftApp, rect: Rect, scale: f32, supersample: u /// Start the full-quality frame (2×2 supersampled, full resolution) on a worker thread. #[cfg(not(target_arch = "wasm32"))] fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key: u64, size: (u32, u32)) { - let samples = settings::samples(app); - let Some((scene, light, maps, settings)) = inputs(app, samples) else { return }; - let (w, h) = pixels(rect, ctx.pixels_per_point() * settings::view_scale(app)); + let Some((scene, light, maps, settings)) = inputs(app, 2) else { return }; + let (w, h) = pixels(rect, ctx.pixels_per_point()); let cancel = Arc::new(AtomicBool::new(false)); let (tx, rx) = std::sync::mpsc::channel(); let (stop, repaint, viewport) = (cancel.clone(), ctx.clone(), ctx.viewport_id()); @@ -488,8 +557,7 @@ fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key: Ok(_) => app.view3d.job = Some(Job { key, size, cancel, rx }), Err(e) => { log::warn!("could not start a 3D view render thread ({e}); rendering here"); - let scale = ctx.pixels_per_point() * settings::view_scale(app); - if let Some(frame) = render_now(app, rect, scale, samples) { + if let Some(frame) = render_now(app, rect, ctx.pixels_per_point(), 2) { show_frame(app, ctx, frame, key, true, size); } } @@ -499,8 +567,7 @@ fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key: /// The browser has no threads: the full-quality frame renders here (the page pauses). #[cfg(target_arch = "wasm32")] fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key: u64, size: (u32, u32)) { - let scale = ctx.pixels_per_point() * settings::view_scale(app); - if let Some(frame) = render_now(app, rect, scale, settings::samples(app)) { + if let Some(frame) = render_now(app, rect, ctx.pixels_per_point(), 2) { show_frame(app, ctx, frame, key, true, size); } } diff --git a/crates/ui-egui/src/view3d/actions.rs b/crates/ui-egui/src/view3d/actions.rs deleted file mode 100644 index b811b96..0000000 --- a/crates/ui-egui/src/view3d/actions.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! What the 3D view's menus do beyond one `view.3d` call: property pages, framing, resets, -//! state files, saving and copying a render - -use egui::ColorImage; -use serde_json::json; - -use crate::MaterialCraftApp; -use crate::i18n::tr; - -/// Which 3D view property page the Properties panel shows (Edit properties) -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Page3d { - Camera, - Lights, - Environment, - Renderer, - Material, -} - -impl Page3d { - pub fn title(self) -> &'static str { - match self { - Page3d::Camera => "Camera", - Page3d::Lights => "Lights", - Page3d::Environment => "Environment", - Page3d::Renderer => "Renderer", - Page3d::Material => "Material", - } - } -} - -/// Open a 3D view property page in the Properties panel -pub fn edit_properties(app: &mut MaterialCraftApp, page: Page3d) { - app.props3d = Some((page, app.session.selection.clone())); - app.ui.dock.focus(crate::docking::Panel::Properties); -} - -/// Camera ▸ Frame (F): fit the mesh in the view -pub fn frame(app: &mut MaterialCraftApp) { - app.run("view.3d", json!({"distance": 3.2, "target": [0.0, 0.0, 0.0]})); -} - -/// Camera ▸ Reset Position (R) -pub fn reset_position(app: &mut MaterialCraftApp) { - app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2, "target": [0.0, 0.0, 0.0]})); -} - -/// Scene ▸ Reset Scene: the saved default state, else the built-in one -pub fn reset_all(app: &mut MaterialCraftApp) { - match app.ui.view3d_default.clone() { - Some(state) => { - app.run("view.3d.loadState", json!({"state": state})); - } - None => { - app.run("view.3d.reset", json!({})); - } - } -} - -/// Scene ▸ Save Current State: the 3D view's state as a JSON file -pub(super) fn save_state(app: &mut MaterialCraftApp) { - #[cfg(not(target_arch = "wasm32"))] - { - let Some(state) = app.run("view.3d.state", json!({})) else { return }; - let Some(p) = crate::windows::dialog(app).set_file_name("3d-view-state.json").add_filter("3D view state", &["json"]).save_file() else { return }; - crate::windows::remember_dir(app, &p); - match serde_json::to_string_pretty(&state).map_err(|e| e.to_string()).and_then(|t| std::fs::write(&p, t).map_err(|e| e.to_string())) { - Ok(()) => app.toast(format!("{} {}", tr("Saved"), p.display()), false), - Err(e) => app.toast(format!("{}: {e}", tr("Could not save the state")), true), - } - } - #[cfg(target_arch = "wasm32")] - app.toast(tr("The desktop app saves state files"), true); -} - -/// Scene ▸ Load State File: restore a saved state (`with_mesh` also switches the scene) -pub(super) fn load_state(app: &mut MaterialCraftApp, with_mesh: bool) { - #[cfg(not(target_arch = "wasm32"))] - { - let Some(p) = crate::windows::dialog(app).add_filter("3D view state", &["json"]).pick_file() else { return }; - crate::windows::remember_dir(app, &p); - const MAX: u64 = 4 << 20; - if std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0) > MAX { - app.toast(tr("That is not a 3D view state file"), true); - return; - } - match std::fs::read_to_string(&p).map_err(|e| e.to_string()).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(|e| e.to_string())) { - Ok(state) => { - if app.run("view.3d.loadState", json!({"state": state, "keepScene": !with_mesh})).is_some() { - app.toast(format!("{} {}", tr("Loaded"), p.display()), false); - } - } - Err(e) => app.toast(format!("{}: {e}", tr("Could not read the state file")), true), - } - } - #[cfg(target_arch = "wasm32")] - { - let _ = with_mesh; - app.toast(tr("The desktop app loads state files"), true); - } -} - -/// Camera ▸ Save Render (Alt+S): the view at the camera's render resolution, as a PNG -pub fn save_render(app: &mut MaterialCraftApp) { - #[cfg(not(target_arch = "wasm32"))] - { - let name = format!("{}_render.png", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default())); - let Some(p) = crate::windows::dialog(app).set_file_name(name).add_filter("PNG", &["png"]).save_file() else { return }; - crate::windows::remember_dir(app, &p); - let Some((w, h, px)) = super::render_offscreen(app) else { return }; - match crate::control::encode_png(w, h, px) - .ok_or_else(|| tr("could not encode the image").to_string()) - .and_then(|(_, _, png)| std::fs::write(&p, png).map_err(|e| e.to_string())) - { - Ok(()) => app.toast(format!("{} {}", tr("Render saved to"), p.display()), false), - Err(e) => app.toast(format!("{}: {e}", tr("Could not save the render")), true), - } - } - #[cfg(target_arch = "wasm32")] - { - let Some((w, h, px)) = super::render_offscreen(app) else { return }; - if let Some((_, _, png)) = crate::control::encode_png(w, h, px) { - let _ = crate::web_files::download("render.png", &png); - } - } -} - -/// Camera ▸ Copy Render to Clipboard -pub fn copy_render(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let Some((w, h, px)) = super::render_offscreen(app) else { return }; - let img = ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &px); - ctx.copy_image(img); - app.toast(tr("Render copied to the clipboard"), false); -} diff --git a/crates/ui-egui/src/view3d/menus.rs b/crates/ui-egui/src/view3d/menus.rs deleted file mode 100644 index ed1fef1..0000000 --- a/crates/ui-egui/src/view3d/menus.rs +++ /dev/null @@ -1,306 +0,0 @@ -//! The 3D view's menu bar: Scene, Materials, Lights, Camera, Environment, Display, Renderer - -use egui::{RichText, Ui}; -use egui_phosphor::regular as icon; -use materialcraft_engine::view_cmds::{ENVIRONMENTS, SCENES}; -use materialcraft_render::{Common, MapUse, Shader}; -use serde_json::json; - -use super::actions::{self, Page3d, edit_properties, frame}; -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -fn menu_row(ui: &mut Ui, ic: &str, label: &str) -> bool { - ui.add(egui::Button::new(format!("{ic} {label}"))).clicked() -} - -pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(4, 1)).show(ui, |ui| { - egui::MenuBar::new().ui(ui, |ui| { - ui.menu_button(tr("Scene"), |ui| scene(app, ui)); - ui.menu_button(tr("Materials"), |ui| materials(app, ui)); - ui.menu_button(tr("Lights"), |ui| { - if menu_row(ui, icon::GEAR, tr("Edit properties")) { - edit_properties(app, Page3d::Lights); - ui.close(); - } - if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Lights")) { - app.run("view.3d.reset", json!({"what": "lights"})); - ui.close(); - } - }); - ui.menu_button(tr("Camera"), |ui| camera(app, ui)); - ui.menu_button(tr("Environment"), |ui| environment(app, ui)); - ui.menu_button(tr("Display"), |ui| display(app, ui)); - ui.menu_button(tr("Renderer"), |ui| { - if menu_row(ui, icon::GEAR, tr("Edit settings")) { - edit_properties(app, Page3d::Renderer); - ui.close(); - } - ui.separator(); - let _ = ui.selectable_label(true, tr("MC Ray caster (CPU)")); - ui.add_enabled(false, egui::Button::new(tr("GPU path tracer (not supported yet)"))); - ui.separator(); - let mut depth_percent = app.session.view3d.height_scale * 100.0; - if crate::widgets::slider(ui, tr("Height depth (% of the mesh size)"), &mut depth_percent, 0.0..=20.0, 1).changed() { - app.run("view.3d", json!({"heightScale": depth_percent / 100.0})); - } - let mut level = app.session.view3d.height_level; - if crate::widgets::slider(ui, tr("Height level (0 = rises out of the surface)"), &mut level, 0.0..=1.0, 2).changed() { - app.run("view.3d", json!({"heightLevel": level})); - } - let mut t = app.session.view3d.tiling; - if crate::widgets::slider(ui, tr("Tiling"), &mut t, 0.25..=8.0, 2).changed() { - app.run("view.3d", json!({"tiling": t})); - } - }); - }); - }); -} - -fn scene(app: &mut MaterialCraftApp, ui: &mut Ui) { - for (i, (id, label)) in SCENES.iter().enumerate() { - if i == 5 { - ui.separator(); - } - if ui.selectable_label(app.session.view3d.scene == *id, tr(label)).clicked() { - app.run("view.3d", json!({"scene": id})); - ui.close(); - } - } - ui.separator(); - if ui.button(tr("Load mesh...")).clicked() { - crate::web_files::load_mesh(app, ui.ctx()); - ui.close(); - } - if app.session.custom_mesh.is_some() && ui.selectable_label(app.session.view3d.scene == "custom", super::scene_label_custom(app)).clicked() { - app.run("view.3d", json!({"scene": "custom"})); - ui.close(); - } - ui.separator(); - if ui.button(tr("Display UVs in 2D View")).clicked() { - app.view2d.show_uvs = !app.view2d.show_uvs; - app.ui.dock.focus(crate::docking::Panel::View2d); - ui.close(); - } - ui.separator(); - if ui.button(tr("Load State File...")).clicked() { - actions::load_state(app, false); - ui.close(); - } - if ui.button(tr("Load State File With Mesh...")).clicked() { - actions::load_state(app, true); - ui.close(); - } - ui.separator(); - if ui.button(tr("Save Current State...")).clicked() { - actions::save_state(app); - ui.close(); - } - if ui.button(tr("Save Current State As Default")).clicked() { - app.ui.view3d_default = app.run("view.3d.state", json!({})); - app.toast(tr("The 3D view opens with this state from now on (Reset Scene restores it)"), false); - ui.close(); - } - ui.separator(); - if ui.button(tr("Reset Scene")).clicked() { - actions::reset_all(app); - ui.close(); - } -} - -/// Materials ▸ Default: the shader and its properties; below it, what each material channel -/// is assigned from (View in 3D view or the graph's output usages) -fn materials(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.menu_button(tr("Default"), |ui| { - if menu_row(ui, icon::GEAR, tr("Edit properties")) { - edit_properties(app, Page3d::Material); - ui.close(); - } - ui.separator(); - let current = app.session.view3d.material.shader; - for (shader, label) in [ - (Shader::Blinn, "Blinn"), - (Shader::Lambert, "Lambert"), - (Shader::MeshInfo, "Mesh Info"), - (Shader::OpenPbr, "OpenPBR [Default]"), - (Shader::MetallicRoughness, "Metallic Roughness"), - (Shader::Coated, "Metallic Roughness - Coated"), - (Shader::Subsurface, "Metallic Roughness - SSS"), - (Shader::SpecularGlossiness, "Specular Glossiness"), - (Shader::Unlit, "Unlit"), - ] { - if ui.selectable_label(current == shader, tr(label)).clicked() { - app.run("view.3d", json!({"material": {"shader": shader.id()}})); - ui.close(); - } - } - ui.separator(); - if ui.button(tr("Reset Common Parameters")).clicked() { - app.run("view.3d", json!({"material": {"common": Common::default(), "useMap": MapUse::default()}})); - ui.close(); - } - if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Material")) { - app.run("view.3d.reset", json!({"what": "material"})); - ui.close(); - } - ui.separator(); - if ui.button(tr("Create graph from texture inputs")).clicked() { - crate::menus::invoke(app, ui.ctx(), "ui.newGraph"); - ui.close(); - } - }); - ui.separator(); - ui.label(RichText::new(tr("Assigned channels")).italics().color(tk.text_dim)); - let sources = app.session.material_preview.sources(&app.session.pkg); - for channel in materialcraft_engine::core::MaterialChannel::ALL { - let label = sources - .get(&channel) - .and_then(|source| { - let graph = app.session.pkg.graphs.get(source.graph)?; - let node = graph.node(source.node).ok()?; - Some(format!("{} / {}", graph.name, crate::graph::node_label(node))) - }) - .unwrap_or_else(|| tr("Unassigned").to_string()); - ui.label(format!("{}: {label}", tr(channel.label()))); - } - ui.separator(); - if ui.button(tr("Clear material assignments")).clicked() { - app.run("view.3d.clear", json!({})); - ui.close(); - } -} - -fn camera(app: &mut MaterialCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - if menu_row(ui, icon::GEAR, tr("Edit properties")) { - edit_properties(app, Page3d::Camera); - ui.close(); - } - if ui.add(egui::Button::new(tr("Frame")).shortcut_text("F")).clicked() { - frame(app); - ui.close(); - } - ui.label(RichText::new(tr("Viewpoint")).italics().color(tk.text_dim)); - for (label, yaw, pitch) in [ - ("Default", 35.0, 25.0), - ("Front", 0.0, 0.0), - ("Right", 90.0, 0.0), - ("Back", 180.0, 0.0), - ("Left", 270.0, 0.0), - ("Top", 0.0, 89.0), - ("Bottom", 0.0, -89.0), - ] { - if ui.button(format!(" {}", tr(label))).clicked() { - app.run("view.3d", json!({"yaw": yaw, "pitch": pitch, "distance": 3.2, "target": [0.0, 0.0, 0.0]})); - ui.close(); - } - } - ui.separator(); - if ui.add(egui::Button::new(format!("{} {}", icon::FLOPPY_DISK, tr("Save Render..."))).shortcut_text("Alt+S")).clicked() { - actions::save_render(app); - ui.close(); - } - if menu_row(ui, icon::CLIPBOARD, tr("Copy Render to Clipboard")) { - actions::copy_render(app, ui.ctx()); - ui.close(); - } - ui.separator(); - if ui.add(egui::Button::new(tr("Reset Position")).shortcut_text("R")).clicked() { - actions::reset_position(app); - ui.close(); - } - if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Camera")) { - app.run("view.3d.reset", json!({"what": "camera"})); - ui.close(); - } -} - -fn environment(app: &mut MaterialCraftApp, ui: &mut Ui) { - if menu_row(ui, icon::GEAR, tr("Edit properties")) { - edit_properties(app, Page3d::Environment); - ui.close(); - } - if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Environment")) { - app.run("view.3d.reset", json!({"what": "environment"})); - ui.close(); - } - ui.separator(); - for (id, label) in ENVIRONMENTS { - if ui.selectable_label(app.session.view3d.environment == *id, tr(label)).clicked() { - app.run("view.3d", json!({"environment": id})); - ui.close(); - } - } - ui.separator(); - let mut rot = app.session.view3d.env_rotation; - if crate::widgets::slider(ui, tr("Rotation"), &mut rot, 0.0..=360.0, 0).changed() { - app.run("view.3d", json!({"envRotation": rot})); - } - let mut exp = app.session.view3d.exposure; - if crate::widgets::slider(ui, tr("Exposure"), &mut exp, -4.0..=4.0, 2).changed() { - app.run("view.3d", json!({"exposure": exp})); - } -} - -fn display(app: &mut MaterialCraftApp, ui: &mut Ui) { - let d = app.session.view3d.display.clone(); - let mut toggles: Vec<(&str, bool)> = Vec::new(); - for (key, label, on) in [ - ("wireframe", "Wireframe", d.wireframe), - ("axis", "Axis", app.session.view3d.show_axis), - ("backfaceCulling", "Backface culling", d.backface_culling), - ("boundingBox", "Bounding box", d.bounding_box), - ("grid", "Grid", app.session.view3d.show_grid), - ("lights", "Light", d.lights), - ] { - if ui.selectable_label(on, tr(label)).clicked() { - toggles.push((key, !on)); - } - } - ui.separator(); - for (key, label, on) in [("resolution", "Resolution", d.resolution), ("stats", "Scene stats", d.stats), ("fps", "FPS", d.fps)] { - if ui.selectable_label(on, tr(label)).clicked() { - toggles.push((key, !on)); - } - } - ui.separator(); - let mut flip = app.session.view3d.normal_y_flip; - if ui.checkbox(&mut flip, tr("Flip normal map Y (DirectX)")).changed() { - app.run("view.3d", json!({"normalYFlip": flip})); - } - ui.checkbox(&mut app.view3d.show_env, tr("Environment background")); - let mut t = app.session.view3d.transparency; - if ui.checkbox(&mut t, tr("Transparency (alpha)")).changed() { - app.run("view.3d", json!({"transparency": t})); - } - let mut a = app.session.view3d.alpha_view; - if ui.checkbox(&mut a, tr("Show alpha channel")).changed() { - app.run("view.3d", json!({"alphaView": a})); - } - ui.separator(); - // A submenu rather than a combo box: a popup inside a menu closes it - let mut size = app.session.preview_size.unwrap_or(0); - ui.menu_button(format!("{}: {}", tr("Preview size"), crate::preview_resolution::label(size)), |ui| { - if crate::preview_resolution::choices(ui, &mut size) { - app.run("view.previewSize", json!({"size": size})); - ui.close(); - } - }); - for (key, on) in toggles { - match key { - "axis" => { - app.run("view.3d", json!({"axis": on})); - } - "grid" => { - app.run("view.3d", json!({"grid": on})); - } - _ => { - app.run("view.3d", json!({"display": {key: on}})); - } - } - } -} diff --git a/crates/ui-egui/src/view3d/overlays.rs b/crates/ui-egui/src/view3d/overlays.rs deleted file mode 100644 index a530046..0000000 --- a/crates/ui-egui/src/view3d/overlays.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Display menu overlays painted over the frame: bounding box, light gizmos, resolution, scene -//! statistics and FPS - -use egui::{Color32, Rect, pos2, vec2}; -use materialcraft_engine::geom::glam::Vec3; - -use super::settings::settings_of; -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -pub(super) fn paint(app: &mut MaterialCraftApp, p: &egui::Painter, rect: Rect) { - let tk = Tokens::get(p.ctx()); - let v = app.session.view3d.clone(); - let d = &v.display; - if d.bounding_box || d.lights { - let (_, scene) = super::base_scene(app); - let settings = settings_of(&v, app.view3d.show_env, 1); - let cam = materialcraft_render::camera(&scene, &settings); - let aspect = rect.width() / rect.height().max(1.0); - let to_screen = |w: Vec3| { - cam.project(w, aspect).map(|ndc| pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height())) - }; - if d.bounding_box { - let (lo, hi) = scene.mesh.bounds(); - let corners: Vec<Vec3> = (0..8) - .map(|i| Vec3::new(if i & 1 == 0 { lo.x } else { hi.x }, if i & 2 == 0 { lo.y } else { hi.y }, if i & 4 == 0 { lo.z } else { hi.z })) - .collect(); - let stroke = egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(0xff, 0xc0, 0x40, 200)); - for (a, b) in [(0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)] { - if let (Some(pa), Some(pb)) = (to_screen(corners[a]), to_screen(corners[b])) { - p.line_segment([pa, pb], stroke); - } - } - } - if d.lights { - for (i, l) in v.lights.point.iter().enumerate() { - let w = scene.center + Vec3::from(l.position) * scene.radius; - if let Some(q) = to_screen(w) { - let c = if l.on { Color32::from_rgb(0xff, 0xe0, 0x60) } else { Color32::from_gray(0x80) }; - p.circle(q, 6.0, c, egui::Stroke::new(1.0, Color32::BLACK)); - p.text(q + vec2(9.0, 0.0), egui::Align2::LEFT_CENTER, format!("{} {}", tr("Light"), i + 1), egui::FontId::proportional(10.5), c); - if let Some(center) = to_screen(scene.center) { - p.line_segment([q, center], egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(0xff, 0xe0, 0x60, 90))); - } - } - } - } - } - let mut lines: Vec<String> = Vec::new(); - if d.resolution { - let (w, h) = app.view3d.shown.as_ref().map_or((0, 0), |(w, h, _)| (*w, *h)); - lines.push(format!("{}: {w} x {h}", tr("Resolution"))); - } - if d.stats { - let (_, scene) = super::base_scene(app); - let tris = app.view3d.displaced.as_ref().map_or(scene.mesh.triangle_count(), |(_, s)| s.mesh.triangle_count()); - let maps = app.session.material_maps().len(); - lines.push(format!("{}: {tris} {}, {maps} {}", tr("Scene"), tr("triangles"), tr("maps"))); - } - if d.fps { - lines.push(format!("{:.0} FPS ({} {})", app.fps, app.view3d.renders, tr("frames"))); - } - for (i, line) in lines.iter().enumerate() { - p.text( - rect.left_bottom() + vec2(8.0, -8.0 - 14.0 * (lines.len() - 1 - i) as f32), - egui::Align2::LEFT_BOTTOM, - line, - egui::FontId::proportional(10.5), - tk.viewport_text, - ); - } -} diff --git a/crates/ui-egui/src/view3d/settings.rs b/crates/ui-egui/src/view3d/settings.rs deleted file mode 100644 index 2f3602b..0000000 --- a/crates/ui-egui/src/view3d/settings.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! The renderer's `Settings` for a 3D view state, and the viewport render scale - -use materialcraft_render::{Background, Settings}; - -use crate::MaterialCraftApp; - -/// The renderer's settings for the view state -pub fn settings_of(v: &materialcraft_engine::View3d, show_env: bool, supersample: u32) -> Settings { - let cam = &v.camera; - let bg = [cam.background_color[0], cam.background_color[1], cam.background_color[2]]; - let background = match cam.background.as_str() { - "color" => Background::Color(bg), - "environment" => Background::Environment, - _ => Background::Backdrop, - }; - let lights = &v.lights; - Settings { - yaw: v.yaw, - pitch: v.pitch, - distance: v.distance, - target: v.target, - tiling: v.tiling * v.material.uv_scale[0].max(0.01), - exposure: v.exposure, - env_rotation: v.env_rotation, - normal_y_flip: v.normal_y_flip, - show_env, - supersample: supersample.min(v.renderer.samples.max(1)), - ao_rays: v.renderer.ao_rays, - transparency: v.transparency, - alpha_view: v.alpha_view, - fov: cam.fov(), - ortho: cam.projection == "orthographic", - background, - clip: if cam.auto_clip { None } else { Some([cam.near, cam.far]) }, - ambient: if lights.ambient_on { lights.ambient } else { [0.0; 3] }, - lights: lights.point, - env_light: v.env_enabled, - shader: v.material.shader, - common: v.material.common, - use_map: v.material.use_map, - wireframe: v.display.wireframe, - backface_culling: v.display.backface_culling, - ..Settings::default() - } -} - -/// The viewport render scale: the session's renderer setting, else the preference (0 = auto = 1) -pub(super) fn view_scale(app: &MaterialCraftApp) -> f32 { - let r = &app.session.view3d.renderer; - if !r.use_viewport_resolution { - return r.scale; - } - let p = app.ui.prefs.viewport_scale; - if p > 0.0 { p.clamp(0.25, 2.0) } else { r.scale.clamp(0.25, 2.0) } -} - -/// The full-quality frame's samples per pixel: the preference, within the renderer's limit -pub(super) fn samples(app: &MaterialCraftApp) -> u32 { - app.ui.prefs.sample_count.clamp(1, 4) -} diff --git a/crates/ui-egui/src/view3d/side_strip.rs b/crates/ui-egui/src/view3d/side_strip.rs deleted file mode 100644 index c35855a..0000000 --- a/crates/ui-egui/src/view3d/side_strip.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! The tool strip down the left of the viewport: framing, property pages and display toggles - -use egui::{Rect, Ui, vec2}; -use egui_phosphor::regular as icon; -use serde_json::json; - -use super::actions::{Page3d, edit_properties, frame}; -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; - -pub(super) const WIDTH: f32 = 28.0; - -pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, strip: Rect) { - let tk = Tokens::get(ui.ctx()); - ui.painter().rect_filled(strip, 0.0, tk.panel); - ui.scope_builder(egui::UiBuilder::new().max_rect(strip.shrink2(vec2(2.0, 4.0))), |ui| { - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.y = 2.0; - let b = |ui: &mut Ui, ic: &str, tip: &str, on: bool| crate::widgets::icon_button(ui, ic, tip, on, 22.0).clicked(); - if b(ui, icon::CORNERS_OUT, tr("Frame (F)"), false) { - frame(app); - } - let page = app.props3d.as_ref().map(|(p, _)| *p); - for (ic, tip, pg) in [ - (icon::VIDEO_CAMERA, "Camera properties", Page3d::Camera), - (icon::LIGHTBULB, "Light properties", Page3d::Lights), - (icon::SUN_HORIZON, "Environment properties", Page3d::Environment), - (icon::SPHERE, "Material properties", Page3d::Material), - (icon::GEAR, "Renderer settings", Page3d::Renderer), - ] { - if b(ui, ic, tr(tip), page == Some(pg)) { - edit_properties(app, pg); - } - } - ui.add_space(6.0); - let v = app.session.view3d.clone(); - let mut set: Option<serde_json::Value> = None; - if b(ui, icon::POLYGON, tr("Wireframe"), v.display.wireframe) { - set = Some(json!({"display": {"wireframe": !v.display.wireframe}})); - } - if b(ui, icon::GRID_FOUR, tr("Grid"), v.show_grid) { - set = Some(json!({"grid": !v.show_grid})); - } - if b(ui, icon::ARROWS_OUT_CARDINAL, tr("Axis"), v.show_axis) { - set = Some(json!({"axis": !v.show_axis})); - } - if b(ui, icon::BOUNDING_BOX, tr("Bounding box"), v.display.bounding_box) { - set = Some(json!({"display": {"boundingBox": !v.display.bounding_box}})); - } - if b(ui, icon::CUBE_TRANSPARENT, tr("Transparency (alpha)"), v.transparency) { - set = Some(json!({"transparency": !v.transparency})); - } - if b(ui, icon::CHECKERBOARD, tr("Show alpha channel"), v.alpha_view) { - set = Some(json!({"alphaView": !v.alpha_view})); - } - if b(ui, icon::IMAGE, tr("Environment background"), app.view3d.show_env) { - app.view3d.show_env = !app.view3d.show_env; - } - if let Some(p) = set { - app.run("view.3d", p); - } - }); - }); -} diff --git a/crates/ui-egui/src/view3d_props.rs b/crates/ui-egui/src/view3d_props.rs deleted file mode 100644 index ba85894..0000000 --- a/crates/ui-egui/src/view3d_props.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! The 3D view's "Edit properties" pages in the Properties panel: camera, lights, environment, -//! renderer and the material's common values. Every change is a `view.3d` command. - -use egui::{RichText, Ui, vec2}; -use materialcraft_engine::View3d; -use serde_json::{Value as J, json}; - -use crate::MaterialCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; -use crate::view3d::Page3d; - -/// The panel title for an open page. -pub fn title(page: Page3d) -> String { - format!("{} - {}", tr(page.title()), tr("Properties")) -} - -/// A section header like the node pages. -fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) { - crate::widgets::section(ui, id, title, true, body); -} - -/// A labelled row: the label on top, the control below. -fn labelled(ui: &mut Ui, label: &str, body: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); - ui.add_space(2.0); - ui.label(RichText::new(label).strong().color(tk.text)); - body(ui); - ui.add_space(2.0); -} - -/// A common-value row: a checkbox (use the map when one exists), the label and "Common". -fn common_label(ui: &mut Ui, label: &str, use_map: Option<&mut bool>) -> bool { - let tk = Tokens::get(ui.ctx()); - let mut changed = false; - ui.horizontal(|ui| { - match use_map { - Some(flag) => { - let r = ui.add(egui::Checkbox::without_text(flag)).on_hover_text(tr("Use the map output when the graph has one (off: the common value below)")); - changed = r.changed(); - } - None => { - ui.add_space(22.0); - } - } - ui.label(RichText::new(label).strong().color(tk.text)); - ui.label(RichText::new(tr("Common")).color(tk.text_dim)); - }); - changed -} - -pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, page: Page3d) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr(page.title())).heading()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.small_button(tr("Back to the graph")).clicked() { - app.props3d = None; - } - }); - }); - ui.label(RichText::new(tr("3D view properties: changes show in the view at once and are kept with the session.")).small().color(tk.text_dim)); - ui.add_space(4.0); - let v = app.session.view3d.clone(); - let patch: Option<J> = match page { - Page3d::Camera => camera(ui, &v), - Page3d::Lights => lights(ui, &v), - Page3d::Environment => environment(app, ui, &v), - Page3d::Renderer => renderer(ui, &v), - Page3d::Material => material(ui, &v), - }; - if let Some(p) = patch { - app.run("view.3d", p); - } -} - -fn camera(ui: &mut Ui, v: &View3d) -> Option<J> { - let mut c = v.camera.clone(); - let mut changed = false; - section(ui, "cam", tr("Camera Component"), |ui| { - labelled(ui, tr("Focal Length (mm)"), |ui| { - changed |= crate::widgets::slider(ui, "", &mut c.focal_length, 4.0..=300.0, 0).changed(); - }); - labelled(ui, tr("Projection"), |ui| { - let label = if c.projection == "orthographic" { tr("Orthographic") } else { tr("Perspective") }; - let r = egui::ComboBox::from_id_salt("cam-proj").width(ui.available_width()).selected_text(label).show_ui(ui, |ui| { - for (id, label) in [("perspective", "Perspective"), ("orthographic", "Orthographic")] { - if ui.selectable_label(c.projection == id, tr(label)).clicked() { - c.projection = id.into(); - changed = true; - } - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Projection"); - }); - labelled(ui, tr("Background Type"), |ui| { - let labels = [("backdrop", "Studio backdrop"), ("color", "Uniform Color"), ("environment", "Environment")]; - let cur = labels.iter().find(|(id, _)| *id == c.background).map_or("Studio backdrop", |(_, l)| l); - let r = egui::ComboBox::from_id_salt("cam-bg").width(ui.available_width()).selected_text(tr(cur)).show_ui(ui, |ui| { - for (id, label) in labels { - if ui.selectable_label(c.background == id, tr(label)).clicked() { - c.background = id.into(); - changed = true; - } - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Background type"); - }); - if c.background == "color" { - labelled(ui, tr("Background Color"), |ui| { - let mut rgb = [c.background_color[0], c.background_color[1], c.background_color[2]]; - let mut a = c.background_color[3]; - if crate::widgets::color_strip(ui, "cam-bg-color", &mut rgb, Some(&mut a)) { - c.background_color = [rgb[0], rgb[1], rgb[2], a]; - changed = true; - } - }); - } - changed |= crate::widgets::bool_button(ui, tr("Override Render Resolution"), &mut c.override_resolution); - ui.add_enabled_ui(c.override_resolution, |ui| { - let mut w = c.resolution[0] as f32; - let mut h = c.resolution[1] as f32; - labelled(ui, tr("Render resolution"), |ui| { - if crate::widgets::slider(ui, tr("Width"), &mut w, 16.0..=8192.0, 0).changed() - | crate::widgets::slider(ui, tr("Height"), &mut h, 16.0..=8192.0, 0).changed() - { - c.resolution = [w as u32, h as u32]; - changed = true; - } - }); - labelled(ui, tr("Render resolution scale"), |ui| { - let r = egui::ComboBox::from_id_salt("cam-scale") - .width(ui.available_width()) - .selected_text(format!("{:.0} %", c.resolution_scale * 100.0)) - .show_ui(ui, |ui| { - for s in [0.25f32, 0.5, 1.0, 1.5, 2.0] { - if ui.selectable_label((c.resolution_scale - s).abs() < 1e-3, format!("{:.0} %", s * 100.0)).clicked() { - c.resolution_scale = s; - changed = true; - } - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Render resolution scale"); - }); - }); - changed |= crate::widgets::bool_button(ui, tr("Automatic Clip Planes"), &mut c.auto_clip); - ui.add_enabled_ui(!c.auto_clip, |ui| { - labelled(ui, tr("Near Clip Plane"), |ui| { - changed |= crate::widgets::slider(ui, "", &mut c.near, 0.001..=20.0, 3).changed(); - }); - labelled(ui, tr("Far Clip Plane"), |ui| { - changed |= crate::widgets::slider(ui, "", &mut c.far, 0.01..=200.0, 2).changed(); - }); - }); - ui.label(RichText::new(tr("Clip distances are in mesh radii from the camera.")).small().color(Tokens::get(ui.ctx()).text_dim)); - }); - changed.then(|| json!({"camera": c})) -} - -fn lights(ui: &mut Ui, v: &View3d) -> Option<J> { - let mut l = v.lights.clone(); - let mut changed = false; - section(ui, "ambient", tr("Ambient Light"), |ui| { - changed |= crate::widgets::bool_button(ui, tr("Created"), &mut l.ambient_on); - ui.add_enabled_ui(l.ambient_on, |ui| { - labelled(ui, tr("Color"), |ui| { - changed |= crate::widgets::color_strip(ui, "ambient-color", &mut l.ambient, None); - }); - }); - }); - for i in 0..2 { - section(ui, &format!("point{i}"), &format!("{} {}", tr("Point Light"), i + 1), |ui| { - let pl = &mut l.point[i]; - changed |= crate::widgets::bool_button(ui, tr("Created"), &mut pl.on); - ui.add_enabled_ui(pl.on, |ui| { - labelled(ui, tr("Color"), |ui| { - changed |= crate::widgets::color_strip(ui, &format!("light{i}-color"), &mut pl.color, None); - }); - labelled(ui, tr("Intensity"), |ui| { - changed |= crate::widgets::slider(ui, "", &mut pl.intensity, 0.0..=20.0, 2).changed(); - }); - labelled(ui, tr("Position (mesh radii from the center)"), |ui| { - for (k, axis) in ["X", "Y", "Z"].iter().enumerate() { - changed |= crate::widgets::slider(ui, axis, &mut pl.position[k], -10.0..=10.0, 2).changed(); - } - }); - }); - }); - } - changed.then(|| json!({"lights": l})) -} - -fn environment(app: &mut MaterialCraftApp, ui: &mut Ui, v: &View3d) -> Option<J> { - let mut patch = serde_json::Map::new(); - let mut enabled = v.env_enabled; - if crate::widgets::bool_button(ui, tr("Enabled"), &mut enabled) { - patch.insert("envEnabled".into(), json!(enabled)); - } - labelled(ui, tr("Exposure"), |ui| { - let mut e = v.exposure; - if crate::widgets::slider(ui, "", &mut e, -4.0..=4.0, 2).changed() { - patch.insert("exposure".into(), json!(e)); - } - }); - labelled(ui, tr("Rotation Angle"), |ui| { - let mut turns = v.env_rotation / 360.0; - let mut degrees = v.env_rotation; - ui.horizontal(|ui| { - // The dial: drag around it to turn the environment. - let (rect, resp) = ui.allocate_exact_size(vec2(56.0, 56.0), egui::Sense::click_and_drag()); - crate::widgets::name(&resp, egui::Role::Slider, "Rotation dial"); - let tk = Tokens::get(ui.ctx()); - let c = rect.center(); - ui.painter().circle(c, 24.0, tk.row, egui::Stroke::new(1.0, tk.field_border)); - let a = v.env_rotation.to_radians(); - ui.painter().line_segment([c, c + vec2(a.cos(), -a.sin()) * 22.0], egui::Stroke::new(2.0, tk.accent)); - if (resp.dragged() || resp.clicked()) - && let Some(p) = resp.interact_pointer_pos() - { - let d = p - c; - let deg = (-d.y).atan2(d.x).to_degrees().rem_euclid(360.0); - patch.insert("envRotation".into(), json!(deg)); - } - ui.vertical(|ui| { - if crate::widgets::slider(ui, tr("Turns"), &mut turns, 0.0..=1.0, 3).changed() { - patch.insert("envRotation".into(), json!(turns * 360.0)); - } - if crate::widgets::slider(ui, tr("Degrees"), &mut degrees, 0.0..=360.0, 1).changed() { - patch.insert("envRotation".into(), json!(degrees)); - } - }); - }); - }); - labelled(ui, tr("Environment"), |ui| { - let cur = materialcraft_engine::view_cmds::ENVIRONMENTS.iter().find(|(id, _)| *id == v.environment).map_or("", |(_, l)| l); - let r = egui::ComboBox::from_id_salt("env-pick").width(ui.available_width()).selected_text(tr(cur)).show_ui(ui, |ui| { - for (id, label) in materialcraft_engine::view_cmds::ENVIRONMENTS { - if ui.selectable_label(v.environment == *id, tr(label)).clicked() { - patch.insert("environment".into(), json!(id)); - } - } - }); - crate::widgets::name(&r.response, egui::Role::ComboBox, "Environment"); - // A strip of the environment: its blurred reflection, as the renderer sees it. - let strip = app.thumbs.environment(ui.ctx(), &v.environment); - let w = ui.available_width(); - let (rect, _) = ui.allocate_exact_size(vec2(w, w * 0.5), egui::Sense::hover()); - match strip { - Some(t) => { - ui.painter().image(t, rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); - } - None => { - ui.painter().rect_filled(rect, 4.0, Tokens::get(ui.ctx()).row); - } - } - let mut show_env = app.view3d.show_env; - if ui.checkbox(&mut show_env, tr("Show the environment behind the mesh")).changed() { - app.view3d.show_env = show_env; - } - }); - (!patch.is_empty()).then_some(J::Object(patch)) -} - -fn renderer(ui: &mut Ui, v: &View3d) -> Option<J> { - let mut r = v.renderer.clone(); - let mut changed = false; - section(ui, "res", tr("Resolution"), |ui| { - changed |= crate::widgets::bool_button(ui, tr("Use viewport resolution"), &mut r.use_viewport_resolution); - ui.add_enabled_ui(!r.use_viewport_resolution, |ui| { - let mut w = r.resolution[0] as f32; - let mut h = r.resolution[1] as f32; - labelled(ui, tr("Render resolution"), |ui| { - if crate::widgets::slider(ui, tr("Width"), &mut w, 16.0..=4096.0, 0).changed() - | crate::widgets::slider(ui, tr("Height"), &mut h, 16.0..=4096.0, 0).changed() - { - r.resolution = [w as u32, h as u32]; - changed = true; - } - }); - }); - labelled(ui, tr("Render resolution scale"), |ui| { - let cb = - egui::ComboBox::from_id_salt("rend-scale").width(ui.available_width()).selected_text(format!("{:.0} %", r.scale * 100.0)).show_ui(ui, |ui| { - for s in [0.25f32, 0.5, 0.75, 1.0, 1.5, 2.0] { - if ui.selectable_label((r.scale - s).abs() < 1e-3, format!("{:.0} %", s * 100.0)).clicked() { - r.scale = s; - changed = true; - } - } - }); - crate::widgets::name(&cb.response, egui::Role::ComboBox, "Render resolution scale"); - }); - }); - section(ui, "quality", tr("Quality"), |ui| { - labelled(ui, tr("Samples per pixel (resting frame)"), |ui| { - let mut s = r.samples as f32; - if crate::widgets::slider(ui, "", &mut s, 1.0..=4.0, 0).changed() { - r.samples = s as u32; - changed = true; - } - ui.label(RichText::new(tr("n × n rays per pixel once the camera rests")).small().color(Tokens::get(ui.ctx()).text_dim)); - }); - labelled(ui, tr("Ambient occlusion rays"), |ui| { - let mut a = r.ao_rays as f32; - if crate::widgets::slider(ui, "", &mut a, 0.0..=32.0, 0).changed() { - r.ao_rays = a as u32; - changed = true; - } - ui.label(RichText::new(tr("Ray-traced occlusion in the relief's crevices (0 = off)")).small().color(Tokens::get(ui.ctx()).text_dim)); - }); - }); - changed.then(|| json!({"renderer": r})) -} - -fn material(ui: &mut Ui, v: &View3d) -> Option<J> { - let tk = Tokens::get(ui.ctx()); - let mut m = v.material.clone(); - let mut changed = false; - let mut extra = serde_json::Map::new(); - ui.label(RichText::new(format!("{} / {}", tr("OpenPBR"), tr("Tessellation + Displacement"))).color(tk.text_dim)); - let weight = |ui: &mut Ui, id: &str, label: &str, value: &mut f32, use_map: Option<&mut bool>, changed: &mut bool| { - *changed |= common_label(ui, label, use_map); - *changed |= crate::widgets::gray_strip(ui, id, value); - }; - let color = |ui: &mut Ui, id: &str, label: &str, value: &mut [f32; 3], use_map: Option<&mut bool>, changed: &mut bool| { - *changed |= common_label(ui, label, use_map); - *changed |= crate::widgets::color_strip(ui, id, value, None); - }; - let scalar = |ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, changed: &mut bool| { - common_label(ui, label, None); - *changed |= crate::widgets::slider(ui, "", value, range, 2).changed(); - }; - section(ui, "uvs", tr("UVs"), |ui| { - labelled(ui, tr("Tiling"), |ui| { - let mut t = v.tiling; - if crate::widgets::slider(ui, "", &mut t, 0.25..=16.0, 2).changed() { - extra.insert("tiling".into(), json!(t)); - } - }); - labelled(ui, tr("UV scale"), |ui| { - changed |= crate::widgets::slider(ui, "U", &mut m.uv_scale[0], 0.1..=8.0, 2).changed(); - changed |= crate::widgets::slider(ui, "V", &mut m.uv_scale[1], 0.1..=8.0, 2).changed(); - }); - }); - let c = &mut m.common; - let u = &mut m.use_map; - section(ui, "base", tr("Base"), |ui| { - weight(ui, "base-weight", tr("Weight"), &mut c.base_weight, None, &mut changed); - color(ui, "base-color", tr("Color"), &mut c.base_color, Some(&mut u.base_color), &mut changed); - weight(ui, "metalness", tr("Metalness"), &mut c.metalness, Some(&mut u.metallic), &mut changed); - weight(ui, "diffuse-rough", tr("Diffuse roughness"), &mut c.diffuse_roughness, None, &mut changed); - }); - section(ui, "specular", tr("Specular"), |ui| { - weight(ui, "spec-weight", tr("Weight"), &mut c.specular_weight, Some(&mut u.specular), &mut changed); - color(ui, "spec-color", tr("Color"), &mut c.specular_color, None, &mut changed); - weight(ui, "spec-rough", tr("Roughness"), &mut c.specular_roughness, Some(&mut u.roughness), &mut changed); - scalar(ui, tr("IOR"), &mut c.ior, 1.0..=3.0, &mut changed); - }); - section(ui, "transmission", tr("Transmission"), |ui| { - weight(ui, "trans-weight", tr("Weight"), &mut c.transmission_weight, None, &mut changed); - color(ui, "trans-color", tr("Color"), &mut c.transmission_color, None, &mut changed); - }); - section(ui, "subsurface", tr("Subsurface"), |ui| { - weight(ui, "sss-weight", tr("Weight"), &mut c.subsurface_weight, None, &mut changed); - color(ui, "sss-color", tr("Color"), &mut c.subsurface_color, None, &mut changed); - }); - section(ui, "coat", tr("Coat"), |ui| { - weight(ui, "coat-weight", tr("Weight"), &mut c.coat_weight, None, &mut changed); - color(ui, "coat-color", tr("Color"), &mut c.coat_color, None, &mut changed); - weight(ui, "coat-rough", tr("Roughness"), &mut c.coat_roughness, None, &mut changed); - scalar(ui, tr("IOR"), &mut c.coat_ior, 1.0..=3.0, &mut changed); - weight(ui, "coat-dark", tr("Darkening"), &mut c.coat_darkening, None, &mut changed); - }); - section(ui, "fuzz", tr("Fuzz"), |ui| { - weight(ui, "fuzz-weight", tr("Weight"), &mut c.fuzz_weight, None, &mut changed); - color(ui, "fuzz-color", tr("Color"), &mut c.fuzz_color, None, &mut changed); - }); - section(ui, "emission", tr("Emission"), |ui| { - common_label(ui, tr("Luminance"), Some(&mut u.emissive)); - changed |= crate::widgets::slider(ui, "", &mut c.emission_luminance, 0.0..=10.0, 2).changed(); - color(ui, "emit-color", tr("Color"), &mut c.emission_color, None, &mut changed); - }); - section(ui, "thinfilm", tr("Thin-film"), |ui| { - weight(ui, "film-weight", tr("Weight"), &mut c.thin_film_weight, None, &mut changed); - common_label(ui, tr("Thickness (nm)"), None); - changed |= crate::widgets::slider(ui, "", &mut c.thin_film_thickness, 0.0..=2000.0, 0).changed(); - scalar(ui, tr("IOR"), &mut c.thin_film_ior, 1.0..=3.0, &mut changed); - }); - section(ui, "geometry", tr("Geometry"), |ui| { - weight(ui, "opacity", tr("Opacity"), &mut c.opacity, Some(&mut u.opacity), &mut changed); - common_label(ui, tr("Thin walled"), None); - let mut tw = c.thin_walled; - if crate::widgets::bool_button(ui, "", &mut tw) { - c.thin_walled = tw; - changed = true; - } - common_label(ui, tr("DirectX normal"), Some(&mut u.normal)); - let mut flip = v.normal_y_flip; - if crate::widgets::bool_button(ui, "", &mut flip) { - extra.insert("normalYFlip".into(), json!(flip)); - } - weight(ui, "ao", tr("Ambient occlusion"), &mut c.ambient_occlusion, Some(&mut u.ao), &mut changed); - }); - section(ui, "height", tr("Height"), |ui| { - weight(ui, "height", tr("Height"), &mut c.height, Some(&mut u.height), &mut changed); - common_label(ui, tr("Height scale"), None); - let mut hs = v.height_scale * 100.0; - if crate::widgets::slider(ui, "", &mut hs, 0.0..=50.0, 1).changed() { - extra.insert("heightScale".into(), json!(hs / 100.0)); - } - ui.label(RichText::new(tr("% of the mesh size")).small().color(tk.text_dim)); - common_label(ui, tr("Height level"), None); - let mut hl = v.height_level; - if crate::widgets::slider(ui, "", &mut hl, 0.0..=1.0, 2).changed() { - extra.insert("heightLevel".into(), json!(hl)); - } - common_label(ui, tr("Tessellation factor"), None); - changed |= crate::widgets::slider(ui, "", &mut m.tessellation, 0.1..=4.0, 2).changed(); - ui.label(RichText::new(tr("Multiplies the displaced mesh's triangle budget")).small().color(tk.text_dim)); - }); - if changed { - extra.insert("material".into(), json!(m)); - } - (!extra.is_empty()).then_some(J::Object(extra)) -} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 283b9d5..0704943 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -68,8 +68,10 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI let t = ((x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); f64::from(lo) + (f64::from(hi) - f64::from(lo)) * f64::from(t) }; - // Use the same round-value aiming as egui's standard sliders, within one physical pixel. - let radius = ui.input(|i| i.aim_radius()); + // Snap to a round value only within half a physical pixel (in points), so + // round values are reachable by aiming at them while fractional values + // between round steps remain reachable. + let radius = 0.5 / ui.ctx().pixels_per_point(); let v = egui::emath::smart_aim::best_in_range_f64(value_at(p.x - radius), value_at(p.x + radius)) as f32; if (v - *value).abs() > f32::EPSILON { *value = v; @@ -91,8 +93,15 @@ pub fn bar_slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Ra if (resp.dragged() || resp.clicked()) && let Some(p) = resp.interact_pointer_pos() { - let t = ((p.x - rect.left() - 4.0) / (rect.width() - 8.0).max(1.0)).clamp(0.0, 1.0); - let v = lo + (hi - lo) * t; + let value_at = |x: f32| { + let t = ((x - rect.left() - 4.0) / (rect.width() - 8.0).max(1.0)).clamp(0.0, 1.0); + f64::from(lo) + (f64::from(hi) - f64::from(lo)) * f64::from(t) + }; + // Snap to a round value only within half a physical pixel (in points), so + // round values are reachable by aiming at them while fractional values + // between round steps remain reachable. + let radius = 0.5 / ui.ctx().pixels_per_point(); + let v = egui::emath::smart_aim::best_in_range_f64(value_at(p.x - radius), value_at(p.x + radius)) as f32; if (v - *value).abs() > f32::EPSILON { *value = v; resp.mark_changed(); @@ -242,186 +251,3 @@ pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), trailing); }); } - -/// How the colour strip's channel sliders read: sRGB 0..255, linear floats or HSV. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum ColorMode { - #[default] - Srgb, - Float, - Hsv, -} - -/// A colour row as the 3D view's property pages show it: a swatch (click opens the picker), a -/// hue strip (click or drag sets the hue), then sRGB / Float / HSV sliders for the channels. -/// `linear` is linear RGB; `alpha` adds a fourth slider. Returns true when the colour changed. -pub fn color_strip(ui: &mut Ui, id: &str, linear: &mut [f32; 3], alpha: Option<&mut f32>) -> bool { - let tk = Tokens::get(ui.ctx()); - let mode_id = ui.make_persistent_id((id, "color-mode")); - let mut mode: ColorMode = ui.data(|d| d.get_temp(mode_id)).unwrap_or_default(); - let mut changed = false; - ui.horizontal(|ui| { - changed |= color_swatch(ui, id, linear, 22.0); - // Hue strip. - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(60.0), 18.0), Sense::click_and_drag()); - name(&resp, egui::Role::Slider, "Hue"); - let steps = 24; - for i in 0..steps { - let (a, b) = (i as f32 / steps as f32, (i + 1) as f32 / steps as f32); - let r = egui::Rect::from_min_max( - egui::pos2(rect.left() + rect.width() * a, rect.top()), - egui::pos2(rect.left() + rect.width() * b + 0.5, rect.bottom()), - ); - let c = egui::ecolor::Hsva::new(a + 0.5 / steps as f32, 1.0, 1.0, 1.0); - ui.painter().rect_filled(r, 0.0, Color32::from(c)); - } - ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let srgb = linear.map(materialcraft_engine::image::linear_to_srgb); - let mut hsv = egui::ecolor::Hsva::from_rgb(srgb); - let hx = rect.left() + rect.width() * hsv.h; - ui.painter().line_segment([egui::pos2(hx, rect.top()), egui::pos2(hx, rect.bottom())], Stroke::new(2.0, Color32::WHITE)); - if (resp.clicked() || resp.dragged()) - && let Some(p) = resp.interact_pointer_pos() - { - hsv.h = ((p.x - rect.left()) / rect.width().max(1.0)).clamp(0.0, 1.0); - if hsv.s <= 0.0 { - hsv.s = 1.0; - } - if hsv.v <= 0.0 { - hsv.v = 1.0; - } - let rgb = hsv.to_rgb(); - *linear = rgb.map(materialcraft_engine::image::srgb_to_linear); - changed = true; - } - }); - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - for (m, label) in [(ColorMode::Srgb, "sRGB"), (ColorMode::Float, "Float"), (ColorMode::Hsv, "HSV")] { - if ui.add(egui::Button::new(label).selected(mode == m).min_size(vec2(46.0, 18.0))).clicked() { - mode = m; - } - } - }); - ui.vertical(|ui| { - let srgb = linear.map(materialcraft_engine::image::linear_to_srgb); - match mode { - ColorMode::Srgb => { - let mut v = srgb.map(|c| (c * 255.0).round()); - let mut dirty = false; - for (i, ch) in ["R", "G", "B"].iter().enumerate() { - dirty |= slider(ui, ch, &mut v[i], 0.0..=255.0, 0).changed(); - } - if dirty { - *linear = v.map(|c| materialcraft_engine::image::srgb_to_linear(c / 255.0)); - changed = true; - } - } - ColorMode::Float => { - let mut dirty = false; - for (i, ch) in ["R", "G", "B"].iter().enumerate() { - dirty |= slider(ui, ch, &mut linear[i], 0.0..=1.0, 3).changed(); - } - changed |= dirty; - } - ColorMode::Hsv => { - let hsv = egui::ecolor::Hsva::from_rgb(srgb); - let mut v = [hsv.h * 360.0, hsv.s * 100.0, hsv.v * 100.0]; - let mut dirty = false; - dirty |= slider(ui, "H", &mut v[0], 0.0..=360.0, 0).changed(); - dirty |= slider(ui, "S", &mut v[1], 0.0..=100.0, 0).changed(); - dirty |= slider(ui, "V", &mut v[2], 0.0..=100.0, 0).changed(); - if dirty { - let rgb = egui::ecolor::Hsva::new(v[0] / 360.0, v[1] / 100.0, v[2] / 100.0, 1.0).to_rgb(); - *linear = rgb.map(materialcraft_engine::image::srgb_to_linear); - changed = true; - } - } - } - if let Some(a) = alpha { - let mut v = if mode == ColorMode::Float { *a } else { (*a * 255.0).round() }; - let (hi, dec) = if mode == ColorMode::Float { (1.0, 3) } else { (255.0, 0) }; - if slider(ui, "A", &mut v, 0.0..=hi, dec).changed() { - *a = if mode == ColorMode::Float { v } else { v / 255.0 }; - changed = true; - } - } - }); - }); - ui.data_mut(|d| d.insert_temp(mode_id, mode)); - changed -} - -/// A grey value row like [`color_strip`]: swatch, black-to-white strip and an "L" slider -/// (sRGB 0..255 or float). `value` is linear 0..1. Returns true when it changed. -pub fn gray_strip(ui: &mut Ui, id: &str, value: &mut f32) -> bool { - let tk = Tokens::get(ui.ctx()); - let mode_id = ui.make_persistent_id((id, "gray-mode")); - let mut float_mode: bool = ui.data(|d| d.get_temp(mode_id)).unwrap_or(false); - let mut changed = false; - ui.horizontal(|ui| { - let mut rgb = [*value; 3]; - if color_swatch(ui, id, &mut rgb, 22.0) { - *value = (rgb[0] + rgb[1] + rgb[2]) / 3.0; - changed = true; - } - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(60.0), 18.0), Sense::click_and_drag()); - name(&resp, egui::Role::Slider, "Value"); - let steps = 16; - for i in 0..steps { - let (a, b) = (i as f32 / steps as f32, (i + 1) as f32 / steps as f32); - let r = egui::Rect::from_min_max( - egui::pos2(rect.left() + rect.width() * a, rect.top()), - egui::pos2(rect.left() + rect.width() * b + 0.5, rect.bottom()), - ); - let g = (materialcraft_engine::image::linear_to_srgb(a + 0.5 / steps as f32) * 255.0) as u8; - ui.painter().rect_filled(r, 0.0, Color32::from_gray(g)); - } - ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let x = rect.left() + rect.width() * value.clamp(0.0, 1.0); - ui.painter().line_segment([egui::pos2(x, rect.top()), egui::pos2(x, rect.bottom())], Stroke::new(2.0, tk.accent)); - if (resp.clicked() || resp.dragged()) - && let Some(p) = resp.interact_pointer_pos() - { - *value = ((p.x - rect.left()) / rect.width().max(1.0)).clamp(0.0, 1.0); - changed = true; - } - }); - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - if ui.add(egui::Button::new("sRGB").selected(!float_mode).min_size(vec2(46.0, 18.0))).clicked() { - float_mode = false; - } - if ui.add(egui::Button::new("Float").selected(float_mode).min_size(vec2(46.0, 18.0))).clicked() { - float_mode = true; - } - }); - ui.vertical(|ui| { - if float_mode { - changed |= slider(ui, "L", value, 0.0..=1.0, 3).changed(); - } else { - let mut v = (materialcraft_engine::image::linear_to_srgb(*value) * 255.0).round(); - if slider(ui, "L", &mut v, 0.0..=255.0, 0).changed() { - *value = materialcraft_engine::image::srgb_to_linear(v / 255.0); - changed = true; - } - } - }); - }); - ui.data_mut(|d| d.insert_temp(mode_id, float_mode)); - changed -} - -/// A two-state "True / False" button like the 3D view property pages. Returns true when toggled. -pub fn bool_button(ui: &mut Ui, label: &str, value: &mut bool) -> bool { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(label).color(tk.text)); - let text = if *value { "True" } else { "False" }; - let r = ui.add(egui::Button::new(text).min_size(vec2(ui.available_width().max(60.0), 20.0))); - name(&r, egui::Role::CheckBox, label); - if r.clicked() { - *value = !*value; - return true; - } - false -} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 7d47fc3..d9d44c4 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,9 +1,6 @@ //! Dialogs (new graph, export outputs, preferences, shortcuts, about, home), the console and history panels, file actions behind the File menu, and the function editor -use std::collections::HashMap; -use std::sync::mpsc::Receiver; - -use egui::{Color32, RichText, TextureHandle, Ui, vec2}; +use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as icon; use materialcraft_engine::core::FunctionGraph; use materialcraft_engine::core::NodeId; @@ -14,65 +11,11 @@ use crate::MaterialCraftApp; use crate::i18n::tr; use crate::theme::Tokens; -/// Template previews for the New graph dialog (rendered in the background on first open) -#[derive(Default)] -pub struct TemplatePreviews { - tex: HashMap<String, TextureHandle>, - rx: Option<Receiver<crate::thumbs::Previews>>, - started: bool, -} +mod template_previews; +pub(crate) use template_previews::TemplatePreviews; -const PREVIEW: u32 = 96; - -fn render_templates() -> crate::thumbs::Previews { - let light = materialcraft_render::Lighting::new("studio"); - let scene = materialcraft_render::Scene::builtin("sphere"); - let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() }; - materialcraft_engine::samples::TEMPLATES - .iter() - .filter_map(|(id, _)| { - let mut s = materialcraft_engine::Session::new(materialcraft_engine::core::Package::new("t")); - s.pkg.graphs.push(materialcraft_engine::samples::template(id, "t", 8).ok()?); - s.preview_size = Some(256); - s.cook(); - let maps = materialcraft_render::Maps::from_usages(s.material_maps()); - Some((id.to_string(), materialcraft_render::render(&scene, &maps, &light, &settings, PREVIEW, PREVIEW))) - }) - .collect() -} - -impl TemplatePreviews { - fn get(&mut self, ctx: &egui::Context, id: &str) -> Option<egui::TextureId> { - if !self.started { - self.started = true; - let (tx, rx) = std::sync::mpsc::channel(); - #[cfg(not(target_arch = "wasm32"))] - { - let c = ctx.clone(); - let _ = std::thread::Builder::new().name("materialcraft-templates".into()).spawn(move || { - let _ = tx.send(render_templates()); - c.request_repaint(); - }); - } - #[cfg(target_arch = "wasm32")] - let _ = tx.send(render_templates()); - self.rx = Some(rx); - } - if let Some(rx) = &self.rx - && let Ok(list) = rx.try_recv() - { - for (k, px) in list { - let img = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &px); - self.tex.insert(k.clone(), ctx.load_texture(format!("tpl-{k}"), img, egui::TextureOptions::LINEAR)); - } - self.rx = None; - } - self.tex.get(id).map(TextureHandle::id) - } -} - -thread_local! { - static TEMPLATES: std::cell::RefCell<TemplatePreviews> = std::cell::RefCell::new(TemplatePreviews::default()); +pub(crate) fn template_preview(app: &mut MaterialCraftApp, context: &egui::Context, template: &str) -> Option<egui::TextureId> { + app.template_previews.get(context, template) } pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { @@ -95,26 +38,9 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { if app.ui.windows.home { home(app, ctx); } - if app.ui.windows.switch_engine { - crate::tool_windows::switch_engine(app, ctx); - } - if app.ui.windows.dependencies { - crate::tool_windows::dependencies(app, ctx); - } - if app.ui.windows.plugin_manager { - crate::plugins::window(app, ctx); - } - if app.import_pick.is_some() { - crate::tool_windows::import_pick(app, ctx); - } crate::unsaved::show(app, ctx); } -/// The rendered preview of a starter template (made once, in the background) -pub(crate) fn template_preview(ctx: &egui::Context, id: &str) -> Option<egui::TextureId> { - TEMPLATES.with(|t| t.borrow_mut().get(ctx, id)) -} - pub(crate) fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) { egui::Window::new(title) .id(egui::Id::unique(id)) @@ -227,9 +153,8 @@ fn about(app: &mut MaterialCraftApp, ctx: &egui::Context) { ui.label(tr("Node-based procedural materials, built in pure Rust.")); ui.label(tr("An open-source Crafting App by the ArtCraft team and community.")); ui.add_space(6.0); - ui.hyperlink_to("getartcraft.com/apps/materialcraft", crate::menus::WEBSITE); - ui.hyperlink_to("discord.gg/artcraft", crate::menus::DISCORD); - ui.hyperlink_to("github.com/storytold/materialcraft", "https://github.com/storytold/materialcraft"); + ui.hyperlink_to("getartcraft.com/apps/materialcraft", "https://getartcraft.com/apps/materialcraft"); + ui.hyperlink_to("discord.gg/artcraft", "https://discord.gg/artcraft"); ui.add_space(6.0); ui.label(RichText::new("MIT OR Apache-2.0").size(11.0).color(tk.text_dim)); }); @@ -273,7 +198,7 @@ fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) { let mut open = true; - let mut create: Option<(String, String, Option<String>)> = None; + let mut create: Option<(&str, &str)> = None; modal(ctx, "home", tr("Home"), &mut open, vec2(760.0, 470.0), |ui| { let tk = Tokens::get(ui.ctx()); ui.horizontal_top(|ui| { @@ -290,10 +215,9 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) { crate::menus::invoke(app, ui.ctx(), "file.open"); } ui.add_space(16.0); - ui.hyperlink_to(tr("Tutorials"), "https://getartcraft.com/tutorials"); - ui.hyperlink_to(tr("Support"), "https://getartcraft.com/support"); - ui.hyperlink_to(tr("Community (Discord)"), crate::menus::DISCORD); - ui.hyperlink_to("getartcraft.com", crate::menus::WEBSITE); + ui.hyperlink_to(tr("Documentation"), "https://github.com/storytold/materialcraft#readme"); + ui.hyperlink_to(tr("Community (Discord)"), "https://discord.gg/artcraft"); + ui.hyperlink_to("getartcraft.com", "https://getartcraft.com/apps/materialcraft"); ui.add_space(16.0); ui.checkbox(&mut app.ui.prefs.show_home, tr("Show at startup")); }); @@ -308,43 +232,29 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) { ); ui.add_space(8.0); ui.label(RichText::new(tr("Samples")).strong()); - // The starter templates, then the graphs of loaded library packages - let mut samples: Vec<(String, String, Option<String>)> = materialcraft_engine::samples::TEMPLATES - .iter() - .filter(|(id, _)| !matches!(*id, "empty" | "pbr")) - .map(|(id, l)| (id.to_string(), l.to_string(), None)) - .collect(); - for (_, package, graph, _) in app.plugin_graphs().into_iter().take(12) { - samples.push((graph.clone(), graph, Some(package))); - } ui.horizontal_wrapped(|ui| { - for (id, label, package) in &samples { + for (id, label) in materialcraft_engine::samples::TEMPLATES.iter().filter(|(id, _)| !matches!(*id, "empty" | "pbr")) { let (r, resp) = ui.allocate_exact_size(vec2(92.0, 116.0), egui::Sense::click()); crate::widgets::name(&resp, egui::Role::ListItem, label); if resp.hovered() { ui.painter().rect_filled(r, 6.0, tk.row_hover); } let img = egui::Rect::from_min_size(r.min + vec2(6.0, 4.0), vec2(80.0, 80.0)); - let preview = if package.is_some() { None } else { TEMPLATES.with(|t| t.borrow_mut().get(ui.ctx(), id)) }; - match preview { + match template_preview(app, ui.ctx(), id) { Some(t) => { ui.painter().image(t, img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { ui.painter().circle_filled(img.center(), 36.0, tk.row); - ui.painter().text(img.center(), egui::Align2::CENTER_CENTER, icon::PUZZLE_PIECE, egui::FontId::proportional(28.0), tk.text_dim); } } let g = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tk.text, 90.0); ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text); if resp.clicked() { - create = Some((id.clone(), label.clone(), package.clone())); + create = Some((id, label)); } } }); - if samples.len() <= 1 { - ui.label(RichText::new(tr("Library packages added in Tools > Plugin Manager show their graphs here")).small().color(tk.text_dim)); - } ui.add_space(8.0); ui.label(RichText::new(tr("Recent")).strong()); if app.ui.recent.is_empty() { @@ -360,12 +270,8 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) { }); }); }); - if let Some((id, label, package)) = create { - let made = match package { - Some(package) => app.run("file.importGraph", json!({"path": package, "graph": id})), - None => app.run("file.new", json!({"template": id, "name": label.replace(' ', "_"), "size": 1024})), - }; - if made.is_some() { + if let Some((id, label)) = create { + if app.run("file.new", json!({"template": id, "name": label.replace(' ', "_"), "size": 1024})).is_some() { app.ui.frame_all = true; } open = false; @@ -457,35 +363,6 @@ pub fn after_open(app: &mut MaterialCraftApp) { } } -/// Where a file dialog opens (Preferences ▸ Save/Export Path): the last folder used, the -/// package's folder, or a fixed one -#[cfg(not(target_arch = "wasm32"))] -pub fn dialog_dir(app: &MaterialCraftApp) -> Option<std::path::PathBuf> { - let p = &app.ui.prefs; - let dir = match p.save_path_mode.as_str() { - "package" => app.session.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(|p| p.to_path_buf()), - "custom" if !p.save_path.trim().is_empty() => Some(std::path::PathBuf::from(p.save_path.trim())), - _ => (!app.ui.last_dir.is_empty()).then(|| std::path::PathBuf::from(&app.ui.last_dir)), - }; - dir.filter(|d| d.is_dir()) -} - -/// A file dialog opening in the preferred folder -#[cfg(not(target_arch = "wasm32"))] -pub fn dialog(app: &MaterialCraftApp) -> rfd::FileDialog { - match dialog_dir(app) { - Some(d) => rfd::FileDialog::new().set_directory(d), - None => rfd::FileDialog::new(), - } -} - -/// Remember the folder of a path a dialog gave (Save/Export Path: Last path) -pub fn remember_dir(app: &mut MaterialCraftApp, path: &std::path::Path) { - if let Some(d) = path.parent().filter(|d| !d.as_os_str().is_empty()) { - app.ui.last_dir = d.display().to_string(); - } -} - /// File menu actions that need a file dialog. Returns true when handled pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] @@ -494,8 +371,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> { match id { "file.open" => { - if let Some(p) = dialog(app).add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() { - remember_dir(app, &p); + if let Some(p) = rfd::FileDialog::new().add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() { open_path(app, &p.display().to_string()); } true @@ -510,8 +386,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } "file.save" | "file.saveAs" => { let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); - if let Some(p) = dialog(app).set_file_name(name).add_filter("SBS package", &["sbs"]).save_file() { - remember_dir(app, &p); + if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("SBS package", &["sbs"]).save_file() { let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string()); if app.run("file.save", json!({"path": path})).is_some() { app.ui.add_recent(&path); @@ -539,65 +414,11 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> true } "file.importBitmap" => { - if let Some(path) = dialog(app).add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() { - remember_dir(app, &path); + if let Some(path) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() { crate::graph::import_bitmap_file(app, &path.display().to_string()); } true } - "file.linkBitmap" => { - if let Some(p) = dialog(app).add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() { - remember_dir(app, &p); - if let Some(r) = app.run("file.linkBitmap", json!({"path": p.display().to_string()})) { - let name = r["name"].as_str().unwrap_or_default().to_string(); - crate::graph::add_node_near_selection(app, "bitmap"); - if let Some(id) = app.session.selection.last().copied() { - app.run("graph.node.param", json!({"id": id.0, "param": "resource", "value": name})); - } - app.toast(format!("{} {}", tr("Linked bitmap"), r["name"].as_str().unwrap_or_default()), false); - } - } - true - } - "file.saveCopy" => { - let name = format!("{}_copy.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); - if let Some(p) = dialog(app).set_file_name(name).add_filter("SBS package", &["sbs"]).save_file() { - remember_dir(app, &p); - if let Some(r) = app.run("file.saveCopy", json!({"path": p.display().to_string()})) { - app.toast(format!("{} {}", tr("Saved a copy to"), r["path"].as_str().unwrap_or_default()), false); - } - } - true - } - "file.exportWithDependencies" => { - if let Some(dir) = dialog(app).set_title(tr("Folder for the package and its dependencies")).pick_folder() - && let Some(r) = app.run("file.exportWithDependencies", json!({"dir": dir.display().to_string()})) - { - let n = r["files"].as_array().map_or(0, Vec::len); - app.toast(format!("{} {n} {} {}", tr("Exported"), tr("file(s) to"), dir.display()), false); - } - true - } - "file.importGraph" => { - if let Some(p) = dialog(app).add_filter("Packages", &["sbs"]).pick_file() { - remember_dir(app, &p); - let path = p.display().to_string(); - // Several graphs: the picker window asks which; one graph imports at once - match app.run("file.packageGraphs", json!({"path": path})) { - Some(list) if list.as_array().is_some_and(|a| a.len() > 1) => { - let names = list.as_array().cloned().unwrap_or_default().iter().filter_map(|g| g["name"].as_str().map(str::to_string)).collect(); - app.import_pick = Some((path, names)); - } - Some(_) => { - if let Some(r) = app.run("file.importGraph", json!({"path": path})) { - app.toast(format!("{} {}", tr("Imported graph"), r["name"].as_str().unwrap_or_default()), false); - } - } - None => {} - } - } - true - } _ => false, } } diff --git a/crates/ui-egui/src/windows/template_previews.rs b/crates/ui-egui/src/windows/template_previews.rs new file mode 100644 index 0000000..da06630 --- /dev/null +++ b/crates/ui-egui/src/windows/template_previews.rs @@ -0,0 +1,61 @@ +use std::{collections::HashMap, sync::mpsc::Receiver}; + +use egui::TextureHandle; + +/// Procedural template thumbnails owned by one app and its texture manager +#[derive(Default)] +pub struct TemplatePreviews { + textures: HashMap<String, TextureHandle>, + receiver: Option<Receiver<crate::thumbs::Previews>>, + started: bool, +} + +const PREVIEW_PIXELS: u32 = 96; + +fn render_templates() -> crate::thumbs::Previews { + let lighting = materialcraft_render::Lighting::new("studio"); + let scene = materialcraft_render::Scene::builtin("sphere"); + let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() }; + materialcraft_engine::samples::TEMPLATES + .iter() + .filter_map(|(identifier, _)| { + let mut package = materialcraft_engine::core::Package::new("Template preview"); + package.graphs.push(materialcraft_engine::samples::template(identifier, "Template preview", 8).ok()?); + let mut session = materialcraft_engine::Session::new(package); + session.preview_size = Some(256); + session.cook(); + let maps = materialcraft_render::Maps::from_usages(session.material_maps()); + Some((identifier.to_string(), materialcraft_render::render(&scene, &maps, &lighting, &settings, PREVIEW_PIXELS, PREVIEW_PIXELS))) + }) + .collect() +} + +impl TemplatePreviews { + pub(super) fn get(&mut self, context: &egui::Context, identifier: &str) -> Option<egui::TextureId> { + if !self.started { + self.started = true; + let (sender, receiver) = std::sync::mpsc::channel(); + #[cfg(not(target_arch = "wasm32"))] + { + let context = context.clone(); + let _ = std::thread::Builder::new().name("materialcraft-templates".into()).spawn(move || { + let _ = sender.send(render_templates()); + context.request_repaint(); + }); + } + #[cfg(target_arch = "wasm32")] + let _ = sender.send(render_templates()); + self.receiver = Some(receiver); + } + if let Some(receiver) = &self.receiver + && let Ok(previews) = receiver.try_recv() + { + for (identifier, pixels) in previews { + let image = egui::ColorImage::from_rgba_unmultiplied([PREVIEW_PIXELS as usize, PREVIEW_PIXELS as usize], &pixels); + self.textures.insert(identifier.clone(), context.load_texture(format!("tpl-{identifier}"), image, egui::TextureOptions::LINEAR)); + } + self.receiver = None; + } + self.textures.get(identifier).map(TextureHandle::id) + } +} diff --git a/crates/ui-egui/tests/dialog_transplant.rs b/crates/ui-egui/tests/dialog_transplant.rs new file mode 100644 index 0000000..18d5be3 --- /dev/null +++ b/crates/ui-egui/tests/dialog_transplant.rs @@ -0,0 +1,100 @@ +use egui::vec2; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +fn harness(preferences: bool) -> Harness<'static, MaterialCraftApp> { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = 64; + app.ui.windows.preferences = preferences; + app.ui.windows.new_graph = !preferences; + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + harness.run_steps(8); + harness +} + +fn choose_size(harness: &mut Harness<'static, MaterialCraftApp>, axis: &str, size: &str) { + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label(axis)).click(); + harness.run_steps(2); + harness.get_by_label(size).click(); + harness.run_steps(2); +} + +#[test] +fn template_selection_preserves_the_name_and_rectangular_creation_is_one_undo() { + let mut harness = harness(false); + let original = harness.state().session.pkg.clone(); + harness.state_mut().ui.new_graph_name = "My material".into(); + harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Atomic sample")).click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.new_graph_name, "My material"); + choose_size(&mut harness, "Width", "512 px"); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Link width and height")).click(); + harness.run_steps(2); + choose_size(&mut harness, "Height", "128 px"); + harness.get_by_label("Create").click(); + harness.run_steps(3); + assert!(!harness.state().ui.windows.new_graph); + assert_eq!(harness.state().session.graph().unwrap().size_px(), [512, 128]); + assert_eq!(harness.state().session.graph().unwrap().name, "My material"); + assert!(harness.state().session.graph().unwrap().nodes.iter().any(|node| node.def == "fx_map")); + harness.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(harness.state().session.pkg, original); +} + +#[test] +fn relinking_dimensions_creates_a_square_and_function_creation_keeps_main_behavior() { + let mut harness = harness(false); + choose_size(&mut harness, "Width", "256 px"); + harness.get_by_label("Link width and height").click(); + harness.run_steps(2); + choose_size(&mut harness, "Height", "64 px"); + harness.get_by_label("Link width and height").click(); + harness.run_steps(2); + harness.get_by_label("Create").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.graph().unwrap().size_px(), [256, 256]); + + harness.state_mut().ui.windows.new_graph = true; + harness.run_steps(3); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Function Graph")).click(); + harness.run_steps(3); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::ComboBox).label("Width")).next().is_none()); + harness.get_by_label("Create").click(); + harness.run_steps(3); + assert!(harness.state().session.graph().unwrap().function.is_some()); + assert!(harness.state().function_editor.is_some()); +} + +#[test] +fn preferences_tabs_edit_supported_settings_without_changing_the_document() { + let mut harness = harness(true); + let original = harness.state().session.pkg.clone(); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).next().is_some()); + harness.get(By::new().role(egui::accesskit::Role::Tab).label("Graph")).click(); + harness.run_steps(3); + let thumbnails = harness.state().ui.prefs.thumbnails; + harness.get(By::new().role(egui::accesskit::Role::CheckBox).label("Show node thumbnails")).click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.prefs.thumbnails, !thumbnails); + harness.get(By::new().role(egui::accesskit::Role::Tab).label("3D View")).click(); + harness.run_steps(3); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::Slider).label("3D pan speed")).next().is_some()); + harness.get(By::new().role(egui::accesskit::Role::Tab).label("General")).click(); + harness.run_steps(3); + harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Language")).click(); + harness.run_steps(2); + assert!(harness.query_all(By::new().label("العربية")).next().is_some()); + assert_eq!(harness.state().session.pkg, original); + let saved: UiState = serde_json::from_value(serde_json::to_value(&harness.state().ui).unwrap()).unwrap(); + assert_eq!(saved.prefs.thumbnails, !thumbnails); +} diff --git a/crates/ui-egui/tests/numeric_input.rs b/crates/ui-egui/tests/numeric_input.rs index 5679841..df84d97 100644 --- a/crates/ui-egui/tests/numeric_input.rs +++ b/crates/ui-egui/tests/numeric_input.rs @@ -47,6 +47,32 @@ fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32 } } #[test] +fn graph_name_typed_across_frames_commits_on_focus_loss() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.run("file.new", json!({"template":"empty"})).unwrap(); + app.session.reset_history(); + let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0); + let mut h = builder.build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app, + ); + h.run_steps(8); + h.state_mut().run("graph.select", json!({"ids": []})).unwrap(); + h.run_steps(3); + h.get_by_label("Graph name").click(); + h.step(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.step(); + type_text(&mut h, "My_graph"); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(4); + assert_eq!(h.state().session.graph().unwrap().name, "My_graph", "graph name typed across frames was reset before focus was lost"); +} +#[test] fn offset_x_commits_on_enter_and_focus_loss_with_undo() { for enter in [true, false] { let (mut h, id) = harness(false); diff --git a/crates/ui-egui/tests/panel_maximize.rs b/crates/ui-egui/tests/panel_maximize.rs new file mode 100644 index 0000000..8ebbca9 --- /dev/null +++ b/crates/ui-egui/tests/panel_maximize.rs @@ -0,0 +1,172 @@ +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::{ + Harness, + kittest::{By, Queryable}, +}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState, control, docking::Panel, menus}; +use serde_json::{Value, json}; + +fn app() -> MaterialCraftApp { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = 64; + app +} + +fn maximized(app: &mut MaterialCraftApp, context: &egui::Context) -> Value { + control::handle(app, context, "ui.inspect", &json!({}))["result"]["maximizedPanel"].clone() +} + +fn maximize(app: &mut MaterialCraftApp, context: &egui::Context, panel: Panel) { + let response = control::handle(app, context, "ui.panel.maximize", &json!({"panel": panel})); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(maximized(app, context), json!(panel)); +} + +#[test] +fn maximize_restores_each_panel_without_changing_the_workspace_or_document() { + let mut app = app(); + let context = egui::Context::default(); + app.ui.dock.focus(Panel::Console); + app.ui.dock.focus(Panel::History); + let workspace = serde_json::to_value(&app.ui.dock).unwrap(); + let package = app.session.pkg.clone(); + let modified = app.session.modified; + + for panel in Panel::ALL { + maximize(&mut app, &context, panel); + assert!(menus::enabled(&app, "ui.unmaximize")); + assert!(app.ui.dock.is_visible(panel)); + assert_eq!(serde_json::to_value(&app.ui.dock).unwrap(), workspace); + let saved: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + let mut reopened = MaterialCraftApp::headless(materialcraft_engine::new_session(), saved); + assert_eq!(maximized(&mut reopened, &context), Value::Null); + let response = control::handle(&mut app, &context, "ui.menu.invoke", &json!({"id": "ui.unmaximize"})); + assert_eq!(response["ok"], true); + assert_eq!(maximized(&mut app, &context), Value::Null); + assert!(!menus::enabled(&app, "ui.unmaximize")); + assert_eq!(serde_json::to_value(&app.ui.dock).unwrap(), workspace); + assert_eq!(app.session.pkg, package); + assert_eq!(app.session.modified, modified); + } +} + +#[test] +fn invalid_or_hidden_panels_leave_the_maximized_panel_and_workspace_alone() { + let mut app = app(); + let context = egui::Context::default(); + maximize(&mut app, &context, Panel::View2d); + let workspace = app.ui.dock.workspace().clone(); + + for parameters in [json!({}), json!({"panel": "missing"}), json!({"panel": null}), json!({"panel": "Console"})] { + let response = control::handle(&mut app, &context, "ui.panel.maximize", ¶meters); + assert_eq!(response["ok"], false, "{response}"); + assert_eq!(maximized(&mut app, &context), json!("View2d")); + assert_eq!(app.ui.dock.workspace(), &workspace); + } +} + +#[test] +fn opening_another_panel_or_closing_the_maximized_panel_restores_the_workspace() { + let mut app = app(); + let context = egui::Context::default(); + maximize(&mut app, &context, Panel::View2d); + menus::invoke(&mut app, &context, "ui.view.properties"); + assert_eq!(maximized(&mut app, &context), Value::Null); + assert!(app.ui.dock.is_visible(Panel::Properties)); + + maximize(&mut app, &context, Panel::View2d); + app.ui.dock.close(Panel::View2d); + assert_eq!(maximized(&mut app, &context), Value::Null); + assert!(!app.ui.dock.is_open(Panel::View2d)); + + maximize(&mut app, &context, Panel::Graph); + app.ui.dock.close(Panel::Graph); + assert!(app.ui.dock.is_open(Panel::Graph)); + assert_eq!(maximized(&mut app, &context), json!("Graph")); + menus::invoke(&mut app, &context, "ui.resetLayout"); + assert_eq!(maximized(&mut app, &context), Value::Null); + assert_eq!(app.ui.dock, materialcraft_ui_egui::docking::Dock::default()); +} + +fn harness() -> Harness<'static, MaterialCraftApp> { + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.step(&ui.ctx().clone()); + app.draw(ui); + }, + app(), + ); + harness.run_steps(8); + harness +} + +fn press_shift_space(harness: &mut Harness<'static, MaterialCraftApp>) { + harness.event(Event::ModifiersChanged(Modifiers::SHIFT)); + harness.event(Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + harness.step(); + harness.event(Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::SHIFT }); + harness.step(); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(3); +} + +#[test] +fn shortcut_uses_the_current_pointer_and_restore_button_keeps_panel_geometry() { + let mut harness = harness(); + let context = harness.ctx.clone(); + let graph = harness.state().graph.view; + let workspace = harness.state().ui.dock.workspace().clone(); + harness.event(Event::PointerMoved(graph.center())); + press_shift_space(&mut harness); + assert_eq!(maximized(harness.state_mut(), &context), json!("Graph")); + assert!(harness.state().graph.view.width() > graph.width()); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Restore panel layout")).click(); + harness.run_steps(4); + assert_eq!(maximized(harness.state_mut(), &context), Value::Null); + assert_eq!(harness.state().graph.view, graph); + assert_eq!(harness.state().ui.dock.workspace(), &workspace); + + harness.event(Event::PointerMoved(graph.center())); + harness.step(); + harness.event(Event::PointerMoved(egui::pos2(1599.0, 1.0))); + press_shift_space(&mut harness); + assert_eq!(maximized(harness.state_mut(), &context), Value::Null); +} + +#[test] +fn shortcut_leaves_text_input_and_popups_in_control() { + let mut harness = harness(); + let context = harness.ctx.clone(); + harness.state_mut().ui.windows.new_graph = true; + harness.run_steps(5); + harness + .get(By::new().role(egui::accesskit::Role::Window).label("New graph")) + .get(By::new().role(egui::accesskit::Role::TextInput).label("Graph name")) + .click(); + harness.run_steps(2); + let graph = harness.state().graph.view; + harness.event(Event::PointerMoved(graph.center())); + press_shift_space(&mut harness); + assert_eq!(maximized(harness.state_mut(), &context), Value::Null); + + harness.state_mut().ui.windows.new_graph = false; + harness.run_steps(3); + maximize(harness.state_mut(), &context, Panel::Graph); + harness.state_mut().ui.windows.new_graph = true; + harness.run_steps(5); + harness + .get(By::new().role(egui::accesskit::Role::Window).label("New graph")) + .get(By::new().role(egui::accesskit::Role::TextInput).label("Graph name")) + .click(); + harness.run_steps(2); + press_shift_space(&mut harness); + assert_eq!(maximized(harness.state_mut(), &context), json!("Graph")); + + harness.get_by_label("Cancel").click(); + harness.run_steps(3); + harness.get_by_label("Windows").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&context)); + press_shift_space(&mut harness); + assert_eq!(maximized(harness.state_mut(), &context), json!("Graph")); +} diff --git a/crates/ui-egui/tests/resolution.rs b/crates/ui-egui/tests/resolution.rs index ae5d15a..64231d5 100644 --- a/crates/ui-egui/tests/resolution.rs +++ b/crates/ui-egui/tests/resolution.rs @@ -48,6 +48,36 @@ fn selecting_4k_cooks_and_displays_4k_material_maps() { assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); } +#[test] +fn four_k_preview_refreshes_texture_after_size_change() { + let mut h = Harness::builder().with_context_setup(materialcraft_ui_egui::theme::install).with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut MaterialCraftApp| { + app.apply_prefs(); + view2d::show(app, ui); + }, + app(), + ); + h.input_mut().max_texture_side = Some(4096); + // The cooked key alone does not name the input size, so changing size must still refresh. + let node = h.state().session.view2d.node.unwrap(); + h.state_mut().session.preview_size = Some(4096); + h.state_mut().session.cook(); + h.state_mut().session.cooked.nodes.get_mut(&node).unwrap().key = 0; + h.state_mut().ui.prefs.preview_size = 4096; + h.step(); + let (_, image) = h.state().session.view2d_image().unwrap(); + assert_eq!((image.w, image.h), (4096, 4096)); + assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096))); + h.state_mut().session.preview_size = Some(256); + h.state_mut().session.cook(); + h.state_mut().session.cooked.nodes.get_mut(&node).unwrap().key = 0; + h.state_mut().ui.prefs.preview_size = 256; + h.step(); + let (_, image) = h.state().session.view2d_image().unwrap(); + assert_eq!((image.w, image.h), (256, 256)); + assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256))); +} + #[test] fn command_resolution_survives_preferences_and_invalid_requests() { let mut app = app(); diff --git a/crates/ui-egui/tests/slider_round_values.rs b/crates/ui-egui/tests/slider_round_values.rs index 0e6fdf9..deb0af4 100644 --- a/crates/ui-egui/tests/slider_round_values.rs +++ b/crates/ui-egui/tests/slider_round_values.rs @@ -5,9 +5,15 @@ use egui_kittest::{ kittest::{By, Queryable}, }; use materialcraft_engine::core::{NodeId, Value}; -use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState, widgets}; use serde_json::json; +/// Offset from the exact round value, in physical pixels. Must be positive (so the +/// unsnapped value differs from the round value by more than `f32::EPSILON`) and +/// smaller than the half-physical-pixel snap range in `widgets`, so the round +/// value is the one snapped to. +const AIM_OFFSET_PHYSICAL_PIXELS: f32 = 0.4; + fn harness(ppp: f32, render: bool, definition: &str) -> (Harness<'static, MaterialCraftApp>, NodeId) { let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); let id = NodeId(app.run("graph.node.add", json!({"def":definition})).unwrap()["id"].as_u64().unwrap()); @@ -28,8 +34,9 @@ fn harness(ppp: f32, render: bool, definition: &str) -> (Harness<'static, Materi fn drag_near(h: &mut Harness<'static, MaterialCraftApp>, label: &str, index: usize, value: f32, lo: f32, hi: f32) { let rect = h.get_all(By::new().role(egui::accesskit::Role::Slider).label(label)).nth(index).unwrap().rect(); let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y); - // Aim slightly off the exact value, within one physical pixel. - let target = pos2(rect.left() + 5.0 + (rect.width() - 10.0) * (value - lo) / (hi - lo) + 0.4 / h.ctx.pixels_per_point(), rect.center().y); + // Aim slightly off the exact value, within the half-physical-pixel snap range. + let target = + pos2(rect.left() + 5.0 + (rect.width() - 10.0) * (value - lo) / (hi - lo) + AIM_OFFSET_PHYSICAL_PIXELS / h.ctx.pixels_per_point(), rect.center().y); h.event(Event::PointerMoved(start)); h.step(); h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); @@ -76,6 +83,61 @@ fn fractional_parameter_values_remain_reachable() { assert_eq!(n.params.get("offset"), Some(&Value::Float2([-0.5, 0.25]))); } +#[test] +fn bar_slider_drag_reaches_exact_round_values() { + let mut h = Harness::builder().with_size(vec2(800.0, 400.0)).with_pixels_per_point(1.0).build_ui_state( + |ui, value: &mut f32| { + widgets::bar_slider(ui, "Brightness", value, 0.0..=1.0, 128.0); + }, + 0.0f32, + ); + h.run_steps(3); + let rect = h.get(By::new().role(egui::accesskit::Role::Slider).label("Brightness")).rect(); + let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y); + // Aim AIM_OFFSET_PHYSICAL_PIXELS to the right of 0.5, as the other drags do. + let target = pos2(rect.left() + 4.0 + (rect.width() - 8.0) * 0.5 + AIM_OFFSET_PHYSICAL_PIXELS / h.ctx.pixels_per_point(), rect.center().y); + h.event(Event::PointerMoved(start)); + h.step(); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.event(Event::PointerMoved(start + vec2(10.0, 0.0))); + h.step(); + h.event(Event::PointerMoved(target)); + h.step(); + h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.step(); + h.run_steps(3); + assert_eq!(*h.state(), 0.5); +} + +#[test] +fn bar_slider_drag_preserves_fractional_values() { + let mut h = Harness::builder().with_size(vec2(800.0, 400.0)).with_pixels_per_point(1.0).build_ui_state( + |ui, value: &mut f32| { + widgets::bar_slider(ui, "Brightness", value, 0.0..=1.0, 128.0); + }, + 0.0f32, + ); + h.run_steps(3); + let rect = h.get(By::new().role(egui::accesskit::Role::Slider).label("Brightness")).rect(); + let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y); + // Aim exactly at 33/120 = 0.275, a fractional value between hundredths + // (0.27 and 0.28), so round-value aiming must not move it. + let target = pos2(rect.left() + 4.0 + 33.0, rect.center().y); + h.event(Event::PointerMoved(start)); + h.step(); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.event(Event::PointerMoved(start + vec2(10.0, 0.0))); + h.step(); + h.event(Event::PointerMoved(target)); + h.step(); + h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.step(); + h.run_steps(3); + assert_eq!(*h.state(), 33.0 / 120.0); +} + #[test] #[ignore = "requires an offscreen GPU"] fn exact_angle_screenshot() { diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index b1327e9..e31b068 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -69,9 +69,7 @@ fn empty_startup_can_create_a_template() { } harness.get_by_label("New graph...").click(); settle(&mut harness, 4); - harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Template")).click(); - settle(&mut harness, 2); - harness.get_by_label("Atomic sample").click(); + harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Atomic sample")).click(); settle(&mut harness, 4); harness.get_by_label("Create").click(); settle(&mut harness, 40); @@ -893,3 +891,84 @@ fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() { assert!(frame.chunks_exact(4).filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count() > 100); save(&mut harness, &directory, "graph-dropped-on-material"); } + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn maximized_panels_restore_main_workspace_and_inline_editors() { + use materialcraft_ui_egui::{control, docking::Panel, menus}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.prefs.preview_size = 64; + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 30); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, "transplant-workspace-before"); + let workspace = harness.state().ui.dock.workspace().clone(); + let package = harness.state().session.pkg.clone(); + let context = harness.ctx.clone(); + + for panel in [Panel::View2d, Panel::View3d, Panel::Graph, Panel::Explorer] { + let response = control::handle(harness.state_mut(), &context, "ui.panel.maximize", &json!({"panel": panel})); + assert_eq!(response["ok"], true, "{response}"); + settle(&mut harness, 15); + save(&mut harness, &directory, &format!("transplant-maximized-{panel:?}")); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Restore panel layout")).click(); + settle(&mut harness, 5); + assert_eq!(harness.state().ui.dock.maximized(), None); + assert_eq!(harness.state().ui.dock.workspace(), &workspace); + assert_eq!(harness.state().session.pkg, package); + } + save(&mut harness, &directory, "transplant-workspace-restored"); + + harness.state_mut().run("graph.node.add", json!({"def": "pixel_processor"})).unwrap(); + menus::invoke(harness.state_mut(), &context, "graph.node.edit"); + settle(&mut harness, 4); + assert!(harness.state().function_editor.is_some()); + let package = harness.state().session.pkg.clone(); + control::handle(harness.state_mut(), &context, "ui.panel.maximize", &json!({"panel": "Graph"})); + settle(&mut harness, 5); + assert_eq!(harness.query_all(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).count(), 1); + save(&mut harness, &directory, "transplant-maximized-inline-function"); + harness.get(By::new().role(egui::accesskit::Role::Button).label("Return to parent graph")).click(); + settle(&mut harness, 4); + assert!(harness.state().function_editor.is_none()); + assert_eq!(harness.state().ui.dock.maximized(), Some(Panel::Graph)); + assert_eq!(harness.state().session.pkg, package); + menus::invoke(harness.state_mut(), &context, "ui.unmaximize"); + settle(&mut harness, 4); + assert_eq!(harness.state().ui.dock.workspace(), &workspace); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn transplanted_dialogs_render_with_main_settings_and_templates() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + for instance in 0..2 { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = 64; + app.ui.windows.new_graph = true; + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 30); + save(&mut harness, &directory, &format!("transplant-new-graph-{instance}")); + let rendered = harness.render().unwrap(); + for label in ["Empty", "Material outputs", "Atomic sample"] { + let tile = harness.get(By::new().role(egui::accesskit::Role::ListItem).label(label)).rect(); + let pixel = rendered.get_pixel(tile.center().x as u32, (tile.top() + 46.0) as u32); + assert!(pixel[0] > 140 && pixel[1] > 140 && pixel[2] > 140, "missing {label} preview in app instance {instance}: {pixel:?}"); + } + let original = harness.state().session.pkg.clone(); + harness.get_by_label("Cancel").click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.pkg, original); + harness.state_mut().ui.windows.preferences = true; + settle(&mut harness, 4); + for label in ["General", "Graph", "3D View"] { + harness.get(By::new().role(egui::accesskit::Role::Tab).label(label)).click(); + settle(&mut harness, 3); + save(&mut harness, &directory, &format!("transplant-preferences-{instance}-{label}")); + } + assert_eq!(harness.state().session.pkg, original); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 336f798..8363f4b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -39,6 +39,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: | `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii | | `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's identifier, display label and screen position, fps, toasts | | `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click | +| `ui.panel.maximize {panel}` | app | maximize an open, active panel: `Graph`, `Explorer`, `Library`, `View3d`, `View2d`, `Properties`, `Console`, or `History`; restore with `ui.menu.invoke {"id":"ui.unmaximize"}` | | `ui.set {...}` | app | recursively merge fields into the UI state | | `ui.input {events}` | app | synthetic input, below | | `view.screenshot {view?: "3d"\|"2d"}` | app | PNG of the 3D or 2D view | @@ -65,11 +66,15 @@ window points (take them from `ui.inspect`'s `nodes` and `ports`). Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (egui key names: `A`, `Enter`, `Space`, `Delete`, `F5`, …), `text`. Buttons: `left`, `right`, `middle`. +`ui.inspect.maximizedPanel` reports the temporary maximized panel, or `null`. Maximizing +preserves the saved workspace. Shift+Space toggles maximization under the pointer; text inputs, +popups, modal dialogs and pointer drags retain their input. + ## Key commands | Command | Params | |---|---| -| `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) | +| `file.new` | `{kind?, template?, name?, size?, width?, height?}`; material width/height override size per axis (default 1024 px), rounded down to powers of two in 16..8192; creation is one undo step. Templates from `graph.templates`: `empty`, `pbr`, `atomics` | | `graph.node.edit` | `{}` resolves the selected FX-Map, processor or local graph instance to `{kind, node, parameter?, graph?}`; use `ui.menu.invoke` to enter it in the graph panel | | `graph.pattern.set` | `{id, pattern}` replaces an FX-Map subgraph with cycle validation and undo | | `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` | @@ -78,19 +83,12 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.wire.swap` / `graph.wire.delete` | `{wires: [{to, toPort}, ...]}`: swap (two) or reverse (more, in input order) where the wires come from / delete them, one undo step each | | `graph.node.param` | `{id?, param, value}`: numbers, `[x, y]`, `"#rrggbb"`, enum index, curve `[[x, y], …]`, gradient `[[pos, color], …]`, or a typed value `{"t": "function", "v": {...}}` | | `graph.node.base` | `{id?, sizeMode?, size?, format?, seed?, tiling?}` | -| `graph.exposed.add` / `graph.exposed.set` | `{id, label?, default?, bind?: {node, param}}` / `{id, value}` | +| `graph.exposed.add` / `graph.exposed.set` | `{id, label?, default?, bind?: {node, param}}` (with `bind`, `id` may be omitted: the input is named after the parameter, `opacity`, `opacity_1`…) / `{id, value}` | | `graph.node.function` | `{id?, param, function}` drives a parameter by a function graph of the graph's inputs (dynamic parameter); `{id?, param, remove: true}` removes it | | `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values | | `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance | | `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | -| `view.3d` (nested) | `camera? {focalLength, projection, background, backgroundColor, overrideResolution, resolution, resolutionScale, autoClip, near, far}`, `lights? {ambientOn, ambient, point: [{on, color, intensity, position}, …]}`, `renderer? {useViewportResolution, resolution, scale, samples, aoRays}`, `display? {wireframe, backfaceCulling, boundingBox, lights, resolution, stats, fps}`, `material? {shader, common: {…}, useMap: {…}, tessellation, uvScale}`, `envEnabled?`: the keys given change, the rest stays; values are clamped | -| `view.3d.reset` / `view.3d.state` / `view.3d.loadState` | `{what?: all\|scene\|camera\|lights\|environment\|material\|renderer\|display}` / `{}` → the state as JSON / `{state, keepScene?}` | | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | -| `file.linkBitmap` / `file.reloadResources` / `file.deleteResource` | `{path, name?}` a bitmap read from disk (a relative link when it lies in the package's folder) / `{}` / `{name}` | -| `file.importGraph` / `file.packageGraphs` | `{path, graph?}` copies a graph with its instances and bitmaps from another package / `{path}` lists a package file's graphs | -| `file.saveCopy` / `file.exportWithDependencies` | `{path}` / `{dir}` the package and copies of its linked bitmaps | -| `graph.add` | `{graph}`: a graph as JSON, added under a unique name | -| `session.settings` | `{historySize?, cacheMb?, cookLimit?}` (preferences) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | ## 3D material assignment @@ -169,8 +167,6 @@ execution use bounded iterative traversal and reject cycles. `graph.frame.edit` accepts `title`, `titleVisible`, `description`, `color` and `rect`. `graph.frame.move {"id": ..., "by": [dx, dy], "snapToGrid": true}` moves enclosed nodes, comments, nested frames and pins together. `graph.comment.edit` accepts `text`, `at` and `size`. -`graph.pin.edit {"id": ..., "name"?: ..., "at"?: [x, y]}` renames or moves a navigation pin (the -editor drags pins and renames them from their context menu); `graph.pin.delete {"id"}` removes one. `session.inspect` includes annotation selection and the standalone function; `ui.inspect` includes frame and comment rectangles for synthetic input. diff --git a/docs/gaps.md b/docs/gaps.md index 55eee87..7c32203 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -8,20 +8,20 @@ Current integration also provides workspace-scoped `material_export`, real Heigh from the assigned material, explicit normal-map convention, and linear bitmap/input previews. The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. -> **Last reviewed:** 2026-11-06 · **Last updated:** 2026-11-06 · **Change:** major (lights, shaders, material common values and view-state files closed most of the 3D view gap; node shortcuts closed part of the keymap gap) · **Target:** the professional node-based material workflow +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable `.mcmat` materials closed the published-archive gap) · **Target:** the professional node-based material workflow Every known shortfall, most important first. Pick from the top. | # | Gap | Evidence | Impact | Estimate | Parity doc | |---:|---|---|---|---:|---| -| 1 | Node library breadth | 227 nodes vs. ~400 in the reference library | Recipes that need scan processing, more grunges, splines or MCF (distance-field) functions | 30 h | target-app-parity (Node library) | -| 2 | GPU 3D view | CPU ray caster with lights, shaders and displacement (a tessellation factor scales the triangle budget) | Large meshes and high sample counts are slow; no path tracing | 12 h | target-app-parity (3D view) | +| 1 | Node library breadth | 227 nodes vs. ~400 in the reference library | Recipes that need scan processing, more grunges, splines or SDF shapes | 30 h | target-app-parity (Node library) | +| 2 | GPU 3D view with tessellation and lights | CPU renderer with parallax only | Displacement previews, light setups | 12 h | target-app-parity (3D view) | | 3 | Mesh-based generators and bakers | None | Workflows that start from a mesh | 15 h | target-app-parity (Node library) | | 4 | Portable materials over MCP | `.mcmat` export runs from the app and the CLI; the MCP workspace sandbox refuses `file.*` commands and has no `material_export` tool | Sandboxed agents can't hand a material to TextureCraft | 1 h | target-app-parity (Files) | | 5 | Function loops and reusable functions | Functions live on one parameter or processor | Iterative effects; sharing logic between nodes | 5 h | target-app-parity (Function graphs) | | 6 | Input visibility conditions, per-instance output sizes | Not implemented | Organizing large graphs' inputs | 4 h | target-app-parity (Graph parameters) | | 7 | `ui.screenshot` times out on this test machine | The window-capture callback never fires here; `view.screenshot` and the offscreen snapshot test work | Agents bridged to the app see views but not the whole window | 1 h | — | -| 8 | Translations and a menu keymap editor | English only; node creation shortcuts are editable, menu shortcuts are fixed | Non-English users; custom menu shortcuts | 7 h | localization-parity | +| 8 | Translations and keymap editor | English only, fixed shortcuts | Non-English users; custom shortcuts | 8 h | localization-parity | | 9 | Minimap and multi-graph tabs | One graph at a time, no overview | Navigating big graphs | 5 h | target-app-parity (Graph editing, UI and UX) | | 10 | First signed release | Workflows copied, not run | Downloads | 3 h | target-app-parity (Platforms) | @@ -29,7 +29,6 @@ Every known shortfall, most important first. Pick from the top. | Date | Change | Summary | |---|---|---| -| 2026-11-06 | major | 3D view lights, shaders, common values, camera and renderer pages; node creation shortcuts; linked bitmaps and the dependency manager; plugins | | 2026-11-02 | minor | Portable `.mcmat` materials for TextureCraft closed gap 4; what's left is an MCP tool | | 2026-11-02 | major | Closed the function editor, dynamic parameters, FX-Map/Text/SVG, presets and groups, browser file I/O and accessible names; re-ranked | | 2026-11-02 | major | First list | diff --git a/docs/roadmap.md b/docs/roadmap.md index 318a323..bb4b4c2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -20,7 +20,7 @@ ## Current focus -1. Node library breadth (gap 1): scan processing, more grunges, spline tools, MCF (distance-field) functions. +1. Node library breadth (gap 1): scan processing, more grunges, spline tools, SDF shapes. 2. The GPU 3D view (gap 2) and mesh-based generators (gap 3). 3. Function loops (gap 5) and the portable-material MCP tool (gap 4). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d62775a..240cf7a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -8,25 +8,25 @@ Current integration also provides workspace-scoped `material_export`, real Heigh from the assigned material, explicit normal-map convention, and linear bitmap/input previews. The native SBS and primitive-library limitations in [atomic-workflow.md](atomic-workflow.md) remain. -> **Last reviewed:** 2026-11-06 · **Last updated:** 2026-11-06 · **Change:** major (3D view 55% → 70%, UI and UX 70% → 85%, Files 70% → 75%: the reference's menus, explorer, library, 3D view property pages, preferences and plugins) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (Files 60% → 70%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later) -**Overall: ≈ 70%** of a material artist's daily workflow works end to end (engine + UI + +**Overall: ≈ 67%** of a material artist's daily workflow works end to end (engine + UI + automation + tests), weighted by how much of the day each area carries. **Remaining: ≈ 83 Opus 5.5 agent hours** (see [roadmap.md](roadmap.md)). | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Graph editing | 15 | 77% | Pan/zoom canvas with grid (toggle, snap); node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags; graph toolbar with 1:1, screenshot, graph info, cook times, straight/curved wires, clean-up, parent size link and reset, stack-aligned alignment; node creation shortcuts | Dot-node chains editing, compact node display mode, multi-graph tabs, minimap | +| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap | | Atomic nodes | 12 | 95% | Bitmap, Blend (16 modes, masks, alpha), Blur, Channels Shuffle, Curve, Directional Blur, Directional Warp, Distance (with color propagation), Emboss, FX-Map (grid, quadtree and scatter modes with per-instance randomness), Gradient (Dynamic), Gradient Map, Grayscale Conversion, HSL, Levels, Normal, Pixel Processor, Value Processor, Sharpen, SVG (path data, fill rules, stroke), Text (own stroke font), Transformation 2D, Uniform Color, Warp, inputs, outputs, dots, graph instances | FX-Map driven by per-iteration functions, SVG arcs and SVG files, font choice for Text | | Node library | 20 | 45% | 227 nodes: noises (tileable 3D Perlin, simplex and Worley, cracks, stones, dirt, grunge maps and more), patterns (tile generator and sampler, bricks, hexagons, weave, shape splatter, paint strokes, scratches), filters (adjustments, blending, blurs, channels, effects, normal map tools, tiling, transforms), the flood fill family, whole-material and height blending, weathering (rust, moss, leaks, edge damage, edge wear, dust) | The rest of the reference library's ~400 graphs: more grunge and scan processing, mesh-based generators and bakers, spline tools, SDF functions | | Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items | | Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages | -| 2D view | 5 | 85% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image, the 3D scene's UV layout as an overlay | Color picker to parameters | -| 3D view | 10 | 70% | Eleven built-in scenes (cube, cylinder, plane, hi-res plane, sphere, cloth, material ball, rounded cube, rounded cylinder, two-tile sphere, torus); OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (real displacement of a subdivided mesh with a tessellation factor), AO, emissive, opacity, specular and glossiness; nine shading models (OpenPBR with coat, fuzz, emission, thin film, transmission and subsurface terms; metallic/roughness, coated, SSS, specular/glossiness, Blinn, Lambert, unlit, mesh info) with common values for every unmapped channel and per-map on/off; ambient and two shadow-casting point lights; camera focal length, orthographic projection, background type/colour, render resolution and clip planes; six environments with rotation, exposure and on/off; Display toggles (wireframe, axis, backface culling, bounding box, grid, light gizmos, resolution, stats, FPS); save/copy render; save/load/default view state; all of it in Properties-panel pages and `view.3d` | GPU renderer, path tracing, draggable light gizmos | -| Files | 8 | 70% | `.sbs` packages with embedded or linked bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; rotating auto backups; recent files; linked (not embedded) bitmaps with reload and a Dependency Manager; save a copy, export with dependencies, import a graph (with its instances and bitmaps) from another package; plugins folder whose packages feed the library | An MCP tool for portable materials, SVG and font files as resources | -| UI and UX | 8 | 85% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history) with maximize (Shift+Space), the reference's File/Edit/Tools/Windows/Help menus (switch engine, cancel/suspend rendering, dependency manager, plugin manager, log export), explorer context menus for packages, graphs and resources (rename in place, copy/paste graphs), library tree with favorites, collapsible groups with counts, function nodes and plugin graphs, graph toolbar, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with categories, template info and linked sizes, export dialog, tabbed preferences (general, projects, graph, 3D view, bakers, library, node shortcuts) where every setting does something, home screen, visual function editor, presets bar, accessible names on every widget, status bar with the engine | Translations, menu keymap editor, minimap, multi-graph tabs | +| 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay | +| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer | +| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources | +| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs | | Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run | -| **Total** | **100** | **≈ 70%** | | | +| **Total** | **100** | **≈ 67%** | | | Beyond the reference app: every edit is a command available through MCP, the CLI and the app's control channel (including synthetic mouse and keyboard input), the engine runs headless with the @@ -43,7 +43,6 @@ and is tested. | Date | Change | Summary | |---|---|---| -| 2026-11-06 | major | ≈ 67% → ≈ 70%: the reference UI (menus, explorer, library, new-graph dialog, graph toolbar, 3D view menus and property pages with lights, shaders and common values, tabbed preferences, plugin manager) | | 2026-11-02 | minor | ≈ 66% → ≈ 67%: `.mcmat` portable materials and TextureCraft interop (Files 70%) | | 2026-11-02 | major | Function editor, dynamic parameters, presets, 227 nodes (FX-Map, SVG, Text, 3D noises, weathering), mesh import, browser file I/O, histogram: ≈ 51% → ≈ 66% | | 2026-11-02 | major | First assessment after the first day of work |