diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb4ec50b..7bef15d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,8 @@ jobs: craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc os: '["ubuntu-24.04","windows-latest"]' toolchain: "1.96.0" + # xtask ci runs cargo test (including doctests), not cargo nextest. + tools: "" packages: >- libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 00000000..de64ad3e --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 5882a81c..c9b40de3 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 TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the @@ -10,10 +63,7 @@ PdfCraft, EffectCraft, DesignCraft) in user-facing text: UI, window titles, Abou release names, docs prose. Machine names stay lowercase: crates (`texturecraft-*`), binaries, file names, ids (`ai.storyteller.texturecraft`), the native project extension `.tcraft`. -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. +Shared code goes only in craft-libs; otherwise copy, don't depend. The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer stack semantics and export conventions) with better performance, every feature drivable by agents, @@ -98,7 +148,7 @@ as a clean-room implementation, in code, docs and commits. People trust TextureCraft with hours of painting. A malformed mesh or project, a bad command or MCP param, 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`. +panic. - Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries @@ -176,6 +226,6 @@ after every arc of work that builds and passes. - `ROADMAP.md`: milestones, parity estimate and remaining effort. - `docs/parity.md`: generated Painter menu coverage. -- `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 3e690427..43c994c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1 @@ -# TextureCraft: 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 8f34fc52..3a4aa398 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -412,6 +412,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -448,6 +454,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -691,6 +706,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -704,7 +729,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -717,19 +742,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-dialogs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "rfd", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -749,10 +796,44 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-keymap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "craft-keymap", + "craft-quit", + "egui", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + +[[package]] +name = "craft-quit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "dispatch2", + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -770,10 +851,36 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "chrono", + "dunce", + "egui", + "flate2", + "getrandom 0.3.4", + "image", + "log", + "plist", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "egui", "objc2 0.6.5", @@ -790,6 +897,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -821,6 +937,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -861,6 +987,22 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -920,6 +1062,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.20" @@ -1252,6 +1400,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -1447,6 +1605,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1457,6 +1625,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1728,6 +1907,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2103,6 +2298,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -2322,6 +2527,24 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "png", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "naga" version = "30.0.1" @@ -2436,6 +2659,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -2795,6 +3024,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -2997,6 +3232,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.18.1" @@ -3081,6 +3329,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "presser" version = "0.3.1" @@ -3155,6 +3409,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3339,6 +3602,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rmcp" version = "3.5.1" @@ -3446,6 +3723,80 @@ dependencies = [ "rustix 1.1.5", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3461,6 +3812,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "1.2.3" @@ -3499,6 +3859,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3510,6 +3893,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "send_wrapper" @@ -3591,6 +3978,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3762,6 +4160,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -3821,6 +4225,16 @@ dependencies = [ "windows", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3847,6 +4261,8 @@ dependencies = [ name = "texturecraft" version = "0.3.1" dependencies = [ + "craft-menu", + "craft-update", "eframe", "egui", "image", @@ -3958,7 +4374,7 @@ dependencies = [ "half", "image", "lz4_flex", - "quick-xml", + "quick-xml 0.41.0", "rayon", "serde", "serde_json", @@ -4026,7 +4442,11 @@ name = "texturecraft-ui-egui" version = "0.3.1" dependencies = [ "base64 0.22.1", + "craft-dialogs", + "craft-keymap", + "craft-quit", "craft-ui", + "craft-update", "craft-window", "eframe", "egui", @@ -4118,6 +4538,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -4300,6 +4750,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -4347,6 +4803,41 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "urlencoding" version = "2.1.3" @@ -4362,6 +4853,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -4416,6 +4913,16 @@ dependencies = [ "vello_common", ] +[[package]] +name = "verifysign" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", +] + [[package]] name = "version_check" version = "0.9.5" @@ -4596,7 +5103,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -4632,6 +5139,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -5152,7 +5668,7 @@ dependencies = [ "calloop", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5197,6 +5713,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + [[package]] name = "winresource" version = "0.1.34" @@ -5513,6 +6039,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index a63fdcc7..29de448b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,9 +65,19 @@ getrandom = "0.3" rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] } # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/README.md b/README.md index 80f807b6..69cd720c 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ MCP server for agents License: MIT OR Apache-2.0
+ Scanned by SonarCloud Reviewed by CodeRabbit

diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 2f80d416..b4a1d57c 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -30,6 +30,12 @@ ron = "0.12" [target.'cfg(windows)'.dependencies] winit = { version = "0.30", default-features = false } winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +# The update helper is a copy of this program (`main`). +craft-update = { workspace = true } + +# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not. +[target.'cfg(target_os = "macos")'.dependencies] +craft-menu = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 377b2e52..4965c438 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -11,11 +11,17 @@ mod window_frame; use texturecraft_engine::Session; use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). const APP_NAME: &str = "TextureCraft"; +/// The window's size when it opens, in points. +const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; +/// The smallest size the window can be resized to, in points. +const MIN_SIZE: [f32; 2] = [960.0, 600.0]; + const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); fn version() -> String { @@ -115,13 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read from the saved settings before the window opens -/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. -fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); - let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); - let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); - kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off +fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs.system_title_bar; + } + + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); + let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -161,7 +170,17 @@ impl eframe::App for Shell { } } +/// A script driving the app gets no network check and no update prompt over its window. +fn checks_for_updates_at_start(control: Option) -> bool { + control.is_none() +} + fn main() { + // Windows: the update helper is a copy of this program started with `--finish-update`. + #[cfg(windows)] + if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + std::process::exit(i32::from(result.is_err())); + } let args = match parse_args() { Ok(Some(a)) => a, Ok(None) => return, @@ -170,21 +189,25 @@ fn main() { std::process::exit(2); } }; - // Errors before the window opens speak the system's language; the app then applies the saved one. + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - // A message box needs the main thread on macOS; other threads' panics are only logged. + // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); let session = initial_session(&args); - // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor - // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); - let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); + let ui_file = + persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + if let Some(file) = &ui_file { + let _ = ui_state_store::FILE.set(file.clone()); + } + let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); + let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); } @@ -195,7 +218,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + // The start window offers new, open and recent projects, unless a file was given or a script drives the app let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, @@ -205,10 +228,16 @@ fn main() { if let Some(w) = cc.winit_window() { set_taskbar_icon(w); } + // winit's Quit ends the process without asking; this menu's asks like the close button. + #[cfg(target_os = "macos")] + if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { + log::warn!("the app menu could not be installed: {e}"); + } let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; app.ui.windows.start = start && app.ui.prefs.start_window; + app.set_startup_update_check(checks_for_updates_at_start(control)); if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } @@ -274,6 +303,12 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } + #[test] + fn only_a_run_without_a_control_port_checks_for_updates_at_start() { + assert!(checks_for_updates_at_start(None)); + assert!(!checks_for_updates_at_start(Some(9000))); + } + #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); @@ -296,19 +331,27 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { - let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; - // Written as eframe writes it: a pretty RON map of RON strings. + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); - std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&path)), on); + std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + ui.prefs.system_title_bar = !on; + std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); } - std::fs::write(&path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&path))); - std::fs::remove_file(&path).unwrap(); - assert!(!saved_system_title_bar(Some(&path))); + + std::fs::write(&json_path, "not json").unwrap(); + std::fs::write(&ron_path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + std::fs::remove_file(&json_path).unwrap(); + std::fs::remove_file(&ron_path).unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); } } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 87d58648..0af8274d 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -72,7 +72,7 @@ fn join(dir: &str, name: &str) -> String { impl Headless { pub fn new(session: Session, fs: Filesystem) -> Headless { // Bakes run here (CLI, MCP) cast their rays on the GPU when there is one. - texturecraft_engine::bake_cmds::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); + texturecraft_engine::bake::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); Headless { session, fs, gpu: None } } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 4621d6a0..c61fce50 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -72,7 +72,7 @@ impl Gpu { // The aux texture behind the mesh-map and mask views (rebuilt every render). let res = texturecraft_render::aux_size(cache.size); let aux = match s.view { - ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)), + ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &comp.block_scales)), ViewMode::Mask(id) if s.doc.project.locate(id).is_some_and(|(t, _, _)| t == ts) => s.mask_view_rgba(id, res), _ => None, }; diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2015c090..1061db2d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError { AutomationError::Io(format!("{op} `{path}` failed: {e}")) } -/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`, -/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped -/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command -/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is -/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the -/// embedded mesh). +/// Host keys a command reads or writes a file through, at the top level or in each `files` entry +const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; + +/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { - let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())); - let ok = match id { + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); + + // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path + let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, _ => !id.starts_with("file.") && !has_path, }; - if ok { + if allowed { Ok(()) } else { Err(bad(format!( @@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError } } +/// Whether `params` names a host path or folder at its own top level +fn names_host_path(params: &Value) -> bool { + HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null())) +} + #[cfg(test)] mod tests { use super::*; @@ -243,6 +248,18 @@ mod tests { assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } + #[test] + fn nested_file_paths_are_denied() { + let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]}); + assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err()); + + let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]}); + assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err()); + + let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]}); + assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok()); + } + /// Every registry command documenting a host path must be classified (fails when a new /// path-taking command is added without an automation policy). #[test] diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs new file mode 100644 index 00000000..d2c7d7f3 --- /dev/null +++ b/crates/bake/src/cage.rs @@ -0,0 +1,15 @@ +//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws + +mod cage_shell; +mod high_poly_reach; +mod ray_frame; +mod ray_start; +mod vertex_reach; + +#[cfg(test)] +pub(crate) use cage_shell::CORNERS; +pub use cage_shell::CageShell; +pub use high_poly_reach::HighPolyReach; +pub(crate) use ray_frame::RayFrame; +pub use ray_start::RayStart; +pub use vertex_reach::VertexReach; diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs new file mode 100644 index 00000000..e1664219 --- /dev/null +++ b/crates/bake/src/cage/cage_shell.rs @@ -0,0 +1,65 @@ +use super::{RayFrame, RayStart}; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use std::collections::{HashMap, HashSet}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::surface_at; + +/// Barycentric coordinates of a triangle's three corners +pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; + +/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles +#[derive(Clone, Debug, Default)] +pub struct CageShell { + /// Low-poly position of each triangle corner, three per triangle + pub positions: Vec, + pub starts: Vec, + /// Corner pairs along the low poly's polygon edges, for the wireframe + pub edges: Vec<[u32; 2]>, + /// World units per unit of the max frontal distance setting + pub cage_units: f32, +} + +impl CageShell { + /// The cage of `request`'s texture set, from the same ray starts the bake uses + pub fn new(request: &BakeRequest) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let (frame, mesh) = (&ray_frame, request.mesh); + let triangles: Vec = mesh.triangles_of(request.material).collect(); + let (positions, starts): (Vec, Vec) = triangles + .par_iter() + .flat_map_iter(|&triangle| { + CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) { + Some(surface) => (surface.pos, frame.start(&surface, barycentric)), + None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }), + }) + }) + .unzip(); + + let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let mut edge_corners = HashMap::new(); + for (triangle_index, &triangle) in triangles.iter().enumerate() { + let Some(vertices) = mesh.tri(triangle) else { continue }; + + for corner in 0..3 { + let next = (corner + 1) % 3; + let (from, to) = (vertices[corner] as u32, vertices[next] as u32); + let key = (from.min(to), from.max(to)); + if wire_edges.contains(&key) { + let first_corner = (triangle_index * 3) as u32; + edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + } + } + } + let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); + edges.sort_unstable(); + + Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + } + + /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling + pub fn corners(&self, max_frontal: f32) -> Vec { + let frontal = max_frontal * self.cage_units; + self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect() + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs new file mode 100644 index 00000000..f957ce49 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,103 @@ +use super::{RayFrame, VertexReach}; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, surface_at}; + +/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses +#[derive(Clone, Debug, Default)] +pub struct HighPolyReach { + /// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly + pub vertices: Vec>, + /// World units per unit of the cage distance settings + pub cage_units: f32, + pub ignore_backface: bool, +} + +impl HighPolyReach { + /// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there + pub fn new(request: &BakeRequest) -> Result { + let Some(high) = request.high else { return Ok(HighPolyReach::default()) }; + + let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let mut in_set = vec![false; request.mesh.triangle_count()]; + for triangle in request.mesh.triangles_of(request.material) { + if let Some(flag) = in_set.get_mut(triangle) { + *flag = true; + } + } + + let winding_normals = winding_normals(high.mesh); + let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode { + MeshMatchMode::Always => (Vec::new(), Vec::new()), + MeshMatchMode::ByMeshName => { + let (low_keys, high_keys) = transfer_keys(request); + (low_keys, vertex_keys(high.mesh, &high_keys)) + } + }; + let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY); + let frame = &frame; + let vertices = high + .mesh + .positions + .par_iter() + .zip(&winding_normals) + .enumerate() + .map(|(vertex, (&high_position, &high_facing))| { + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?; + if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) { + return None; + } + + let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?; + let ray_key = key(&low_keys, nearest.tri as usize); + Some(VertexReach { + low_position: surface.pos, + start: frame.start(&surface, [nearest.u, nearest.v]), + high_position, + high_facing, + name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key, + }) + }) + .collect(); + + Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface }) + } + + /// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's + pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option { + let reach = self.vertices.get(vertex).copied().flatten()?; + Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface)) + } +} + +/// Each vertex's mesh-name key, from the first triangle that uses it +fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { + let mut keys = vec![ANY; mesh.positions.len()]; + for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) { + for &corner in corners { + if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) { + *key = triangle_key; + } + } + } + keys +} + +/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front +fn winding_normals(mesh: &Mesh) -> Vec { + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for corners in mesh.indices.chunks_exact(3) { + let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO); + let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0])); + for &corner in corners { + if let Some(normal) = normals.get_mut(corner as usize) { + *normal += winding_normal; + } + } + } + normals +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs new file mode 100644 index 00000000..e8692cf2 --- /dev/null +++ b/crates/bake/src/cage/ray_frame.rs @@ -0,0 +1,63 @@ +use super::RayStart; +use crate::MeshExtent; +use crate::map::{interpolate, welded}; +use crate::skew::PreparedSkew; +use crate::{BakeError, BakePaintMap, BakeRequest}; +use texturecraft_core::CageType; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +pub(crate) struct RayFrame<'a> { + mesh: &'a Mesh, + ray_normals: Vec, + cage: Option<&'a Mesh>, + skew: Option>, + cage_paint: Option<&'a BakePaintMap>, + /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead + ray_epsilon: f32, + /// World units per unit of the cage distance settings + pub(crate) cage_units: f32, +} + +impl<'a> RayFrame<'a> { + pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { + let settings = request.settings; + let ray_normals = match settings.cage.average_normals && request.high.is_some() { + true => { + let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); + welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + } + false => Vec::new(), + }; + + Ok(RayFrame { + mesh: request.mesh, + ray_normals, + cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, + cage_paint: request.cage_paint, + ray_epsilon: extent.ray_epsilon(), + cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 }, + }) + } + + /// Where the transfer ray of the low-poly point `surface` at `barycentric` starts + pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart { + let cage_offset = self + .cage + .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) + .map(|cage_position| surface.pos - cage_position) + .filter(|offset| offset.length() > self.ray_epsilon); + if let Some(offset) = cage_offset { + return RayStart::CageMesh(offset); + } + + let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let up = match &self.skew { + Some(skew) => skew.correct(self.mesh, surface, averaged_normal), + None => averaged_normal, + }; + RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) } + } +} diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs new file mode 100644 index 00000000..c0c3923a --- /dev/null +++ b/crates/bake/src/cage/ray_start.rs @@ -0,0 +1,20 @@ +use texturecraft_geom::glam::Vec3; + +/// Where the bake's transfer ray for one low-poly point starts +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RayStart { + /// On the cage mesh: the offset from the cage to the low-poly point + CageMesh(Vec3), + /// Out along `up` by the frontal distance times `scale` (the painted cage amount) + Distance { up: Vec3, scale: f32 }, +} + +impl RayStart { + /// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance + pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 { + match *self { + RayStart::CageMesh(offset) => position - offset, + RayStart::Distance { up, scale } => position + up * frontal * scale, + } + } +} diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs new file mode 100644 index 00000000..34adea92 --- /dev/null +++ b/crates/bake/src/cage/vertex_reach.rs @@ -0,0 +1,28 @@ +use super::RayStart; +use texturecraft_geom::glam::Vec3; + +/// One high-poly vertex seen from the transfer ray through its nearest low-poly point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VertexReach { + pub low_position: Vec3, + pub start: RayStart, + pub high_position: Vec3, + /// The side the high poly's triangles face at the vertex, by their winding (not normalized) + pub high_facing: Vec3, + /// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name) + pub name_matches: bool, +} + +impl VertexReach { + /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray + pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { + let origin = self.start.origin(self.low_position, frontal); + let (direction, front) = match self.start { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), + RayStart::Distance { up, scale } => (-up, frontal * scale), + }; + let along_ray = (self.high_position - origin).dot(direction); + + !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 0b315cdb..eb8a61de 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -6,13 +6,17 @@ mod bake_error; mod bake_output; mod bake_request; +mod cage; mod high_poly; +mod mesh_extent; mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; pub use bake_request::BakeRequest; +pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; +pub(crate) use mesh_extent::MeshExtent; pub use progress::Progress; mod map; @@ -143,14 +147,20 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer) + bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) } /// Retry on the CPU if the supplied tracer fails pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { - match bake_in_strips(request, progress, STRIP_TEXELS, tracer) { + bake_tiles(request, progress, &[], Some(tracer)) +} + +/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing +pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { + let tracer = tracer.unwrap_or(&CpuTracer); + match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { Err(BakeError::Tracer(error)) => { - let mut output = bake(request, progress)?; + let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); Ok(output) } @@ -160,8 +170,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) type OutRow<'a> = Vec<&'a mut [f32]>; -fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { +fn bake_in_strips( + request: &BakeRequest, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { validate(request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + let settings = request.settings; let (tile_width, tile_height) = settings.common.output_size(); let tile_size = (tile_width as usize, tile_height as usize); @@ -173,12 +193,13 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz let mut scene = tracer.scene(&meshes)?; progress.done.store(0, Relaxed); - // Normal-map curvature needs a normal bake even when normal output is disabled + // Normal-map curvature needs a world normal bake even when that output is disabled let from_normal = settings.maps.curvature.parameters.method == CurvatureMethod::NormalMap && settings.maps.is_enabled(BakedMap::Curvature); let mut maps: Vec = settings.maps.enabled().collect(); - if from_normal && !maps.contains(&BakedMap::Normal) { - maps.push(BakedMap::Normal); + if from_normal && !maps.contains(&BakedMap::WorldNormal) { + maps.push(BakedMap::WorldNormal); } + let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::, _>>()?; let mut covered = alloc(width * height, false)?; let mut padding_map = None; @@ -196,7 +217,17 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis); strip_mesh.uvs = request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect(); - let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + let mut gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + for &(column, row) in excluded_tiles { + let start_x = column as usize * tile_size.0 * samples_per_axis; + let start_y = row as usize * tile_size.1 * samples_per_axis; + let end_y = (start_y + tile_size.1 * samples_per_axis).min(sample_start_y + strip_sample_height); + for sample_y in start_y.max(sample_start_y)..end_y { + let first = (sample_y - sample_start_y) * sample_width + start_x; + gbuffer.tri.get_mut(first..first + tile_size.0 * samples_per_axis).ok_or_else(strip_error)?.fill(NO_TRI); + } + } + let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?; coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| { for (x, covered_pixel) in row.iter_mut().enumerate() { @@ -255,15 +286,18 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { - let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) }; - if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) { + let world_normal = + if settings.maps.is_enabled(BakedMap::WorldNormal) { output.get(&BakedMap::WorldNormal).cloned() } else { output.remove(&BakedMap::WorldNormal) }; + if let (Some(world_normal), Some(curvature_pixels)) = (world_normal, output.get_mut(&BakedMap::Curvature)) { let parameters = settings.maps.curvature.parameters.normal_map; - map::curvature_from_normal(&normal, &covered, width, tile_size, parameters, curvature_pixels); + let grid = map::TexelGrid { covered: &covered, size: (width, height), tile_size }; + map::curvature_from_normal(&world_normal, request.mesh, request.material, &grid, parameters, curvature_pixels); if parameters.enable_seams { map::fix_seams(request.mesh, request.material, &covered, (width, height), parameters.seams_intensity, curvature_pixels); } } } + let (bounds_min, bounds_max) = request.mesh.bounds(); map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); if let Some(padding_map) = padding_map { diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 9638a140..c9c30fd6 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -12,11 +12,16 @@ pub(crate) use seam::fix_seams; mod position_projection; mod sampling; mod source; +mod texel_grid; mod traced; mod transfer; +mod transfer_keys; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use sampling::{interpolate, welded}; +pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; +pub(crate) use transfer_keys::transfer_keys; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index 21fed094..f3e35df6 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,28 +1,22 @@ use super::curvature::Curvature; -use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded}; +use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::skew::PreparedSkew; +use crate::cage::{RayFrame, RayStart}; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; -use crate::{BakeError, BakeRequest}; +use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; -use std::collections::HashMap; use texturecraft_core::{ - AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, }; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; +use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - cage_paint: Option<&'a crate::BakePaintMap>, - ray_normals: Vec, + ray_frame: RayFrame<'a>, settings: &'a BakeSettings, - eps: f32, frontal: f32, rear: f32, position: PositionProjection, @@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> { impl<'a> BakeContext<'a> { pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { let settings = request.settings; - let (bounds_min, bounds_max) = request.mesh.bounds(); - let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6); - if !mesh_diagonal.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - - let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6); - let mut name_keys = HashMap::new(); - let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys); - let high = request.high.map(|high_mesh| { - Source::new( - high_mesh.mesh, - high_mesh.bvh, - high_mesh.base_color, - high_mesh.file_ids, - &settings.high_poly.high_suffix, - &settings.high_poly, - &mut name_keys, - ) - }); - let ray_normals = match settings.cage.average_normals && high.is_some() { - true => { - let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - - let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?; - let ray_epsilon = 1e-6 * mesh_diagonal; + let extent = MeshExtent::of(request.mesh)?; + let (low, high) = Source::of_request(request); + let ray_frame = RayFrame::new(request, extent)?; + let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 }; @@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> { pass.ignore_backface = parameters.ignore_backface; pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName; pass.attenuation = parameters.attenuation; - pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset); + pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset); } + let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion); if let Some(pass) = &mut bent { pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface; pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName; } + let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness); if let Some(pass) = &mut thickness { pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName; } - let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + + let cage_units = ray_frame.cage_units; Ok(BakeContext { low, high, - cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, - skew, - cage_paint: request.cage_paint, - ray_normals, + ray_frame, settings, - eps: ray_epsilon, frontal: settings.cage.max_frontal * cage_units, rear: settings.cage.max_rear * cage_units, position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters), @@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> { } pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { - let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); - let cage = self - .cage - .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) - .map(|cage_position| surface.pos - cage_position) - .filter(|offset| offset.length() > self.eps); - let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)); - let (origin, direction, front) = match cage { - Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), - None => { - let up = match &self.skew { - Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), - None => averaged_normal, - }; - (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale) - } + let start = self.ray_frame.start(surface, barycentric); + let origin = start.origin(surface.pos, self.frontal); + let (direction, front) = match start { + RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), + RayStart::Distance { up, scale } => (-up, self.frontal * scale), }; let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs index 2cc6bfc5..c96163c7 100644 --- a/crates/bake/src/map/normal_curvature.rs +++ b/crates/bake/src/map/normal_curvature.rs @@ -1,42 +1,120 @@ -/// Divergence of the tangent-space normal map; positive curvature is convex +use rayon::prelude::*; +use texturecraft_core::NormalMapCurvatureSettings; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; + +use super::TexelGrid; + +/// Output slope per unit of normal turn per texel at a 2048-texel tile and Details 0.5, set by eye on a hard-surface bake +const SLOPE_AT_2K: f32 = 3.0; + +/// How fast the baked world normal turns along the low poly's surface; positive curvature is convex pub(crate) fn curvature_from_normal( - normal: &[f32], - covered: &[bool], - width: usize, - tile_size: (usize, usize), - settings: texturecraft_core::NormalMapCurvatureSettings, + world_normal: &[f32], + mesh: &Mesh, + material: usize, + grid: &TexelGrid, + settings: NormalMapCurvatureSettings, output: &mut [f32], ) { - use rayon::prelude::*; - let radius_texels = (tile_size.0.min(tile_size.1) / 512).max(1); - let strength = 2.0f32.powf((settings.details - 0.5) * 4.0); - let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) { - Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback), - _ => fallback, + let TexelGrid { covered, size, tile_size } = *grid; + let triangle_of_texel = triangle_of_each_texel(mesh, material, grid); + let surface_directions = surface_direction_of_each_triangle(mesh, size); + let normal_at = |index: usize| { + let encoded = world_normal.get(index * 3..index * 3 + 3).and_then(|components| <[f32; 3]>::try_from(components).ok()).unwrap_or([0.5, 0.5, 1.0]); + Vec3::from_array(encoded) * 2.0 - 1.0 }; - output.par_chunks_mut(width).enumerate().for_each(|(y, row)| { + + // Turn of the normal per texel, measured along the surface direction each texel axis points to + let turn_along = |axis: usize| -> Vec { + (0..covered.len()) + .into_par_iter() + .map(|index| { + let Some(direction) = + triangle_of_texel.get(index).and_then(|triangle| surface_directions.get(*triangle as usize)).and_then(|pair| pair.get(axis).copied()) + else { + return 0.0; + }; + + let step = if axis == 0 { (1, 0) } else { (0, 1) }; + let forward = grid.neighbour(index, step.0, step.1); + let backward = grid.neighbour(index, -step.0, -step.1); + let change = match (forward, backward) { + (Some(ahead), Some(behind)) => (normal_at(ahead) - normal_at(behind)) * 0.5, + (Some(ahead), None) => normal_at(ahead) - normal_at(index), + (None, Some(behind)) => normal_at(index) - normal_at(behind), + (None, None) => Vec3::ZERO, + }; + change.dot(direction) + }) + .collect() + }; + let (turn_along_x, turn_along_y) = (turn_along(0), turn_along(1)); + + let slope = SLOPE_AT_2K * tile_size.0.min(tile_size.1) as f32 / 2048.0 * 2.0f32.powf((settings.details - 0.5) * 4.0); + output.par_chunks_mut(size.0).enumerate().for_each(|(y, row)| { for (x, value) in row.iter_mut().enumerate() { - if covered.get(y * width + x) != Some(&true) { + let index = y * size.0 + x; + if covered.get(index) != Some(&true) { continue; } - let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5)); - let (left, right) = ( - if x % tile_size.0 >= radius_texels { normal_component(x - radius_texels, y, 0, center_x) } else { center_x }, - if x % tile_size.0 + radius_texels < tile_size.0 && x + radius_texels < width { - normal_component(x + radius_texels, y, 0, center_x) - } else { - center_x - }, - ); - let (up, down) = ( - if y % tile_size.1 >= radius_texels { normal_component(x, y - radius_texels, 1, center_y) } else { center_y }, - if y % tile_size.1 + radius_texels < tile_size.1 && y + radius_texels < covered.len() / width.max(1) { - normal_component(x, y + radius_texels, 1, center_y) - } else { - center_y - }, - ); - *value = (0.5 + ((right - left) + (up - down)) * strength).clamp(0.0, 1.0); + + // A 1-2-1 average across each derivative keeps lines equally wide in every direction + let curvature = grid.average_along(&turn_along_x, index, (0, 1)) + grid.average_along(&turn_along_y, index, (1, 0)); + + // Rises at `slope` near flat and rolls off softly, so strong edges never clip into flat white + *value = 0.5 + 0.5 * (2.0 * slope * curvature).tanh(); } }); } + +/// Unit surface directions of a texel step in x and in y on each triangle of the low poly +fn surface_direction_of_each_triangle(mesh: &Mesh, size: (usize, usize)) -> Vec<[Vec3; 2]> { + let texel_scale = Vec2::new(size.0 as f32, size.1 as f32); + (0..mesh.indices.len() / 3) + .map(|triangle| { + let corner = |slot: usize| -> Option<(Vec3, Vec2)> { + let vertex = *mesh.tri(triangle)?.get(slot)?; + Some((*mesh.positions.get(vertex)?, *mesh.uvs.get(vertex)? * texel_scale)) + }; + let (Some((first_position, first_texel)), Some((second_position, second_texel)), Some((third_position, third_texel))) = + (corner(0), corner(1), corner(2)) + else { + return [Vec3::ZERO; 2]; + }; + + let (position_edge_1, position_edge_2) = (second_position - first_position, third_position - first_position); + let (texel_edge_1, texel_edge_2) = (second_texel - first_texel, third_texel - first_texel); + let determinant = texel_edge_1.perp_dot(texel_edge_2); + // A triangle with no UV area has no texel directions + if determinant.abs() < 1e-12 { + return [Vec3::ZERO; 2]; + } + + let along_x = (position_edge_1 * texel_edge_2.y - position_edge_2 * texel_edge_1.y) / determinant; + let along_y = (position_edge_2 * texel_edge_1.x - position_edge_1 * texel_edge_2.x) / determinant; + [along_x.normalize_or_zero(), along_y.normalize_or_zero()] + }) + .collect() +} + +/// Low-poly triangle under each covered texel; edge texels covered only by antialiasing borrow a neighbour's +fn triangle_of_each_texel(mesh: &Mesh, material: usize, grid: &TexelGrid) -> Vec { + let centres = UvGBuffer::new(mesh, material, grid.size.0 as u32, grid.size.1 as u32).tri; + (0..centres.len()) + .into_par_iter() + .map(|index| { + let own = centres.get(index).copied().unwrap_or(NO_TRI); + if own != NO_TRI || grid.covered.get(index) != Some(&true) { + return own; + } + + [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] + .into_iter() + .filter_map(|(step_x, step_y)| grid.neighbour(index, step_x, step_y)) + .map(|neighbour| centres.get(neighbour).copied().unwrap_or(NO_TRI)) + .find(|triangle| *triangle != NO_TRI) + .unwrap_or(NO_TRI) + }) + .collect() +} diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs index d19e4afa..5f2d2677 100644 --- a/crates/bake/src/map/sampling.rs +++ b/crates/bake/src/map/sampling.rs @@ -3,34 +3,43 @@ use std::ops::{Add, Mul}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) +/// `values` (one per vertex) at `barycentric` in triangle `triangle` +pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option { + let [first, second, third] = mesh.tri(triangle as usize)?; + let [second_weight, third_weight] = barycentric; + + Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight) } -pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { - let q = diag * 1e-5; - let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); - let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); - let weld: Vec = mesh +/// Vertices closer than this fraction of the mesh diagonal count as one when welding +const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5; + +/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals +pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec, Vec, Vec) { + let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL; + let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new(); + let (mut positions, mut normal_sums) = (Vec::new(), Vec::::new()); + + let welded_indices: Vec = mesh .positions .iter() .zip(&mesh.normals) - .map(|(p, n)| { - let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); - let id = *ids.entry(key).or_insert_with(|| { - pos.push(*p); - nrm.push(Vec3::ZERO); - (pos.len() - 1) as u32 + .map(|(position, normal)| { + let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64); + let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| { + positions.push(*position); + normal_sums.push(Vec3::ZERO); + (positions.len() - 1) as u32 }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; + if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) { + *normal_sum += *normal; } - id + welded_index }) .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) + + let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect(); + (welded_indices, positions, normals) } pub(super) fn splitmix64(x: u64) -> u64 { diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..ad057b11 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,4 +1,5 @@ use super::sampling::{generated_hue, interpolate, splitmix64}; +use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; use std::collections::HashMap; use std::sync::Arc; @@ -21,6 +22,18 @@ pub(super) struct Source<'a> { } impl<'a> Source<'a> { + /// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part + pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option>) { + let settings = &request.settings.high_poly; + let mut name_keys = HashMap::new(); + let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys); + let high = request.high.map(|high_mesh| { + Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys) + }); + + (low, high) + } + pub(super) fn new( mesh: &'a Mesh, bvh: &'a Bvh, diff --git a/crates/bake/src/map/texel_grid.rs b/crates/bake/src/map/texel_grid.rs new file mode 100644 index 00000000..49e2b588 --- /dev/null +++ b/crates/bake/src/map/texel_grid.rs @@ -0,0 +1,32 @@ +/// Covered texels of a baked map, with UV tiles that neighbours never cross +#[derive(Clone, Copy)] +pub(crate) struct TexelGrid<'a> { + pub covered: &'a [bool], + pub size: (usize, usize), + pub tile_size: (usize, usize), +} + +impl TexelGrid<'_> { + /// The covered texel one step away in the same tile, if any + pub fn neighbour(&self, index: usize, step_x: isize, step_y: isize) -> Option { + let (width, height) = self.size; + let (x, y) = (index % width.max(1), index / width.max(1)); + let (next_x, next_y) = (x.checked_add_signed(step_x)?, y.checked_add_signed(step_y)?); + if next_x >= width || next_y >= height { + return None; + } + + let same_tile = next_x / self.tile_size.0.max(1) == x / self.tile_size.0.max(1) && next_y / self.tile_size.1.max(1) == y / self.tile_size.1.max(1); + let next = next_y * width + next_x; + (same_tile && self.covered.get(next) == Some(&true)).then_some(next) + } + + /// A 1-2-1 weighted average of `values` along `step`, over covered texels only + pub fn average_along(&self, values: &[f32], index: usize, step: (isize, isize)) -> f32 { + let centre = values.get(index).copied().unwrap_or(0.0); + let sides = [self.neighbour(index, step.0, step.1), self.neighbour(index, -step.0, -step.1)]; + let (sum, weight) = + sides.into_iter().flatten().fold((2.0 * centre, 2.0), |(sum, weight), side| (sum + values.get(side).copied().unwrap_or(0.0), weight + 1.0)); + sum / weight + } +} diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs new file mode 100644 index 00000000..69e9b12a --- /dev/null +++ b/crates/bake/src/map/transfer_keys.rs @@ -0,0 +1,8 @@ +use super::source::Source; +use crate::BakeRequest; + +/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key +pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec, Vec) { + let (low, high) = Source::of_request(request); + (low.key, high.map(|high| high.key).unwrap_or_default()) +} diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs new file mode 100644 index 00000000..3c6fa48d --- /dev/null +++ b/crates/bake/src/mesh_extent.rs @@ -0,0 +1,35 @@ +use crate::BakeError; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances +const MIN_MESH_SIZE: f32 = 1e-6; + +/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal +const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6; + +/// The low-poly mesh's size, which scales the bake's relative distances +#[derive(Clone, Copy, Debug)] +pub(crate) struct MeshExtent { + pub(crate) bounds_min: Vec3, + pub(crate) diagonal: f32, + /// The bounding box's largest side + pub(crate) scale: f32, +} + +impl MeshExtent { + pub(crate) fn of(mesh: &Mesh) -> Result { + let (bounds_min, bounds_max) = mesh.bounds(); + let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE); + if !diagonal.is_finite() { + return Err(BakeError::Invalid("mesh bounds are too large".into())); + } + + Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) }) + } + + /// How far a ray starts past the surface it leaves, in world units + pub(crate) fn ray_epsilon(&self) -> f32 { + RAY_EPSILON_PER_DIAGONAL * self.diagonal + } +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs new file mode 100644 index 00000000..2d114b06 --- /dev/null +++ b/crates/bake/src/test/cage_shell.rs @@ -0,0 +1,103 @@ +use super::settings; +use crate::cage::CORNERS; +use crate::map::BakeContext; +use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly}; +use texturecraft_core::{BakedMap, CageType}; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// A painted map whose values vary over the UV square +fn painted_map() -> BakePaintMap { + let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap(); + map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap(); + map +} + +/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit +fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { + let shell = CageShell::new(request).unwrap(); + let corners = shell.corners(request.settings.cage.max_frontal); + let context = BakeContext::new(request).unwrap(); + let triangles: Vec = request.mesh.triangles_of(request.material).collect(); + assert_eq!(corners.len(), triangles.len() * 3); + + for (corner_index, corner) in corners.iter().enumerate() { + let barycentric = CORNERS[corner_index % 3]; + let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap(); + let (ray, _) = context.transfer_ray(&surface, barycentric); + assert_eq!(*corner, ray.origin, "corner {corner_index}"); + } +} + +#[test] +fn the_cage_corners_are_the_bake_ray_origins() { + let low = primitives::cube(1.0); + let high_mesh = primitives::sphere(0.8, 16, 8); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let (skew, cage_paint) = (painted_map(), painted_map()); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.max_frontal = 0.03; + bake_settings.skew.edge_protection = true; + let request = |settings| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings, + high: Some(high), + cage: None, + skew: Some(&skew), + cage_paint: Some(&cage_paint), + tiles: (1, 1), + }; + + assert_cage_matches_the_ray_origins(&request(&bake_settings)); + let face_normals = { + let mut face_normals = bake_settings.clone(); + face_normals.cage.average_normals = false; + face_normals.cage.relative_to_bounding_box = false; + face_normals + }; + assert_cage_matches_the_ray_origins(&request(&face_normals)); +} + +#[test] +fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { + let low = primitives::cube(1.0); + let low_bvh = Bvh::new(&low); + let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] }; + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max); + + assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly"); + // Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis + assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance"); + assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge"); + + let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() }; + let custom_settings = { + let mut custom_settings = bake_settings.clone(); + custom_settings.cage.kind = CageType::CustomFile; + custom_settings + }; + let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request }; + assert_cage_matches_the_ray_origins(&custom); + let corners = CageShell::new(&custom).unwrap().corners(0.0); + assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); + assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs new file mode 100644 index 00000000..e6d66d07 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,222 @@ +use super::settings; +use crate::map::{BakeContext, transfer_keys}; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart}; +use texturecraft_core::{BakedMap, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them +const BOUNDARY: f32 = 1e-4; + +/// How close the ray's hit must be to the vertex to count as reaching it +const HIT_TOLERANCE: f32 = 1e-4; + +/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way +fn bumpy_high_poly() -> (Mesh, Vec) { + const FLIPPED_FROM_X: f32 = 0.2; + + let mut mesh = primitives::plane(1.0, 40); + for position in &mut mesh.positions { + position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005; + } + + let mut flipped = vec![false; mesh.positions.len()]; + let mut unflipped = vec![false; mesh.positions.len()]; + for corners in mesh.indices.chunks_exact_mut(3) { + let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0; + if center_x > FLIPPED_FROM_X { + corners.swap(1, 2); + } + for &corner in corners.iter() { + if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true } + } + } + // Vertices on the border face both ways: neither answer is right for them + let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect(); + (mesh, mixed) +} + +#[test] +fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { + let low = primitives::plane(1.0, 8); + let (high_mesh, mixed) = bumpy_high_poly(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let back_facing = |triangle: u32, direction: Vec3| { + let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]); + (b - a).cross(c - a).dot(direction) > 0.0 + }; + let mut checked = [0usize; 2]; + + for ignore_backface in [false, true] { + for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] { + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.high_poly.ignore_backface = ignore_backface; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); + let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") }; + let height = vertex_reach.high_position.y - vertex_reach.low_position.y; + let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY); + if near_the_range_end || mixed[vertex] { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let hit = high_bvh + .closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction))); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!( + missed, !reaches_the_vertex, + "vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}" + ); + checked[usize::from(missed)] += 1; + } + } + } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); +} + +#[test] +fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() { + let mut low = primitives::plane(1.0, 4); + let mut right = primitives::plane(1.0, 4); + for position in &mut right.positions { + position.x += 2.0; + } + low.append(&right); + assert_eq!(low.materials.len(), 2, "each plane is its own texture set"); + let mut high_mesh = primitives::plane(3.0, 30); + for position in &mut high_mesh.positions { + position.x += 1.0; + position.y = 0.3; + } + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = |material| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap()); + + for (vertex, position) in high_mesh.positions.iter().enumerate() { + let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some()); + assert!(owners != (true, true), "vertex {vertex} belongs to one set at most"); + if position.x < 0.9 { + assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set"); + } else if position.x > 1.1 { + assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set"); + } + } +} + +#[test] +fn matching_by_mesh_name_misses_the_parts_with_another_name() { + const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01; + + let mut low = primitives::plane(1.0, 8); + low.submeshes[0].name = "part_low".into(); + let mut high_mesh = primitives::plane(0.5, 10); + let mut other_part = primitives::plane(0.5, 10); + for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] { + for position in &mut mesh.positions { + position.x += center_x; + position.y = HEIGHT_INSIDE_THE_CAGE; + } + } + high_mesh.append(&other_part); + high_mesh.submeshes[0].name = "part_high".into(); + high_mesh.submeshes[1].name = "other_high".into(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.cage.max_frontal = 0.02; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + let (_, high_keys) = transfer_keys(&request); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles + if vertex_reach.high_position.x.abs() < BOUNDARY { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key); + let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position); + assert_eq!( + missed, + vertex >= high_mesh.positions.len() - other_part.positions.len(), + "only the part named like the low poly is reached: vertex {vertex}" + ); + } +} + +#[test] +fn without_a_high_poly_no_vertex_has_a_reach() { + let low = primitives::plane(1.0, 4); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + + let reach = HighPolyReach::new(&request).unwrap(); + assert!(reach.vertices.is_empty()); + // Any cage distances: there is no vertex to miss + assert_eq!(reach.missed(0, 0.02, 0.01), None); +} diff --git a/crates/bake/src/test/normal_map_curvature.rs b/crates/bake/src/test/normal_map_curvature.rs new file mode 100644 index 00000000..99ea078e --- /dev/null +++ b/crates/bake/src/test/normal_map_curvature.rs @@ -0,0 +1,84 @@ +use super::{bumped, covered_values, quad, quad_texel, settings, smooth_shaded_box, transfer}; +use texturecraft_core::{BakeSettings, BakedMap, CageSettings, CommonBakeSettings, CurvatureMethod, CurvatureSettings}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; + +fn normal_map_settings(resolution: u32) -> BakeSettings { + let mut base = settings(resolution, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; + base.maps.curvature.parameters.normal_map.enable_seams = false; + base +} + +fn coordinates_beyond(position: Vec3, threshold: f32) -> usize { + position.abs().to_array().iter().filter(|coordinate| **coordinate > threshold).count() +} + +fn lowest_and_highest(values: impl IntoIterator) -> (f32, f32) { + values.into_iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lowest, highest), value| (lowest.min(value), highest.max(value))) +} + +#[test] +fn curvature_from_the_normal_map_sees_the_bump() { + let out = transfer(&quad(), &bumped(0.1, 0.12), None, &normal_map_settings(64)).unwrap(); + assert!(!out.maps.contains_key(&BakedMap::WorldNormal), "the helper world normal map is not returned"); + + let curvature = &out.maps[&BakedMap::Curvature]; + assert!(curvature[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", curvature[quad_texel(64, 0.0, 0.0)]); + assert!((curvature[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", curvature[quad_texel(64, 0.9, 0.9)]); +} + +#[test] +fn flat_faces_of_a_smooth_shaded_low_poly_stay_mid_grey() { + let low = smooth_shaded_box(); + let curvature = covered_values(&low, &transfer(&low, &primitives::cube(2.0), None, &normal_map_settings(256)).unwrap(), BakedMap::Curvature); + let faces: Vec = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.7) == 1).map(|(_, value)| *value).collect(); + + assert!(!faces.is_empty()); + assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.02), "face range {:?}", lowest_and_highest(faces.iter().copied())); +} + +#[test] +fn a_rounded_edge_is_one_convex_band() { + let bevel = 0.1; + let low = smooth_shaded_box(); + let curvature = + covered_values(&low, &transfer(&low, &primitives::rounded_box(Vec3::ONE, bevel), None, &normal_map_settings(512)).unwrap(), BakedMap::Curvature); + let across_one_edge = |from: f32, to: f32| { + curvature + .iter() + .filter(move |(position, _)| (position.x - 1.0).abs() < 1e-3 && position.z.abs() < 0.3 && (from..to).contains(&position.y)) + .map(|(_, value)| *value) + }; + + let inside_the_bevel = across_one_edge(1.0 - bevel * 0.8, 0.99).fold(1.0f32, f32::min); + let next_to_the_bevel = lowest_and_highest(across_one_edge(0.5, 1.0 - bevel * 1.5)); + assert!(inside_the_bevel > 0.55, "the band dips inside the bevel: {inside_the_bevel}"); + assert!(next_to_the_bevel.0 > 0.48 && next_to_the_bevel.1 < 0.52, "next to the bevel {next_to_the_bevel:?}"); +} + +#[test] +fn a_small_bump_has_no_ring_beyond_its_skirt() { + let (resolution, sigma) = (512, 0.08); + let out = transfer(&quad(), &bumped(0.08, sigma), None, &normal_map_settings(resolution)).unwrap(); + let curvature = &out.maps[&BakedMap::Curvature]; + let ring: Vec = (0..64) + .map(|step| step as f32 / 64.0 * std::f32::consts::TAU) + .flat_map(|angle| [3.0f32, 4.0].map(|radius| curvature[quad_texel(resolution, radius * sigma * angle.cos(), radius * sigma * angle.sin())])) + .collect(); + + assert!(curvature[quad_texel(resolution, 0.0, 0.0)] > 0.6, "convex top {}", curvature[quad_texel(resolution, 0.0, 0.0)]); + assert!(ring.iter().all(|value| (value - 0.5).abs() < 0.02), "ring {:?}", lowest_and_highest(ring.iter().copied())); +} + +#[test] +fn island_borders_of_flat_faces_do_not_streak() { + let cube = primitives::cube(2.0); + let curvature = covered_values(&cube, &transfer(&cube, &cube, None, &normal_map_settings(128)).unwrap(), BakedMap::Curvature); + let faces: Vec = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.97) == 1).map(|(_, value)| *value).collect(); + + assert!(!faces.is_empty()); + assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.01), "face range {:?}", lowest_and_highest(faces.iter().copied())); +} diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs new file mode 100644 index 00000000..18f13968 --- /dev/null +++ b/crates/bake/src/test/tile_selection.rs @@ -0,0 +1,54 @@ +use super::{Broken, settings}; +use crate::tracing::CpuTracer; +use crate::{BakeRequest, Progress, bake, bake_in_strips, bake_tiles}; +use texturecraft_core::{BakeAntialiasing, BakedMap, TileGrid}; +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::{Bvh, primitives}; + +#[test] +fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { + let mut mesh = primitives::udim_plane(); + let grid = TileGrid::of(&[1001, 1002]).unwrap(); + mesh.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array()))); + let bvh = Bvh::new(&mesh); + let mut settings = settings(32, &[BakedMap::Position, BakedMap::AmbientOcclusion]); + settings.maps.ao.parameters.rays.rays = 4; + settings.common.antialiasing = BakeAntialiasing::Subsampling2x2; + settings.common.dilation = 4; + settings.common.apply_diffusion = true; + let request = BakeRequest { + mesh: &mesh, + bvh: &bvh, + material: 0, + low_base_color: &[], + settings: &settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (2, 1), + }; + let full = bake(&request, &Progress::new()).unwrap(); + for excluded in [[(0, 0)], [(1, 0)]] { + let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap(); + let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap(); + assert_eq!(strips.maps, partial.maps); + assert_eq!(fallback.maps, partial.maps); + assert!(fallback.tracer.contains("Broken unavailable")); + + for map in [BakedMap::Position, BakedMap::AmbientOcclusion] { + let components = map.components(); + for (index, pixel) in partial.maps[&map].chunks_exact(components).enumerate() { + if index % 64 / 32 == excluded[0].0 as usize { + assert_eq!(pixel, &map.neutral()[..components]); + } else { + assert_eq!(pixel, &full.maps[&map][index * components..(index + 1) * components]); + } + } + } + } + + assert!(bake_tiles(&request, &Progress::new(), &[(2, 0)], None).is_err()); + assert!(bake_tiles(&request, &Progress::new(), &[(0, u32::MAX)], None).is_err()); +} diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs new file mode 100644 index 00000000..7675e8dc --- /dev/null +++ b/crates/bake/src/test/vertex_reach.rs @@ -0,0 +1,51 @@ +use crate::{RayStart, VertexReach}; +use texturecraft_geom::glam::Vec3; + +/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25 +const FRONTAL: f32 = 0.5; +const REAR: f32 = 0.25; + +/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage +const IGNORED_FRONTAL: f32 = 9.0; + +/// How far past an end of the ray's range a vertex counts as outside it +const PAST_THE_END: f32 = 1e-3; + +/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing` +fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach { + VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches } +} + +#[test] +fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() { + // A painted cage amount of 2 doubles the frontal distance + let starts = [ + (RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL), + (RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0), + (RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL), + ]; + let (top, bottom) = (FRONTAL, -REAR); + // Height, facing, name matches, ignore backface: missed + let cases = [ + (top, Vec3::Y, true, false, false), + (bottom, Vec3::Y, true, false, false), + (0.0, Vec3::Y, true, false, false), + (top + PAST_THE_END, Vec3::Y, true, false, true), + (bottom - PAST_THE_END, Vec3::Y, true, false, true), + (0.0, Vec3::Y, false, false, true), + (0.0, Vec3::NEG_Y, true, false, false), + (0.0, Vec3::NEG_Y, true, true, true), + (0.0, Vec3::Y, true, true, false), + ]; + + for (start, frontal) in starts { + for (height, facing, name_matches, ignore_backface, missed) in cases { + let reach = vertex(start, height, facing, name_matches); + assert_eq!( + reach.missed(frontal, REAR, ignore_backface), + missed, + "{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}" + ); + } + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 00b46b7b..abfccaac 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -14,9 +14,24 @@ use texturecraft_geom::primitives; use super::*; +#[path = "test/cage_shell.rs"] +mod cage_shell; + +#[path = "test/high_poly_reach.rs"] +mod high_poly_reach; + #[path = "test/setting.rs"] mod setting; +#[path = "test/normal_map_curvature.rs"] +mod normal_map_curvature; + +#[path = "test/tile_selection.rs"] +mod tile_selection; + +#[path = "test/vertex_reach.rs"] +mod vertex_reach; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { @@ -307,7 +322,7 @@ fn strips_match_a_single_pass() { tiles: (1, 1), }; let whole = bake(&req, &Progress::new()).unwrap(); - let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).unwrap(); + let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap(); for (map, a) in &whole.maps { let b = &strips.maps[map]; let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count(); @@ -562,6 +577,25 @@ fn a_high_poly_box_has_bright_edges_and_flat_faces() { } } +#[test] +fn default_curvature_brightens_box_edges_and_never_darkens_them() { + let mut bake_settings = settings(256, &[BakedMap::Curvature]); + bake_settings.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..bake_settings.cage }; + bake_settings.maps.curvature.parameters.method = CurvatureMethod::default(); + + // A box has no concave texel, whether it is baked from itself or from a beveled high poly + let low = primitives::cube(2.0); + let high = primitives::rounded_box(Vec3::ONE, 0.15); + let bakes = [("itself", run(&low, &bake_settings).unwrap()), ("a beveled high poly", transfer(&low, &high, None, &bake_settings).unwrap())]; + for (source, bake_output) in bakes { + let curvature = covered_values(&low, &bake_output, BakedMap::Curvature); + let darkest = curvature.iter().map(|(_, value)| *value).fold(1.0, f32::min); + let brightest = curvature.iter().map(|(_, value)| *value).fold(0.0, f32::max); + assert!(darkest > 0.45, "baked from {source}, darkest {darkest}"); + assert!(brightest > 0.6, "baked from {source}, brightest {brightest}"); + } +} + #[test] fn a_narrow_high_poly_bevel_stays_bright() { let s = { @@ -635,21 +669,6 @@ fn bump_tilts_the_baked_normal() { assert!(height[quad_texel(64, 0.0, 0.0)] > height[quad_texel(64, 0.6, 0.6)] + 0.2, "the bump top is higher"); } -#[test] -fn curvature_from_the_normal_map_sees_the_bump() { - let s = { - let mut base = settings(64, &[BakedMap::Curvature]); - base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; - base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; - base - }; - let out = transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap(); - assert!(!out.maps.contains_key(&BakedMap::Normal), "the helper normal map is not returned"); - let c = &out.maps[&BakedMap::Curvature]; - assert!(c[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", c[quad_texel(64, 0.0, 0.0)]); - assert!((c[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", c[quad_texel(64, 0.9, 0.9)]); -} - #[test] fn bent_normals_point_away_from_occluders() { let mut m = quad(); diff --git a/crates/compose/src/baked_maps.rs b/crates/compose/src/baked_maps.rs new file mode 100644 index 00000000..1ce05bf7 --- /dev/null +++ b/crates/compose/src/baked_maps.rs @@ -0,0 +1,53 @@ +use std::collections::BTreeMap; + +use texturecraft_core::{BakedMap, BlockScales}; + +/// Dense mesh maps with `components()` floats per texel in row-major order +/// Each UV tile fills its block independently of the working resolution +/// The width is `resolution`; height follows the output size and UV tile grid +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BakedMaps { + /// Width in texels + pub resolution: u32, + pub maps: BTreeMap>>, +} + +impl BakedMaps { + /// Sample a working atlas texel without resampling the stored bake + pub fn sample_working(&self, map: BakedMap, x: u32, y: u32, size: (u32, u32), scales: &BlockScales) -> Option<[f32; 3]> { + let uv = [(x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32]; + self.sample_uv(map, scales.bake_uv(uv, size)?) + } + + /// Nearest sample in the uniform bake atlas + pub fn sample_uv(&self, map: BakedMap, uv: [f32; 2]) -> Option<[f32; 3]> { + if uv.iter().any(|value| !value.is_finite()) { + return None; + } + + let size = (self.resolution, self.height(map)); + self.sample(map, (uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32, size) + } + + /// Height in texels of map `m`, from its length + pub fn height(&self, m: BakedMap) -> u32 { + self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) + } + + /// Sample the corresponding texel of an image with the supplied output size + pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { + let data = self.maps.get(&map)?; + let width = u64::from(self.resolution.max(1)); + let height = u64::from(self.height(map).max(1)); + let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); + let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); + let component_count = map.components(); + let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; + let texel = data.get(offset..offset.checked_add(component_count)?)?; + Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) + } + + pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { + self.sample(m, x, y, size).map(|v| v[0]) + } +} diff --git a/crates/compose/src/curvature_size_level.rs b/crates/compose/src/curvature_size_level.rs new file mode 100644 index 00000000..fcd25492 --- /dev/null +++ b/crates/compose/src/curvature_size_level.rs @@ -0,0 +1,50 @@ +/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers. +pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0; + +/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map. +pub struct CurvatureSizeLevel { + pub step: u32, + pub width: u32, + pub height: u32, + /// UV tile dimensions in stored texels; interpolation must stay inside one tile + pub block: (u32, u32), + pub deviation: Vec, +} + +impl CurvatureSizeLevel { + /// The deviation at map texel `(x, y)`, interpolated within its UV tile + pub fn sample(&self, x: u32, y: u32) -> f32 { + if self.width == 0 || self.height == 0 { + return 0.0; + } + + let step = self.step.max(1); + let axis = |texel: u32, block: u32, length: u32| { + let block = block.max(1); + let first = if block >= length { 0 } else { (texel / block.saturating_mul(step) * block).min(length - 1) }; + let last = first.saturating_add(block - 1).min(length - 1); + let position = ((texel as f32 + 0.5) / step as f32 - 0.5).clamp(first as f32, last as f32); + let lower = position.floor() as u32; + (lower, (lower + 1).min(last), position - lower as f32) + }; + let (x0, x1, blend_x) = axis(x, self.block.0, self.width); + let (y0, y1, blend_y) = axis(y, self.block.1, self.height); + let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE); + let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x; + let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x; + top + (bottom - top) * blend_y + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn samples_blend_the_stored_texels() { + let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, block: (2, 1), deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] }; + assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1"); + assert!((level.sample(3, 0) - 0.25).abs() < 1e-3); + assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends"); + } +} diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs new file mode 100644 index 00000000..d04e7f62 --- /dev/null +++ b/crates/compose/src/curvature_sizes.rs @@ -0,0 +1,447 @@ +//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; +use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; + +/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +pub struct CurvatureSizes { + /// One per blurred size, built once a generator gives that size a weight above 0. + pub levels: Vec>>, +} + +/// The bake map size, its UV tile block and the working texture size a cache entry was built for. +type CacheKey = ((u32, u32), (u32, u32), (u32, u32)); + +/// Built sizes by the curvature data they come from, their layout and the tiles' scales. +type CacheEntry = (Weak>, CacheKey, BlockScales, Arc); + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +// Undo snapshots keep old maps alive; their derived levels must not grow with the history +const CACHE_BYTES: usize = 256 << 20; +const CACHE_MAPS: usize = 16; + +impl CurvatureSizes { + /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. + pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { + let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + if !needed.contains(&true) || width == 0 || height == 0 { + return None; + } + + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); + let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height)); + let built = cached(curvature, key, &inp.block_scales); + if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) { + return Some(sizes.clone()); + } + + // Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again + let covered = covered_texels(inp, (width, height)); + let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref()); + Some(store(curvature, key, &inp.block_scales, sizes)) + } + + /// Whether every size `needed` marks is built. + fn holds(&self, needed: &[bool]) -> bool { + needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some()) + } + + /// Pad and blur each UV tile at the requested sizes, reusing levels already in `built` + fn build( + curvature: &[f32], + (width, height): (u32, u32), + covered: &[bool], + block: (u32, u32), + needed: &[bool], + built: Option<&CurvatureSizes>, + ) -> CurvatureSizes { + let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); + let deviation: Vec = + padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); + let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); + + let levels = CurvatureDetail::SIZES + .iter() + .skip(1) + .enumerate() + .map(|(level, size)| { + if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { + return Some(existing); + } + if !needed.get(level).copied().unwrap_or(false) { + return None; + } + + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser + let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; + let mut step = (radius / 2).max(1).next_power_of_two(); + // A coarse cell must not average curvature from different UV tiles + while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) { + step /= 2; + } + + let mut blurred = deviation.clone(); + for block_y in (0..height).step_by(block_height as usize) { + for block_x in (0..width).step_by(block_width as usize) { + let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y)); + blur_block(&mut blurred, width, region, radius); + } + } + Some(Arc::new(coarsen(&blurred, (width, height), step, (block_width, block_height)))) + }) + .collect(); + CurvatureSizes { levels } + } +} + +/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any +fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Option> { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + let index = cache.iter().position(|entry| is_entry_for(entry, curvature, key, scales))?; + let entry = cache.remove(index); + let sizes = entry.3.clone(); + cache.push(entry); + Some(sizes) +} + +/// Cache `sizes`, merging any levels another thread stored meanwhile +fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let sizes = if let Some((.., cached_sizes)) = cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)) { + let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect(); + CurvatureSizes { levels } + } else { + sizes + }; + + // One layout per curvature map, with the most recently used map at the end + cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); + let sizes = Arc::new(sizes); + cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); + trim_cache(&mut cache, CACHE_BYTES); + sizes +} + +/// Evict the least recently used maps, retaining the newest even if it alone exceeds the budget +fn trim_cache(cache: &mut Vec, budget: usize) { + // Keeping the newest prevents a large atlas from rebuilding its levels for every tile + let mut bytes = 0usize; + let mut keep = 0; + for (.., sizes) in cache.iter().rev() { + let size = sizes.levels.iter().flatten().map(|level| level.deviation.len().saturating_mul(size_of::())).fold(0usize, usize::saturating_add); + bytes = bytes.saturating_add(size); + if keep > 0 && (bytes > budget || keep == CACHE_MAPS) { + break; + } + keep += 1; + } + cache.drain(..cache.len() - keep); +} + +/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`. +fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> bool { + source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales +} + +/// The bake atlas texels (`width × height`) overlapped by covered working texels of `inp` +fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { + let working_size = (inp.gbuf.width, inp.gbuf.height); + if working_size == (width, height) && inp.block_scales == BlockScales::default() { + return (0..width * height).into_par_iter().map(|texel| inp.gbuf.covered(texel as usize)).collect(); + } + + let covered: Vec = (0..width * height).map(|_| AtomicBool::new(false)).collect(); + (0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| { + let (x, y) = (texel % working_size.0, texel / working_size.0); + let uv = [(x as f32 + 0.5) / working_size.0 as f32, (y as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + // A lower-resolution working texel covers a whole rectangle in the bake, not just its center + let scale = inp.block_scales.at(x, y); + let footprint = |center: f32, baked: u32, working: u32| { + let half_width = 0.5 * baked as f32 / (working as f32 * scale); + let center = center * baked as f32; + ((center - half_width).floor().max(0.0) as u32)..((center + half_width).ceil() as u32).min(baked) + }; + let columns = footprint(baked_uv[0], width, working_size.0); + for baked_y in footprint(baked_uv[1], height, working_size.1) { + for baked_x in columns.clone() { + if let Some(slot) = covered.get((baked_y * width + baked_x) as usize) { + slot.store(true, Ordering::Relaxed); + } + } + } + } + }); + covered.into_iter().map(AtomicBool::into_inner).collect() +} + +/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) { + let rows = top..top + region_height; + let mut block: Vec = + rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, region_width as usize, region_height as usize, radius as usize); + + // The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength + let column_weights = window_inside(region_width as usize, radius as usize); + let row_weights = window_inside(region_height as usize, radius as usize); + for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) { + for (value, column_weight) in values.iter_mut().zip(&column_weights) { + *value /= row_weight * column_weight; + } + } + + for (row, values) in block.chunks(region_width as usize).enumerate() { + let start = ((top + row as u32) * width + left) as usize; + if let Some(target) = data.get_mut(start..start + values.len()) { + target.copy_from_slice(values); + } + } +} + +/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in. +fn window_inside(length: usize, radius: usize) -> Vec { + let window = (2 * radius + 1) as f64; + let mut weights = vec![1.0f64; length]; + for _ in 0..BLUR_BOX_PASSES { + let running_totals: Vec = std::iter::once(0.0) + .chain(weights.iter().scan(0.0, |total, weight| { + *total += weight; + Some(*total) + })) + .collect(); + let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0); + weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect(); + } + weights.into_iter().map(|weight| weight as f32).collect() +} + +/// `data` averaged over `step × step` squares, clipping the last cells to the map +fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u32)) -> CurvatureSizeLevel { + let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); + let deviation = (0..coarse_width * coarse_height) + .into_par_iter() + .map(|cell| { + let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width); + let columns = cell_x * step..((cell_x + 1) * step).min(width); + let rows = cell_y * step..((cell_y + 1) * step).min(height); + let count = (columns.len() * rows.len()).max(1) as f32; + let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize)); + let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::() / count; + (mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16 + }) + .collect(); + CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, block: (block.0.div_ceil(step), block.1.div_ceil(step)), deviation } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn coarse_sizes_do_not_blend_between_uv_tiles() { + let (width, height) = (512, 512); + let block = (256, 256); + let curvature: Vec = (0..width * height).map(|texel| if (texel % width) / block.0 == (texel / width) / block.1 { 0.8 } else { 0.2 }).collect(); + let covered = vec![true; curvature.len()]; + let sizes = CurvatureSizes::build(&curvature, (width, height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + for level in sizes.levels.iter().flatten() { + for (x, y) in [(255, 128), (256, 128), (128, 255), (128, 256), (255, 255), (256, 256)] { + let expected = curvature[(y * width + x) as usize] - 0.5; + assert!((level.sample(x, y) - expected).abs() < 0.001, "step {} at ({x}, {y}): {} instead of {expected}", level.step, level.sample(x, y)); + } + } + } + + #[test] + fn coverage_preserves_bake_texels_above_the_working_resolution() { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + let mesh = primitives::plane(2.0, 1); + let mut project = Project::new("Coverage", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 64)); + let gbuf = UvGBuffer::new(&mesh, 0, 64, 64); + let pixels = Default::default(); + let images = Default::default(); + let baked = Default::default(); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + for size in [(32, 32), (64, 64), (128, 128), (128, 32)] { + let coverage = covered_texels(&inputs, size); + assert!(coverage.iter().all(|covered| *covered), "the plane covers the entire {size:?} bake, including between working texel centers"); + } + } + + #[test] + fn coverage_expands_scaled_tiles_without_crossing_block_borders() { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{NO_TRI, UvGBuffer, primitives}; + + let mesh = primitives::plane(2.0, 1); + let mut project = Project::new("Tile coverage", "builtin:plane"); + let mut set = TextureSet::new("Tiles", 0, 64); + set.uv_tiles = vec![1001, 1002, 1003]; + set.tile_resolutions.insert(1002, 32); + let scales = set.block_scales(); + project.texture_sets.push(set); + let mut gbuf = UvGBuffer::new(&mesh, 0, 192, 64); + for (index, triangle) in gbuf.tri.iter_mut().enumerate() { + if !(64..96).contains(&(index % 192)) || index / 192 >= 32 { + *triangle = NO_TRI; + } + } + let pixels = Default::default(); + let images = Default::default(); + let baked = Default::default(); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: scales, + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + let covered = covered_texels(&inputs, (384, 128)); + for (index, covered) in covered.iter().enumerate() { + assert_eq!(*covered, (128..256).contains(&(index % 384)), "bake texel ({}, {})", index % 384, index / 384); + } + } + + #[test] + fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() { + let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect(); + let scales = BlockScales::default(); + let key = ((4, 4), (4, 4), (4, 4)); + let sizes = store(&sources[0], key, &scales, CurvatureSizes { levels: Vec::new() }); + let first = Arc::downgrade(&sizes); + drop(sizes); + for source in sources.iter().skip(1) { + store(source, key, &scales, CurvatureSizes { levels: Vec::new() }); + } + + assert!(first.upgrade().is_none(), "undo history may retain the bake, but not an unlimited number of derived maps"); + } + + #[test] + fn cache_budget_evicts_old_levels_but_keeps_one_large_map() { + let source = Arc::new(vec![0.5]); + let key = ((1, 1), (1, 1), (1, 1)); + let entry = || { + let level = CurvatureSizeLevel { step: 1, width: 4, height: 1, block: (4, 1), deviation: vec![0; 4] }; + let sizes = CurvatureSizes { levels: vec![Some(Arc::new(level))] }; + (Arc::downgrade(&source), key, BlockScales::default(), Arc::new(sizes)) + }; + let mut cache = vec![entry(), entry(), entry()]; + let oldest = Arc::downgrade(&cache[0].3); + let newest = cache[2].3.clone(); + + trim_cache(&mut cache, 16); + assert_eq!(cache.len(), 2); + assert!(oldest.upgrade().is_none()); + trim_cache(&mut cache, 1); + assert_eq!(cache.len(), 1, "the active map must not rebuild once per composite tile"); + assert!(Arc::ptr_eq(&cache[0].3, &newest)); + } + + #[test] + fn padding_keeps_an_island_border_from_reading_flat() { + let map_size: u32 = 64; + let left_half = |texel: u32| texel % map_size < map_size / 2; + let curvature: Vec = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..map_size * map_size).map(left_half).collect(); + let shape = (map_size, map_size); + let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The last covered column, halfway down + let (border_x, border_y) = (map_size / 2 - 1, map_size / 2); + for level in sizes.levels.iter().flatten() { + assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } + + #[test] + fn uniform_curvature_keeps_its_strength_at_block_borders() { + let (map_width, map_height): (u32, u32) = (256, 256); + // Curvature 0.8 reads 0.3 above the neutral 0.5 at every size + const CURVATURE: f32 = 0.8; + let expected = CURVATURE - 0.5; + let curvature = vec![CURVATURE; (map_width * map_height) as usize]; + let covered = vec![true; curvature.len()]; + let block = (map_width / 2, map_height); + let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The map's corner, then the last texel of the left block and the first of the right one, halfway down + let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)]; + for level in sizes.levels.iter().flatten() { + for (x, y) in border_texels { + assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y)); + } + } + } + + #[test] + fn a_new_layout_replaces_the_sizes_of_the_old_one() { + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let entries_for_curvature = || { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() + }; + + store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); + store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); + assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + } + + #[test] + fn sizes_built_on_demand_match_a_full_build() { + let map_size: u32 = 64; + let curvature: Vec = + (0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect(); + let covered = vec![true; (map_size * map_size) as usize]; + let shape = (map_size, map_size); + let all = vec![true; CurvatureDetail::BLURRED_SIZES]; + let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None); + + let even: Vec = (0..all.len()).map(|level| level % 2 == 0).collect(); + let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None); + assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built"); + + let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial)); + for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) { + assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way"); + if let (Some(built), Some(earlier)) = (built, earlier) { + assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt"); + } + } + } +} diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index f78e9470..ba4b675e 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0); + let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); let px = &mut out[i * 4..i * 4 + 4]; px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; @@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let px = &mut out[i * 4..i * 4 + 4]; // The baked normal is the base the painted normal details sit on (as in export). let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height)); + let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales); match (n, base) { (Some(t), None) => { for (k, d) in px.iter_mut().take(3).enumerate() { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6c642b75..b43796e8 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,17 +4,20 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, + blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level}; +use crate::curvature_sizes::CurvatureSizes; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -93,6 +96,7 @@ pub struct Inputs<'a> { pub gbuf: &'a UvGBuffer, pub pixels: &'a PixelStore, pub baked: &'a BakedMaps, + pub block_scales: BlockScales, pub preview: Option<&'a StrokePreview>, /// Imported image resources (fill sources). pub images: &'a ImageStore, @@ -203,6 +207,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, + /// The curvature detail sizes a generator with detail reads. + curvature_sizes: Option>, } struct MaskPlan<'a> { @@ -265,36 +271,35 @@ enum Op { Slope { scale: f32, seed: u32 }, } -/// Index (among visible effects) of the last neighbourhood filter of an effect stack, its -/// radius in texels (`res` texels per UV tile across) and what it does. +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { - let texels = |v: f32| (v * res as f32 / 2048.0).max(0.5); - effects - .iter() - .filter(|e| e.visible) - .enumerate() - .filter_map(|(i, e)| match &e.kind { - EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), - EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((i, texels(*radius), Op::Line(direction(*angle)))), - EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { - Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) - } - EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { - Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) - } - EffectKind::Filter(Filter::HighPass { radius }) => Some((i, texels(*radius), Op::HighPass)), - EffectKind::Filter(Filter::EdgeDetect { width }) => Some((i, texels(*width), Op::Edge)), - // Three box passes ramp an edge over about twice their radius. - EffectKind::Filter(Filter::Bevel { width }) => Some((i, texels(*width * 0.5), Op::Bevel)), - EffectKind::Filter(Filter::Glow { radius, amount }) => Some((i, texels(*radius), Op::Glow(*amount))), - EffectKind::Filter(Filter::Mosaic { size }) => Some((i, texels(*size), Op::Mosaic)), - EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { - Some((i, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) - } - _ => None, - }) - .last() + neighbourhood_filters(effects, res).last() +} + +/// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. +fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { + let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5); + effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { + EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), + EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), + EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), + EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { + Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) + } + EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { + Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) + } + EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)), + EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), + // Three box passes ramp an edge over about twice their radius + EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)), + EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), + EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { + Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) + } + _ => None, + }) } /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn @@ -304,6 +309,12 @@ fn direction(angle: f32) -> [f32; 2] { [cs, -sn] } +/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white). +const MAP_GAIN: f32 = 2.0; + +/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength. +const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; + /// Samples along a directional or slope blur at most (beyond, samples spread out). const LINE_SAMPLES: i32 = 24; @@ -421,17 +432,20 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; -/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. -/// Rows (and columns, transposed) blur in parallel. -fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { - let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut v: Vec = data.par_iter().map(fix).collect(); - blur_rows(&mut v, w, r); - let mut t = transpose(&v, w, h); - blur_rows(&mut t, h, r); - data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32); +/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. +pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + blur_rows(&mut fixed, width, radius); + + let mut columns = transpose(&fixed, width, height); + blur_rows(&mut columns, height, radius); + data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } +/// The box blurs `blur` runs along each axis +pub(crate) const BLUR_BOX_PASSES: usize = 3; + /// Three box blurs of radius `r` along every row (`w` long) of `data`. fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { @@ -439,7 +453,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { } data.par_chunks_mut(w).for_each(|row| { let mut tmp = vec![0i64; row.len()]; - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_line(row, &mut tmp, r); row.copy_from_slice(&tmp); } @@ -528,153 +542,205 @@ enum Job<'a> { Content(Channel), } -/// One neighbourhood-filtered field of `layer` over `tiles` plus the filter's reach, built on -/// the fields already computed below it. +/// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`. fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { - let (gw, gh) = (inp.gbuf.width, inp.gbuf.height); let effects = match job { - Job::Mask(m) => &m.effects, + Job::Mask(mask) => &mask.effects, Job::Content(_) => &inp.project.content_layer(id)?.content_effects, }; - let (k, radius, op) = neighbourhood(effects, inp.tile_res())?; - let opacity = effects.iter().filter(|e| e.visible).nth(k).map(|e| e.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - // Clamped: a hostile radius must not overflow the halo and window arithmetic. - let r = radius.round().clamp(1.0, gw.max(gh) as f32) as u32; - // Three box passes reach 3r texels, the other filters r (and a texel for bilinear samples). - let blurs = matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)); - let reach = if blurs { 3 * r } else { r + 1 }; - let halo = reach.div_ceil(TILE); - let (tx0, ty0) = tiles.iter().fold((u32::MAX, u32::MAX), |(a, b), t| (a.min(t.0), b.min(t.1))); - let (tx1, ty1) = tiles.iter().fold((0, 0), |(a, b), t| (a.max(t.0), b.max(t.1))); - let (rx0, ry0) = (tx0.saturating_sub(halo) * TILE, ty0.saturating_sub(halo) * TILE); - let (rx1, ry1) = (((tx1 + 1 + halo) * TILE).min(gw), ((ty1 + 1 + halo) * TILE).min(gh)); - let (w, h) = (rx1.saturating_sub(rx0), ry1.saturating_sub(ry0)); - if w == 0 || h == 0 { - return None; + let filters: Vec<(usize, f32, Op)> = neighbourhood_filters(effects, inp.tile_res()).collect(); + let longest_side = inp.gbuf.width.max(inp.gbuf.height); + + // Each filter's region also holds what every filter above it reads around the tiles + let mut margins: Vec = filters.iter().map(|&(_, radius, op)| filter_extent(radius, op, longest_side).1.div_ceil(TILE)).collect(); + for index in (0..margins.len().saturating_sub(1)).rev() { + margins[index] += margins[index + 1]; } + + let mut previous: Option<(usize, Field)> = None; + for (&filter, &margin) in filters.iter().zip(&margins) { + let region = region_around(inp, tiles, margin)?; + let start = previous.as_ref().map(|(index, field)| (*index, field)); + let filtered = filter_region(inp, channels, below, id, job, effects, filter, region, start)?; + previous = Some((filter.0, filtered)); + } + previous.map(|(_, field)| field) +} + +/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set. +fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32) -> Option<(u32, u32, u32, u32)> { + let (first_x, first_y) = tiles.iter().fold((u32::MAX, u32::MAX), |(min_x, min_y), tile| (min_x.min(tile.0), min_y.min(tile.1))); + let (last_x, last_y) = tiles.iter().fold((0, 0), |(max_x, max_y), tile| (max_x.max(tile.0), max_y.max(tile.1))); + let (x0, y0) = (first_x.saturating_sub(margin) * TILE, first_y.saturating_sub(margin) * TILE); + let (x1, y1) = (((last_x + 1 + margin) * TILE).min(inp.gbuf.width), ((last_y + 1 + margin) * TILE).min(inp.gbuf.height)); + let (w, h) = (x1.saturating_sub(x0), y1.saturating_sub(y0)); + (w > 0 && h > 0).then_some((x0, y0, w, h)) +} + +/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads. +fn filter_extent(radius: f32, op: Op, longest_side: u32) -> (u32, u32) { + // Clamped so a hostile radius can't overflow the region arithmetic + let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; + + // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel + let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; + (radius_texels, reach) +} + +/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples). +fn is_box_blur(op: Op) -> bool { + matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)) +} + +/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. +#[allow(clippy::too_many_arguments)] +fn filter_region( + inp: &Inputs, + channels: &[Channel], + below: &Fields, + id: LayerId, + job: Job, + effects: &[Effect], + (index, radius, op): (usize, f32, Op), + (rx0, ry0, w, h): (u32, u32, u32, u32), + start: Option<(usize, &Field)>, +) -> Option { + let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height)); let comps = match job { Job::Mask(_) => 1, Job::Content(_) => 4, }; - // Evaluate the stack before the filter, tile by tile (content premultiplied by coverage). + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + let (rx1, ry1) = (rx0 + w, ry0 + h); let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect(); let parts: Vec> = region_tiles .par_iter() .map(|&(tx, ty)| { let full = anchor_plan(inp, id, channels, tx, ty, Some(below)); - let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty)); + let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); let mut mask = None; let mut nodes = Vec::new(); match job { - Job::Mask(m) => { - let Some(mut mp) = mask_plan(inp, id, m, tx, ty, None) else { return Vec::new() }; - mp.effects.truncate(k); - mask = Some(mp); + Job::Mask(layer_mask) => { + let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() }; + + mask_stack.effects.truncate(index); + mask_stack.start = start; + mask = Some(mask_stack); } - Job::Content(ch) => { - nodes = plan(inp, &[id], &[ch], tx, ty, 0, Some(below)); - if let Some(c) = nodes.first_mut().and_then(|n| n.chans.first_mut()) { - c.effects.truncate(k); - c.start = None; + Job::Content(channel) => { + nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below)); + if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + chan.effects.truncate(index); + chan.start = start; } } } tile_texels(inp.gbuf, tx, ty) - .map(|(x, y, o)| { - let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); + .map(|(x, y, offset)| { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); if !full.is_empty() { - tex.anchors_below(&full, id); + texel.anchors_below(&full, id); } - let v = match (&mask, nodes.first()) { - (Some(mp), _) => [tex.mask(mp), 0.0, 0.0, 0.0], - (None, Some(n)) => match n.chans.first().and_then(|c| tex.content(&n.content, c)) { - Some((v, cov)) => [v[0] * cov, v[1] * cov, v[2] * cov, cov], + let value = match (&mask, nodes.first()) { + (Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0], + (None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) { + Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov], None => [0.0; 4], }, (None, None) => [0.0; 4], }; - (x, y, v) + (x, y, value) }) .collect() }) .collect(); - // Scatter into the region, a row of tiles at a time (the region is tile aligned). - let n = (w * h) as usize; - let mut orig = vec![0.0f32; n * comps]; - let mut cover = vec![0.0f32; n]; + + // Scatter into the region, a row of tiles at a time (the region is tile aligned) + let texel_count = (w * h) as usize; + let mut orig = vec![0.0f32; texel_count * comps]; + let mut cover = vec![0.0f32; texel_count]; let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize; let band = (TILE * w) as usize; orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| { - for &(x, y, v) in row.iter().flatten() { - let i = (((y - ry0) % TILE) * w + (x - rx0)) as usize; - if let (Some(c), Some(px)) = (cover.get_mut(i), orig.get_mut(i * comps..(i + 1) * comps)) { - *c = 1.0; - px.copy_from_slice(&v[..comps]); + for &(x, y, value) in row.iter().flatten() { + let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) { + *covered = 1.0; + pixel.copy_from_slice(&value[..comps]); } } }); - // High pass centers on the channel's mid value (0 for signed channels like height). + + // High pass centers on the channel's mid value (0 for signed channels like height) let mid = match job { - Job::Content(ch) if ch.kind() == ChannelKind::Signed => 0.0, + Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; - // The filter at the radius of a tile filling `scale` of its atlas block (a smaller tile has - // fewer texels per UV unit, so its filters reach fewer texels). + + // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); - let r = neighbourhood(effects, res).map_or(r, |(_, radius, _)| radius.round().clamp(1.0, r as f32) as u32); - if !blurs { - return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, res, opacity); + let scaled_radius = neighbourhood_filters(effects, res) + .find(|filter| filter.0 == index) + .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); + if !is_box_blur(op) { + return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity); } - // Weighted so uncovered texels don't bleed in. - let (wu, hu, ru) = (w as usize, h as usize, r as usize); + + // Weighted so uncovered texels don't bleed in + let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, wu, hu, ru); + blur(&mut weights, width, height, blur_radius); let mut data = orig.clone(); - for p in 0..comps { - let mut vals: Vec = orig.par_chunks(comps).map(|px| px.get(p).copied().unwrap_or(0.0)).collect(); - blur(&mut vals, wu, hu, ru); - data.par_chunks_mut(comps).zip(vals.par_iter()).zip(weights.par_iter()).for_each(|((px, v), wt)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept). - let cov = if comps == 4 { px.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *wt > 1e-6 - && let Some(slot) = px.get_mut(p) + for component in 0..comps { + let mut sums: Vec = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, width, height, blur_radius); + data.par_chunks_mut(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the mid value is too (coverage itself is kept) + let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > 1e-6 + && let Some(slot) = pixel.get_mut(component) { - let (o, blurred) = (*slot, v / wt); - let filtered = match op { - Op::Blur(Some(amount)) => o + amount * (o - blurred), - Op::HighPass if p < 3 => o - blurred + mid * cov, - // Away from 0 by at most the value itself: 0 at the edge, full inside. - Op::Bevel if p < 3 => o.signum() * o.abs().min((2.0 * blurred * o.signum() - o.abs()).max(0.0)), - Op::Glow(amount) if p < 3 => o + amount * blurred, - Op::HighPass | Op::Bevel | Op::Glow(_) => o, + let (original, blurred) = (*slot, sum / weight); + let result = match op { + Op::Blur(Some(amount)) => original + amount * (original - blurred), + Op::HighPass if component < 3 => original - blurred + mid * cov, + // Away from 0 by at most the value itself: 0 at the edge, full inside + Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), + Op::Glow(amount) if component < 3 => original + amount * blurred, + Op::HighPass | Op::Bevel | Op::Glow(_) => original, _ => blurred, }; - *slot = o + (filtered - o) * opacity; + *slot = original + (result - original) * opacity; } }); } data }; - // Each block keeps the result at its tile's scale (blocks are TILE aligned). + + // Each block keeps the result at its tile's scale (blocks are TILE aligned) let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); let mut levels: Vec = (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); levels.sort_by(f32::total_cmp); levels.dedup(); - let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(f, r)| (*f, r)); + let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); let mut data = filtered(first); for &scale in rest { let other = filtered(scale); let row = w as usize * comps; data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { - for (x, (d, s)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { + for (x, (target, source)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { - d.copy_from_slice(s); + target.copy_from_slice(source); } } }); } + unpremultiply(&mut data, comps); Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) } @@ -708,28 +774,53 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if tiles.is_empty() || inp.gbuf.width == 0 { return out; } - let res = inp.gbuf.width; + + let working_width = inp.gbuf.width; let mut order = Vec::new(); draw_order(inp.project, list, 0, &mut order); + prepare_curvature_sizes(inp, &order); + for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; - if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some()) - && let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles) + + if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) + && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) { - out.insert(FieldKey::Mask(id), f); + out.insert(FieldKey::Mask(id), filtered); } - if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() { + + if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } - for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) { - if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) { - out.insert(FieldKey::Content(id, *ch), f); + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); } } } out } +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { + let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); + let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + prepare_mask_curvature_sizes(inp, masks); +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { + if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + *slot |= in_use; + } + } + } + CurvatureSizes::of(inp, &needed); +} + struct Node<'a> { id: LayerId, content: Content<'a>, @@ -747,21 +838,26 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() - .filter(|e| e.visible) - .map(|e| { - let (img, target) = match channel { - Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), - None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), + .filter(|effect| effect.visible) + .map(|effect| { + let (image, target) = match channel { + Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), + None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), + }; + let curvature_sizes = match &effect.kind { + EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + _ => None, }; EffectPlan { - kind: &e.kind, - blend: e.blend, - opacity: e.opacity, - data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, + kind: &effect.kind, + blend: effect.blend, + opacity: effect.opacity, + data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), + curvature_sizes, } }) .collect() @@ -1043,7 +1139,11 @@ impl<'a, 'b> Texel<'a, 'b> { } fn baked(&self, m: BakedMap) -> Option { - self.inp.baked.scalar(m, self.x, self.y, (self.res, self.inp.gbuf.height)) + self.baked_color(m).map(|value| value[0]) + } + + fn baked_color(&self, map: BakedMap) -> Option<[f32; 3]> { + self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its @@ -1110,94 +1210,142 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, g: &Generator) -> f32 { - let c = self.coords(); - let s = match g.kind { - GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5), - GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), - GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let coords = self.coords(); + let signal = match (generator.kind, &generator.detail) { + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), + (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let th = 1.0 - g.level.clamp(0.0, 1.0); - let soft = g.softness.max(1e-3); - let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + let signal = if generator.noise_amount > 0.0 { + let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); + if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { + // Break up curvature without inventing edges or cavities on a flat surface + let neutral = if detail.mode == CurvatureMode::Raw { 0.5 } else { 0.0 }; + neutral + (signal - neutral) * (1.0 - noise * generator.noise_amount).max(0.0) + } else { + signal + (noise - 0.5) * generator.noise_amount + } + } else { + signal + }; + + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(1e-3); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + let value = ramp * ramp * (3.0 - 2.0 * ramp); + if generator.invert { 1.0 - value } else { value } } - fn mask(&mut self, m: &MaskPlan) -> f32 { - let mut v = m.background; - let mut skip = 0; - if let Some((k, field)) = m.start - && let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied()) - { - v = f; - skip = k + 1; + /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let combine = |edges: f32, cavities: f32| match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + }; + + // Without curvature to read the texel is flat: no edges or cavities + let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; + + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; + + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); + let blurred = |index: usize| { + curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) + }; + let (mut edges, mut cavities) = (0.0f32, 0.0f32); + for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { + let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; + + let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size }; + let weight = weight.clamp(0.0, 1.0); + edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0)); + cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - for e in m.effects.iter().skip(skip) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + + combine(edges, cavities) + } + + fn mask(&mut self, plan: &MaskPlan) -> f32 { + let mut value = plan.background; + let mut skip = 0; + if let Some((filtered_index, field)) = plan.start + && let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied()) + { + value = filtered; + skip = filtered_index + 1; + } + + for effect in plan.effects.iter().skip(skip) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (mut pv, mut cov) = match e.data.as_deref() { - Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))), + let (mut painted, mut cov) = match effect.data.as_deref() { + Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; - if e.preview - && let Some(p) = self.inp.preview + if effect.preview + && let Some(preview) = self.inp.preview { - let a = (self.stroke * p.opacity).clamp(0.0, 1.0); - if p.erase { - pv *= 1.0 - a; - cov *= 1.0 - a; + let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + if preview.erase { + painted *= 1.0 - stroke; + cov *= 1.0 - stroke; } else { - pv = p.mask_value * a + pv * (1.0 - a); - cov = a + cov * (1.0 - a); + painted = preview.mask_value * stroke + painted * (1.0 - stroke); + cov = stroke + cov * (1.0 - stroke); } } if cov > 0.0 { - let val = pv / cov.max(1e-5); - v += (blend1(e.blend, v, val) - v) * cov * o; + let layer_value = painted / cov.max(1e-5); + value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity; } } EffectKind::Fill { source, projection } => { - let val = self.source(source, projection, ChannelKind::Scalar)[0]; - v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection); + let fill = self.source(source, projection, ChannelKind::Scalar)[0]; + value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); } - EffectKind::Generator(g) => { - let val = self.generator(g); - v += (blend1(e.blend, v, val) - v) * o; + EffectKind::Generator(generator) => { + let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + value += (blend1(effect.blend, value, generated) - value) * opacity; } - EffectKind::Levels(l) => v += (l.apply(v) - v) * o, - EffectKind::Filter(f) => { - // A mask is gray (HSL only changes its lightness); neighbourhood filters come - // precomputed through `MaskPlan::start`. - let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]); - v += (val - v) * o; + EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter) => { + // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` + let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + value += (filtered - value) * opacity; } EffectKind::ColorSelection { colors, tolerance } => { - let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, (self.res, self.inp.gbuf.height)); - let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); - let val = if hit { 1.0 } else { 0.0 }; - v += (blend1(e.blend, v, val) - v) * o; + let id = self.baked_color(BakedMap::Id); + let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); + let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; + value += (blend1(effect.blend, value, selected) - value) * opacity; } - EffectKind::Compare { op, value, tolerance } => { + EffectKind::Compare { op, value: compared, tolerance } => { let pass = match op { - CompareOp::LesserThan => v < *value, - CompareOp::GreaterThan => v > *value, - CompareOp::WithinTolerance => (v - value).abs() <= *tolerance, + CompareOp::LesserThan => value < *compared, + CompareOp::GreaterThan => value > *compared, + CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, }; - let val = if pass { 1.0 } else { 0.0 }; - v += (val - v) * o; + let result = if pass { 1.0 } else { 0.0 }; + value += (result - value) * opacity; } - // Content-only effects. + // Content-only effects EffectKind::Material(_) | EffectKind::Anchor => {} } } - v.clamp(0.0, 1.0) + value.clamp(0.0, 1.0) } /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` @@ -1835,47 +1983,123 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) written } -/// The mask of layer `id` as an 8-bit grayscale image of `size × size` stretched over the -/// texture set (nearest texel; uncovered texels black). None when the layer has no enabled mask. -pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { - let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; - let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - let all = all_tiles(w, h); - let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: Vec<(u32, u32, Vec)> = all +/// The layer mask as a square grayscale image, using nearest texels and black outside the mesh +/// Returns None without an enabled mask +pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let coordinates = all_tiles(width, height); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + + let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() - .filter_map(|&(tx, ty)| { - let mp = mask_plan(inp, id, mask, tx, ty, Some(&fields))?; - let full = anchor_plan(inp, id, &channels, tx, ty, Some(&fields)); - let mut buf = vec![0u8; TILE_AREA]; - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - tex.anchors_below(&full, id); - } - if let Some(b) = buf.get_mut(o) { - *b = (tex.mask(&mp) * 255.0 + 0.5) as u8; + .map(|&tile| { + let mut values = vec![0u8; TILE_AREA]; + for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) { + if let Some(destination) = values.get_mut(offset) { + *destination = (value * 255.0 + 0.5) as u8; } } - Some((tx, ty, buf)) + (tile, values) }) .collect(); + let size = size.max(1); - let mut out = vec![0u8; (size * size) as usize]; - let lookup: std::collections::HashMap<(u32, u32), &Vec> = tiles.iter().map(|(x, y, b)| ((*x, *y), b)).collect(); + let mut output = vec![0u8; (size * size) as usize]; for y in 0..size { for x in 0..size { - let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = lookup.get(&(sx / TILE, sy / TILE)) - && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) - && let Some(d) = out.get_mut((y * size + x) as usize) + let sample_x = (u64::from(x) * u64::from(width) / u64::from(size)) as u32; + let sample_y = (u64::from(y) * u64::from(height) / u64::from(size)) as u32; + if let Some(tile) = tiles.get(&(sample_x / TILE, sample_y / TILE)) + && let Some(value) = tile.get(((sample_y % TILE) * TILE + sample_x % TILE) as usize) + && let Some(destination) = output.get_mut((y * size + x) as usize) { - *d = *v; + *destination = *value; } } } - Some(out) + Some(output) +} + +/// Mask values at texture-set coordinates, in request order; None without an enabled mask +/// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels +pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let mut output = vec![0.0; texels.len()]; + + // Group valid requests before planning effects, which may resample painted tiles + let mut requested: HashMap<(u32, u32), Vec<(usize, usize)>> = HashMap::new(); + for (index, &(x, y)) in texels.iter().enumerate() { + if x >= inputs.gbuf.width || y >= inputs.gbuf.height { + continue; + } + + let offset = ((y % TILE) * TILE + x % TILE) as usize; + requested.entry((x / TILE, y / TILE)).or_default().push((offset, index)); + } + + if requested.is_empty() { + return Some(output); + } + + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + + // Filters and anchors can depend on texels outside the requested tiles + let fields = neighbourhood_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height)); + let values: Vec<(usize, f32)> = requested + .par_iter_mut() + .flat_map_iter(|(&tile, requests)| { + requests.sort_unstable_by_key(|&(offset, _)| offset); + let groups = requests.chunk_by(|left, right| left.0 == right.0); + let offsets = groups.clone().filter_map(|group| group.first().map(|&(offset, _)| offset)); + mask_tile(inputs, id, mask, &channels, &fields, tile, offsets) + .zip(groups) + .flat_map(|((_, value), group)| group.iter().map(move |&(_, index)| (index, value))) + }) + .collect(); + + for (index, value) in values { + if let Some(destination) = output.get_mut(index) { + *destination = value; + } + } + Some(output) +} + +/// Mask values in offset order, including zeros for uncovered texels so request groups stay aligned +fn mask_tile<'a>( + inputs: &'a Inputs<'a>, + id: LayerId, + mask: &'a Mask, + channels: &[Channel], + fields: &'a Fields, + (tile_x, tile_y): (u32, u32), + offsets: impl Iterator + 'a, +) -> impl Iterator + 'a { + let plan = mask_plan(inputs, id, mask, tile_x, tile_y, Some(fields)); + let anchor_stack = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(fields)); + offsets.map(move |offset| { + let Some(plan) = plan.as_ref() else { return (offset, 0.0) }; + + let x = tile_x * TILE + (offset % TILE as usize) as u32; + let y = tile_y * TILE + (offset / TILE as usize) as u32; + if x >= inputs.gbuf.width || y >= inputs.gbuf.height || inputs.gbuf.tri.get((y * inputs.gbuf.width + x) as usize).is_none_or(|tri| *tri == NO_TRI) { + return (offset, 0.0); + } + + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + if !anchor_stack.is_empty() { + texel.anchors_below(&anchor_stack, id); + } + (offset, texel.mask(plan)) + }) } /// Tiles [`effect_histogram`] samples at most (a million texels). @@ -1913,7 +2137,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u false } }; - let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); // A field covers the bounding box of the tiles it is built for, which for a scattered sample @@ -1990,7 +2214,7 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option< if let Some(l) = solo.layers.get_mut(&id) { l.visible = true; } - let solo_inp = Inputs { project: &solo, preview: None, ..*inp }; + let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let fields = neighbourhood_fields(&solo_inp, &channels, tiles); let out: Vec> = tiles .par_iter() @@ -2067,6 +2291,7 @@ mod tests { gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview, images: &images, bounds: f.mesh.bounds(), @@ -2175,6 +2400,235 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + fn assert_sparse_mask_matches_image(fixture: &Fixture, layer: LayerId, texels: &[(u32, u32)]) -> Option> { + let images = ImageStore::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + let sparse = mask_at(&inputs, layer, texels); + let image = mask_image(&inputs, layer, fixture.gbuf.width); + assert_eq!(sparse.is_some(), image.is_some()); + let values = sparse?; + let image = image?; + assert_eq!(values.len(), texels.len()); + + for (&(x, y), &value) in texels.iter().zip(&values) { + let expected = + if x < fixture.gbuf.width && y < fixture.gbuf.height { f32::from(image[(y * fixture.gbuf.width + x) as usize]) / 255.0 } else { 0.0 }; + assert!((value - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {value} vs {expected}"); + } + Some(values) + } + + #[test] + fn mask_at_reads_the_same_values_as_the_mask_image() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + fixture.gbuf.tri[30 * 128 + 90] = NO_TRI; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let maskless = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let effect = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let pattern = Procedural::new(ProceduralKind::Checker); + mask.effects.push(Effect::new( + effect, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + )); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + + // Cross tile boundaries and include duplicates, a UV hole and invalid coordinates + let texels = [(0, 0), (0, 40), (63, 63), (64, 64), (127, 127), (0, 40), (90, 30), (128, 0), (0, 128), (u32::MAX, u32::MAX)]; + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values.iter().any(|value| *value > 0.99) && values.iter().take(6).any(|value| *value < 0.01)); + assert_eq!(&values[6..], &[0.0; 4]); + assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &[]), Some(Vec::new())); + assert!(assert_sparse_mask_matches_image(&fixture, maskless, &texels).is_none()); + let missing = fixture.project.alloc_id(); + assert!(assert_sparse_mask_matches_image(&fixture, missing, &texels).is_none()); + fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().enabled = false; + assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none()); + } + + #[test] + fn mask_at_ignores_out_of_range_texels_before_resampling_paint() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let paint = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(paint, EffectKind::Paint)); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + fixture.pixels.mask_mut(paint, (32, 32)).set(4, 5, &[u16::MAX; 2]); + + let texels = [(8, 10), (u32::MAX, 0), (0, u32::MAX), (u32::MAX, u32::MAX), (64, 0), (0, 64)]; + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values[0] > 0.5, "valid texels still read resampled paint"); + assert_eq!(&values[1..], &[0.0; 5]); + assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &texels[1..]), Some(vec![0.0; 5])); + } + + #[test] + fn mask_at_preserves_anchors_and_neighbourhood_filters_across_tiles() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind else { panic!("expected a fill layer") }; + + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let upper = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor }, projection: Projection::default() }, + )); + fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let original = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(original.iter().any(|value| *value > 0.99) && original.iter().any(|value| *value < 0.01), "the anchor supplies the checker"); + + for filter in [Filter::Blur { radius: 64.0 }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }] { + let mut filtered = mask.clone(); + filtered.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter))); + fixture.project.layer_mut(upper).unwrap().mask = Some(filtered); + let values = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(values.iter().zip(&original).any(|(value, original)| (value - original).abs() > 0.1), "the filter changes the anchor values"); + } + } + + #[test] + fn a_mask_runs_every_neighbourhood_filter_in_order() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let mut masked = |filters: &[Filter]| { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker.clone(), projection: Projection::default() })); + for filter in filters { + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter.clone()))); + } + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap() + }; + + let warped = masked(std::slice::from_ref(&warp)); + let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0 }, warp]); + assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); + assert!(blurred_then_warped.iter().any(|value| *value > 0.05 && *value < 0.95), "the blur softens the checker before the warp moves it"); + } + + #[test] + fn a_content_stack_runs_every_neighbourhood_filter_in_order() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(layer).unwrap().kind else { panic!("expected a fill layer") }; + + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp)); + let row = |fixture: &Fixture| -> Vec { + let composite = run(fixture, None); + (0..64).map(|x| composite.value(Channel::BaseColor, x, 20)[0]).collect() + }; + let warped = row(&fixture); + + content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + let effects = &mut fixture.project.layer_mut(layer).unwrap().content_effects; + let warp_index = effects.iter().position(|effect| effect.id == warp_effect).unwrap(); + let warp_on_top = effects.remove(warp_index); + effects.push(warp_on_top); + let blurred_then_warped = row(&fixture); + assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); + } + + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); + fixture.project.texture_sets[0].resolution = 256; + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + }; + + // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth + let (ridge, five_texels_away) = (8, 3); + let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); + assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); + } + + #[test] + fn curvature_detail_noise_keeps_flat_areas_neutral() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let texels: Vec<_> = (0..64).map(|x| (x, 32)).collect(); + + for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { + for mode in CurvatureMode::ALL { + let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), ..Generator::new(kind) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + let expected = if mode == CurvatureMode::Raw { 0.5 } else { 0.0 }; + assert!(values.iter().all(|value| (value - expected).abs() < 0.001), "{kind:?} {mode:?} paints noise on flat curvature: {values:?}"); + } + } + } + + #[test] + fn raw_curvature_reads_mid_gray_without_a_curvature_map() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let detail = CurvatureDetail { mode: CurvatureMode::Raw, ..CurvatureDetail::default() }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + + let values = assert_sparse_mask_matches_image(&fixture, layer, &[(32, 32)]).unwrap(); + assert!(values.iter().all(|value| (value - 0.5).abs() < 0.01), "flat curvature is mid gray in raw mode, not black: {values:?}"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); @@ -2433,6 +2887,7 @@ soft {soft:?}" gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: f.mesh.bounds(), @@ -2494,6 +2949,7 @@ soft {soft:?}" gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: f.mesh.bounds(), diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..fe57e611 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -7,7 +7,10 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod baked_maps; pub mod below; +mod curvature_size_level; +pub mod curvature_sizes; pub mod display; pub mod eval; pub mod pattern; @@ -17,6 +20,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_image, pad_tiles, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index cf640e0a..1370c0c0 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -1,9 +1,9 @@ //! Pixel data owned by a document: painted layer channels, painted mask effects and baked mesh //! maps. Everything is copy-on-write, so cloning the store for undo is cheap. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; -use texturecraft_core::{BakedMap, Channel, ChannelKind, LayerId}; +use texturecraft_core::{Channel, ChannelKind, LayerId}; use texturecraft_texel::{TileImage, from_u16, from_u16_signed}; /// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per @@ -56,38 +56,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 { if kind == ChannelKind::Signed { from_u16_signed(v) } else { from_u16(v) } } -/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The -/// width is `resolution`; height follows the output size and UV tile grid -#[derive(Clone, Debug, Default, PartialEq)] -pub struct BakedMaps { - /// Width in texels. - pub resolution: u32, - pub maps: BTreeMap>>, -} - -impl BakedMaps { - /// Height in texels of map `m` (from its length). - pub fn height(&self, m: BakedMap) -> u32 { - self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) - } - - /// Sample the corresponding texel of an image with the supplied output size - pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { - let data = self.maps.get(&map)?; - let width = u64::from(self.resolution.max(1)); - let height = u64::from(self.height(map).max(1)); - let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); - let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); - let component_count = map.components(); - let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; - let texel = data.get(offset..offset.checked_add(component_count)?)?; - Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) - } - - pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { - self.sample(m, x, y, size).map(|v| v[0]) - } -} +pub use crate::baked_maps::BakedMaps; /// A decoded image resource sampled by fills (values in the file's encoding; see `srgb`). #[derive(Clone, Debug, PartialEq)] diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 020a9de0..d7df0258 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -90,7 +90,18 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { } fn inputs<'a>(f: &'a Fixture, ts: usize, images: &'a texturecraft_compose::ImageStore, baked: &'a texturecraft_compose::BakedMaps) -> Inputs<'a> { - Inputs { project: &f.project, ts, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked, preview: None, images, bounds: f.mesh.bounds() } + Inputs { + project: &f.project, + ts, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked, + block_scales: f.project.texture_sets[ts].block_scales(), + preview: None, + images, + bounds: f.mesh.bounds(), + } } fn run(f: &Fixture, ts: usize, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) -> Composite { diff --git a/crates/core/src/bake/curvature_method.rs b/crates/core/src/bake/curvature_method.rs index 2085c85b..32ac645b 100644 --- a/crates/core/src/bake/curvature_method.rs +++ b/crates/core/src/bake/curvature_method.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum CurvatureMethod { - #[default] NormalMap, + #[default] Mesh, } diff --git a/crates/core/src/bake/curvature_settings.rs b/crates/core/src/bake/curvature_settings.rs index d67138b8..66b4e732 100644 --- a/crates/core/src/bake/curvature_settings.rs +++ b/crates/core/src/bake/curvature_settings.rs @@ -1,16 +1,10 @@ use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings}; use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct CurvatureSettings { pub method: CurvatureMethod, pub normal_map: NormalMapCurvatureSettings, pub mesh: MeshCurvatureSettings, } - -impl Default for CurvatureSettings { - fn default() -> Self { - Self { method: CurvatureMethod::NormalMap, normal_map: NormalMapCurvatureSettings::default(), mesh: MeshCurvatureSettings::default() } - } -} diff --git a/crates/core/src/block_scales.rs b/crates/core/src/block_scales.rs new file mode 100644 index 00000000..65b2403e --- /dev/null +++ b/crates/core/src/block_scales.rs @@ -0,0 +1,43 @@ +/// Per-block UV tile scale for working-to-bake coordinates, filter radii, and height slopes +/// Empty when every tile fills its block; see [`crate::TextureSet::tile_scale`] +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BlockScales { + pub(crate) block: u32, + pub(crate) cols: u32, + pub(crate) scales: Vec, +} + +impl BlockScales { + /// Working atlas UV → uniform bake atlas UV, excluding unused portions of tile blocks + pub fn bake_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> { + if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + if self.scales.is_empty() { + return Some(uv); + } + + let block = self.block.max(1) as f32; + let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block]; + let origin = position.map(f32::floor); + let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32); + let local = [(position[0] - origin[0]) / scale, (position[1] - origin[1]) / scale]; + if local.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32]) + } + + /// The scale at atlas texel (x, y) + pub fn at(&self, x: u32, y: u32) -> f32 { + let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); + if bx >= self.cols { + return 1.0; + } + + let index = (by as usize).checked_mul(self.cols as usize).and_then(|index| index.checked_add(bx as usize)); + index.and_then(|index| self.scales.get(index)).copied().unwrap_or(1.0) + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 551c9803..37ce47e8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize}; use crate::{BlendMode, Channel, ChannelKind, lum}; +mod curvature_detail; +mod curvature_mode; + +pub use curvature_detail::CurvatureDetail; +pub use curvature_mode::CurvatureMode; + /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct LayerId(pub u64); @@ -540,17 +546,26 @@ pub struct Generator { /// Direction for `Position` / `Direction` generators (world space). pub direction: [f32; 3], pub invert: bool, + /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, } impl Generator { pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { - GeneratorKind::EdgeWear => (0.6, 0.12, 0.5), + GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), + GeneratorKind::Curvature => (0.5, 0.5, 0.0), GeneratorKind::Dirt => (0.55, 0.25, 0.35), GeneratorKind::ThinAreas => (0.3, 0.2, 0.0), _ => (0.5, 0.25, 0.0), }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false } + let detail = match kind { + GeneratorKind::Curvature => Some(CurvatureDetail::default()), + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), + _ => None, + }; + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } } } @@ -1050,6 +1065,17 @@ impl Effect { mod tests { use super::*; + #[test] + fn curvature_generators_saved_before_detail_sizes_load_without_them() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes"); + + saved.as_object_mut().unwrap().remove("detail"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.detail, None); + assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs new file mode 100644 index 00000000..75c9d36a --- /dev/null +++ b/crates/core/src/layer/curvature_detail.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +use super::curvature_mode::CurvatureMode; + +/// How a curvature generator reads the curvature map: its mode and how much each detail size adds. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CurvatureDetail { + pub mode: CurvatureMode, + /// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first. + pub weights: [f32; CurvatureDetail::SIZES.len()], +} + +impl CurvatureDetail { + /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. + pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; + + /// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly. + pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15]; + + /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. + pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; + + /// How many sizes are blurred copies of the map (all but the first). + pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1; + + /// Which blurred sizes this detail reads: those with a weight above 0. + pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] { + std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0)) + } +} + +impl Default for CurvatureDetail { + fn default() -> Self { + CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS } + } +} diff --git a/crates/core/src/layer/curvature_mode.rs b/crates/core/src/layer/curvature_mode.rs new file mode 100644 index 00000000..a4183e7a --- /dev/null +++ b/crates/core/src/layer/curvature_mode.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; + +/// Which side of the curvature map a curvature generator shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum CurvatureMode { + /// Convex edges white. + #[default] + Edges, + /// Concave cavities white. + Cavities, + /// Edges and cavities both white. + Both, + /// Signed curvature around mid gray (cavities dark, edges light). + Raw, +} + +impl CurvatureMode { + pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw]; + + pub fn label(self) -> &'static str { + match self { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Edges and cavities", + CurvatureMode::Raw => "Raw curvature", + } + } + + /// The mode named `name` (its variant or label, any case). + pub fn parse(name: &str) -> Option { + let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ddaa6045..75ea2405 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -9,6 +9,7 @@ pub mod bake; pub mod blend; +mod block_scales; pub mod channel; pub mod layer; pub mod project; @@ -23,8 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, - LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, + LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, + hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 26d4f6e6..3fe26e04 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; -pub const FORMAT_VERSION: u32 = 1; +pub const FORMAT_VERSION: u32 = 2; /// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; @@ -63,6 +63,9 @@ pub struct TextureSet { /// [`TileGrid`], [`TextureSet::block_resolution`] texels square. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub uv_tiles: Vec, + /// UV tiles excluded from baking; missing entries stay included + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub bake_excluded_tiles: BTreeSet, /// Per-tile resolutions overriding `resolution` (UDIM → texels per side). A tile smaller /// than the atlas block fills the block's top-left corner (see [`TextureSet::to_atlas`]). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] @@ -132,26 +135,7 @@ impl TileGrid { } } -/// The fraction of its atlas block the UV tile of each block fills ([`TextureSet::tile_scale`]): -/// such a tile has fewer texels per UV unit, so filter radii and height slopes shrink with it. -/// Empty (every scale 1) unless a tile is smaller than its block. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct BlockScales { - block: u32, - cols: u32, - scales: Vec, -} - -impl BlockScales { - /// The scale at atlas texel (x, y). - pub fn at(&self, x: u32, y: u32) -> f32 { - let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); - if bx >= self.cols { - return 1.0; - } - self.scales.get(by as usize * self.cols as usize + bx as usize).copied().unwrap_or(1.0) - } -} +pub use crate::block_scales::BlockScales; fn one() -> f32 { 1.0 @@ -176,6 +160,7 @@ impl TextureSet { baked: BTreeSet::new(), visible: true, uv_tiles: Vec::new(), + bake_excluded_tiles: BTreeSet::new(), tile_resolutions: BTreeMap::new(), } } @@ -185,6 +170,10 @@ impl TextureSet { TileGrid::of(&self.uv_tiles) } + pub fn has_enabled_bake_tiles(&self) -> bool { + self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { @@ -406,6 +395,11 @@ pub struct Project { /// it, so parts the file leaves unnamed get the same name (from it) as on import. #[serde(default, skip_serializing_if = "String::is_empty")] pub mesh_file: String, + /// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads + /// it again from there, so edits made to the file since are picked up. Empty when unknown + /// (built-in meshes, web imports, projects saved before it was kept). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub mesh_path: String, pub normal_format: NormalFormat, pub texture_sets: Vec, pub layers: BTreeMap, @@ -423,6 +417,7 @@ impl Project { name: name.into(), mesh: mesh.into(), mesh_file: String::new(), + mesh_path: String::new(), normal_format: NormalFormat::OpenGl, texture_sets: Vec::new(), layers: BTreeMap::new(), diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 708560f0..800efd98 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -20,7 +20,7 @@ fn reference_defaults_cover_common_and_per_map_settings() { "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { - "method": "NormalMap", + "method": "Mesh", "normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0}, "mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": 1.0} }, @@ -54,7 +54,9 @@ fn reference_defaults_cover_common_and_per_map_settings() { } } } + assert_shape(&serde_json::to_value(decoded).unwrap(), &expected); + assert_eq!(BakedMap::ALL.len(), 10); for name in ["color_map", "Color map", "WorldDirection", "world_space_direction"] { assert_eq!(BakedMap::parse(name), None); diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs new file mode 100644 index 00000000..ab559beb --- /dev/null +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -0,0 +1,45 @@ +use super::MergedHigh; +use std::sync::Arc; +use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it +#[derive(Clone, Debug)] +pub struct BakeCageInputs { + pub(super) mesh: Arc, + pub(super) bvh: Arc, + pub(super) material: usize, + pub(super) settings: BakeSettings, + pub(super) high: MergedHigh, + pub(super) cage: Option>, + pub(super) skew: Option>, + pub(super) cage_paint: Option>, +} + +impl BakeCageInputs { + /// The cage the 3D view draws: the bake's ray origins at each triangle corner + pub fn cage_shell(&self) -> Result { + CageShell::new(&self.request()) + } + + /// Where each high-poly vertex sits relative to the bake's transfer rays + pub fn high_poly_reach(&self) -> Result { + HighPolyReach::new(&self.request()) + } + + fn request(&self) -> BakeRequest<'_> { + BakeRequest { + low_base_color: &[], + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings: &self.settings, + high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }), + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: (1, 1), + } + } +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index 260002db..da0e4a97 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -14,6 +14,11 @@ pub struct BakeMeshes { } impl BakeMeshes { + /// Every high poly appended into one mesh, as bakes see it + pub fn merged_high(&self) -> Option<&MergedHigh> { + self.merged.as_ref() + } + pub(crate) fn rebuild(&mut self) { self.merged = (!self.high.is_empty()).then(|| { let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new()); diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 831a7abc..8c942176 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,7 +1,8 @@ use super::MergedHigh; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_compose::BakedMaps; use texturecraft_core::BakeSettings; use texturecraft_geom::{Bvh, Mesh}; @@ -20,6 +21,9 @@ pub struct BakeTask { pub cage_paint: Option>, /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. pub tiles: (u32, u32), + /// Snapshot of tile selection and pixels to retain while the worker runs + pub excluded_tiles: Vec<(u32, u32)>, + pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, } @@ -40,10 +44,9 @@ impl BakeTask { cage_paint: self.cage_paint.as_deref(), tiles: self.tiles, }; - match &self.tracer { - Some(tracer) => bake_on(&request, progress, tracer.as_ref()), - None => bake(&request, progress), - } - .map_err(|e| EngineError::Other(format!("bake failed: {e}"))) + let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref()) + .map_err(|error| EngineError::Other(format!("bake failed: {error}")))?; + super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; + Ok(output) } } diff --git a/crates/engine/src/bake/high_poly_missed.rs b/crates/engine/src/bake/high_poly_missed.rs new file mode 100644 index 00000000..21de6c05 --- /dev/null +++ b/crates/engine/src/bake/high_poly_missed.rs @@ -0,0 +1,23 @@ +use rayon::prelude::*; +use texturecraft_bake::HighPolyReach; + +/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0 +/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked +/// `vertex_count` is the validated high-poly mesh's vertex count +pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32)], only_set: Option, vertex_count: usize) -> Vec { + // Ownership is already assigned by HighPolyReach; other sets must not color the vertex + let sets: Vec<(&HighPolyReach, f32, f32)> = reach + .iter() + .zip(distances) + .enumerate() + .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) + .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) + .collect(); + (0..vertex_count) + .into_par_iter() + .map(|vertex| { + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); + f32::from(u8::from(missed.unwrap_or(false))) + }) + .collect() +} diff --git a/crates/engine/src/bake/layout.rs b/crates/engine/src/bake/layout.rs new file mode 100644 index 00000000..70e4b539 --- /dev/null +++ b/crates/engine/src/bake/layout.rs @@ -0,0 +1,46 @@ +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_bake::BakePaintMap; +use texturecraft_core::TextureSet; +use texturecraft_geom::glam::Vec2; + +use crate::{EngineError, Result}; + +/// Correction paint stays in working coordinates; the worker reads a uniform bake atlas +pub(super) fn paint_for_bake(painted: &Arc, set: &TextureSet) -> Result> { + let Some(grid) = set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) else { + return Ok(painted.clone()); + }; + + painted.validate().map_err(|error| EngineError::Other(error.to_string()))?; + let (width, height) = (painted.width, painted.height); + let mut values = vec![0.0; painted.values.len()]; + values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| { + for (x, value) in row.iter_mut().enumerate() { + let uv = grid.from_atlas([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]); + *value = painted.sample(Vec2::from_array(set.to_atlas(&grid, uv, uv))); + } + }); + Ok(Arc::new(BakePaintMap { width, height, values })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correction_paint_follows_the_same_surface_in_bake_coordinates() { + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let mut paint = BakePaintMap::constant(0.0).resized(128, 64).unwrap(); + paint.paint(&[Vec2::new(0.625, 0.25)], 0.05, 1.0, 1.0, 1.0).unwrap(); + let paint = Arc::new(paint); + let baked = paint_for_bake(&paint, &set).unwrap(); + assert!(paint.sample(Vec2::new(0.625, 0.25)) > 0.99); + assert!(baked.sample(Vec2::new(0.75, 0.5)) > 0.99); + assert_eq!(baked.sample(Vec2::new(0.25, 0.5)), 0.0); + assert_eq!(paint.sample(Vec2::new(0.75, 0.5)), 0.0); + } +} diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake/mesh_map_command.rs similarity index 83% rename from crates/engine/src/bake_cmds.rs rename to crates/engine/src/bake/mesh_map_command.rs index d56a2bc0..b65d6ac8 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -2,10 +2,13 @@ //! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU //! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise. +use super::model_patch; + use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; +use super::{BakeCageInputs, MergedHigh}; use crate::{BakeMesh, BakeTask}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; @@ -13,11 +16,12 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, }; +use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; -pub fn specs() -> Vec { +pub(super) fn specs() -> Vec { vec![ cmd!( "bake.run", @@ -33,7 +37,7 @@ pub fn specs() -> Vec { "Bake settings", [], None, - "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", + "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, patch?: nested BakeSettings fields to update after model (omitted fields stay unchanged, null clears optional fields), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", always, settings ), @@ -88,8 +92,12 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { - pub fn bake_task(&self, ts: usize) -> Result { - let set = self.doc.project.texture_set(ts)?; + pub fn bake_task(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + if !set.has_enabled_bake_tiles() { + return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); + } + let needs_low_color = set.bake.maps.opacity.is_enabled || (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) { @@ -106,20 +114,22 @@ impl Session { } else { Arc::new(Vec::new()) }; - let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile { - Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone()) - } else { - None - }; - let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned()); - let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned()); - let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); + + let high = self.bake_high(texture_set)?; + let cage = self.bake_cage(texture_set, high.is_some())?; + let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?; + let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?; + + let grid = set.tile_grid(); + let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; + let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, - ts, - mesh: self.mesh.clone(), + ts: texture_set, + mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -128,10 +138,67 @@ impl Session { skew, cage_paint, tiles, + excluded_tiles, + previous_maps, tracer, }) } + /// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file + pub fn bake_cage_inputs(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + let Some(high) = self.bake_high(texture_set)? else { return Ok(None) }; + let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) }; + + Ok(Some(BakeCageInputs { + mesh: self.bake_mesh(texture_set)?, + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?, + cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?, + })) + } + + /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly + fn bake_high(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + } + + /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage + fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile { + return Ok(None); + } + + let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + Ok(Some(cage.mesh.clone())) + } + + /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly + fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() + } + + /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas + fn bake_mesh(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }) + } + /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); @@ -364,7 +431,7 @@ pub fn settings_params(settings: &BakeSettings) -> Value { /// Apply only the bake parameters supplied by the caller fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> { - // Keep the current command limits until the reference controls are integrated + // Preserve the legacy flat-parameter limits for existing callers const MAX_DILATION_PIXELS: u32 = 256; const MAX_SUFFIX_CHARS: usize = 64; @@ -378,6 +445,14 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> } } + if let Some(patch) = params.get("patch") { + let mut model = json!(settings); + model_patch::apply_patch(&mut model, patch, command)?; + let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; + validate_model_settings(&updated, command)?; + *settings = updated; + } + if let Some(resolution) = u64p(params, "resolution") { settings.common.resolution = u32::try_from(resolution) .ok() @@ -604,8 +679,15 @@ fn settings(session: &mut Session, params: &Value) -> Result { } fn bake_run(session: &mut Session, params: &Value) -> Result { - let next = updated_settings(session, params, "bake.run")?; + let next: Vec<_> = updated_settings(session, params, "bake.run")? + .into_iter() + .filter(|(index, _)| session.doc.project.texture_sets.get(*index).is_some_and(|texture_set| texture_set.has_enabled_bake_tiles())) + .collect(); let sets: Vec = next.iter().map(|(index, _)| *index).collect(); + if sets.is_empty() { + return Ok(json!({"baked": [], "tracer": []})); + } + let cpu = boolp(params, "cpu") == Some(true); let tracers = session.edit("Bake mesh maps", |session| { let mut tracers = Vec::with_capacity(next.len()); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 075943b3..fa3403df 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,11 +1,35 @@ +//! Baking tasks, commands, settings helpers, and the mesh-map baking API + +mod bake_cage_inputs; mod bake_mesh; mod bake_meshes; mod bake_task; +mod high_poly_missed; +mod layout; mod merged_high; +mod mesh_map_command; +mod model_patch; +mod paint_command; +mod preserve_tiles; +mod tile_command; +pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; +pub use high_poly_missed::high_poly_missed; pub use merged_high::MergedHigh; +pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; +pub use model_patch::settings_patch; +pub use texturecraft_bake::*; + +use crate::CommandSpec; type MaterialColors = std::sync::Arc>>>; + +pub(crate) fn specs() -> Vec { + let mut commands = mesh_map_command::specs(); + commands.extend(paint_command::specs()); + commands.extend(tile_command::specs()); + commands +} diff --git a/crates/engine/src/bake/model_patch.rs b/crates/engine/src/bake/model_patch.rs new file mode 100644 index 00000000..871d7dc8 --- /dev/null +++ b/crates/engine/src/bake/model_patch.rs @@ -0,0 +1,40 @@ +use serde_json::{Value, json}; +use texturecraft_core::BakeSettings; + +use crate::Result; +use crate::commands::bad; + +/// Only the changed fields, using the persisted model's names and enum values +pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value { + changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({})) +} + +fn changed_fields(before: &Value, after: &Value) -> Option { + if before == after { + return None; + } + + if let (Some(before), Some(after)) = (before.as_object(), after.as_object()) { + let fields = after + .iter() + .filter_map(|(name, value)| changed_fields(before.get(name).unwrap_or(&Value::Null), value).map(|change| (name.clone(), change))) + .collect(); + Some(Value::Object(fields)) + } else { + Some(after.clone()) + } +} + +/// Merge known fields only; null is a value, so optional settings can be cleared +pub(super) fn apply_patch(model: &mut Value, patch: &Value, command: &str) -> Result<()> { + let fields = patch.as_object().ok_or_else(|| bad(command, "bake settings patch must be an object"))?; + for (name, value) in fields { + let target = model.get_mut(name).ok_or_else(|| bad(command, format!("unknown bake setting `{name}`")))?; + if target.is_object() { + apply_patch(target, value, command)?; + } else { + *target = value.clone(); + } + } + Ok(()) +} diff --git a/crates/engine/src/bake_paint_cmds.rs b/crates/engine/src/bake/paint_command.rs similarity index 97% rename from crates/engine/src/bake_paint_cmds.rs rename to crates/engine/src/bake/paint_command.rs index 80cf4852..1bbe2580 100644 --- a/crates/engine/src/bake_paint_cmds.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -6,7 +6,7 @@ use texturecraft_bake::BakePaintMap; use texturecraft_core::BakePaintTarget; use texturecraft_geom::glam::Vec2; -pub fn specs() -> Vec { +pub(super) fn specs() -> Vec { vec![ cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set( session, @@ -65,7 +65,7 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); Ok(()) })?; - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { @@ -76,7 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Ok(()) })?; } - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { @@ -123,7 +123,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) })?; - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs new file mode 100644 index 00000000..27c74ae8 --- /dev/null +++ b/crates/engine/src/bake/preserve_tiles.rs @@ -0,0 +1,54 @@ +use texturecraft_bake::BakeOutput; +use texturecraft_compose::BakedMaps; + +use crate::{EngineError, Result}; + +/// Retain excluded tiles from the worker's snapshot, resampling when output size changes +pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], grid: (u32, u32)) -> Result<()> { + if excluded_tiles.is_empty() { + return Ok(()); + } + + let size = (output.resolution, output.height); + let tile_width = size.0 / grid.0.max(1); + let tile_height = size.1 / grid.1.max(1); + for (map, pixels) in &mut output.maps { + let components = map.components(); + for &(column, row) in excluded_tiles { + for y in row * tile_height..(row + 1) * tile_height { + let first = (y as usize * size.0 as usize + column as usize * tile_width as usize) * components; + let last = first + tile_width as usize * components; + let row_pixels = pixels.get_mut(first..last).ok_or_else(|| EngineError::Other("excluded UV tile lies outside the baked pixels".into()))?; + for (offset, pixel) in row_pixels.chunks_exact_mut(components).enumerate() { + let value = previous.sample(*map, column * tile_width + offset as u32, y, size).unwrap_or_else(|| map.neutral()); + for (component, value) in pixel.iter_mut().zip(value) { + *component = value; + } + } + } + } + } + + // Keep unchecked map outputs too when a partial bake changes the atlas dimensions + for map in previous.maps.keys() { + if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) { + continue; + } + + let components = map.components(); + let count = (size.0 as usize) + .checked_mul(size.1 as usize) + .and_then(|count| count.checked_mul(components)) + .ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?; + for y in 0..size.1 { + for x in 0..size.0 { + let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral()); + pixels.extend(value.into_iter().take(components)); + } + } + output.maps.insert(*map, pixels); + } + Ok(()) +} diff --git a/crates/engine/src/bake/tile_command.rs b/crates/engine/src/bake/tile_command.rs new file mode 100644 index 00000000..766a4b84 --- /dev/null +++ b/crates/engine/src/bake/tile_command.rs @@ -0,0 +1,42 @@ +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad, boolp, u64p}; +use crate::set_cmds::ts_param; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.tile.set", + "Include UV tile in bake", + [], + None, + "{ts?, tile: UDIM number, enabled: bool} → {ts, tile, enabled}; excluded tiles keep existing baked pixels", + always, + set_enabled + )] +} + +fn set_enabled(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.tile.set"; + let texture_set = ts_param(session, params, COMMAND)?; + let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` must be a UDIM number"))?; + let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` must be true or false"))?; + let settings = session.doc.project.texture_set(texture_set)?; + if !settings.uv_tiles.contains(&tile) { + return Err(bad(COMMAND, format!("texture set {} has no UV tile {tile}", settings.name))); + } + + let was_enabled = !settings.bake_excluded_tiles.contains(&tile); + if enabled != was_enabled { + session.edit("Include UV tile in bake", |session| { + let settings = session.doc.project.texture_set_mut(texture_set)?; + if enabled { + settings.bake_excluded_tiles.remove(&tile); + } else { + settings.bake_excluded_tiles.insert(tile); + } + Ok(()) + })?; + } + Ok(json!({"ts": texture_set, "tile": tile, "enabled": enabled})) +} diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index af94815c..9c44c06e 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -28,6 +28,15 @@ pub fn specs() -> Vec { ), cmd!("camera.remove", "Remove camera", [], None, "{index? | name?}", has_cameras, remove), cmd!("camera.rename", "Rename camera", [], None, "{index? | name?, to}", has_cameras, rename), + cmd!("camera.bookmark1", "Go to camera 1", ["Viewport"], Some("Ctrl+1"), "{}", always, |s, _| bookmark(s, 0)), + cmd!("camera.bookmark2", "Go to camera 2", ["Viewport"], Some("Ctrl+2"), "{}", always, |s, _| bookmark(s, 1)), + cmd!("camera.bookmark3", "Go to camera 3", ["Viewport"], Some("Ctrl+3"), "{}", always, |s, _| bookmark(s, 2)), + cmd!("camera.bookmark4", "Go to camera 4", ["Viewport"], Some("Ctrl+4"), "{}", always, |s, _| bookmark(s, 3)), + cmd!("camera.bookmark5", "Go to camera 5", ["Viewport"], Some("Ctrl+5"), "{}", always, |s, _| bookmark(s, 4)), + cmd!("camera.bookmark6", "Go to camera 6", ["Viewport"], Some("Ctrl+6"), "{}", always, |s, _| bookmark(s, 5)), + cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)), + cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)), + cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)), cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at), ] } @@ -132,6 +141,14 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(crate::view_cmds::camera_json(s)) } +/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order. +fn bookmark(s: &mut Session, slot: usize) -> Result { + if slot >= s.doc.project.cameras.len() { + return Err(bad("camera.bookmark", "no saved camera in that slot (see camera.list)")); + } + select(s, &json!({ "index": slot })) +} + fn remove(s: &mut Session, p: &Value) -> Result { let i = which(s, "camera.remove", p)?; s.edit("Remove camera", |s| { @@ -202,6 +219,25 @@ mod tests { assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable"); } + #[test] + fn number_shortcuts_go_to_the_first_nine_cameras() { + let mut s = session(); + assert!(execute(&mut s, "camera.bookmark1", &Value::Null).is_err(), "no cameras yet"); + execute(&mut s, "camera.set", &json!({"yaw": 30})).unwrap(); + let first = s.camera; + execute(&mut s, "camera.add", &json!({"name": "A"})).unwrap(); + execute(&mut s, "camera.orbit", &json!({"dx": 50})).unwrap(); + execute(&mut s, "camera.add", &json!({"name": "B"})).unwrap(); + execute(&mut s, "camera.bookmark1", &Value::Null).unwrap(); + assert_eq!(s.camera, first); + execute(&mut s, "camera.bookmark2", &Value::Null).unwrap(); + assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], 1); + assert!(execute(&mut s, "camera.bookmark3", &Value::Null).is_err(), "empty slot"); + let ids: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.bookmark")).collect(); + assert_eq!(ids.len(), 9); + assert!(ids.iter().all(|c| c.shortcut.is_some())); + } + #[test] fn cameras_round_trip_through_the_project_file() { let mut s = session(); diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs new file mode 100644 index 00000000..2b9f9eaf --- /dev/null +++ b/crates/engine/src/color_selection_cmds.rs @@ -0,0 +1,160 @@ +//! Color selection effects: the ID colors they select, picked from the ID mesh map + +use serde_json::{Value, json}; +use texturecraft_core::{BakedMap, EffectKind, LayerId}; +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::surface_at; + +use crate::commands::{CommandSpec, bad, f32p, has_layer}; +use crate::mask_cmds::effect_id; +use crate::tool_cmds::viewport_of; +use crate::{Result, Session, cmd}; + +/// Most colors one color selection holds; an ID map rarely has more distinct parts +const MAX_SELECTED_COLORS: usize = 256; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.colorSelection.pick", + "Pick ID color", + [], + None, + "{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point", + has_layer, + pick + )] +} + +/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection +pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> { + if let Some(list) = params.get("colors") { + *colors = colors_param(list)?; + } + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); + } + Ok(()) +} + +/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1 +fn colors_param(list: &Value) -> Result> { + const CMD: &str = "effect.set"; + let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?; + if items.is_empty() || items.len() > MAX_SELECTED_COLORS { + return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors"))); + } + + items + .iter() + .map(|item| match finite_numbers::<3>(item) { + Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)), + _ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")), + }) + .collect() +} + +/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection +fn pick(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "effect.colorSelection.pick"; + let effect = effect_id(session, params, CMD)?; + let (owner, color_count) = match session.doc.project.effect(effect) { + Some((owner, found)) => match &found.kind { + EffectKind::ColorSelection { colors, .. } => (owner, colors.len()), + other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))), + }, + None => return Err(bad(CMD, format!("no effect {}", effect.0))), + }; + + let index = params + .get("index") + .filter(|index| !index.is_null()) + .map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer"))) + .transpose()?; + let index = match index { + Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?), + None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))), + None => None, + }; + + let color = id_color_at(session, params, owner)?; + session.edit("Pick ID color", |session| { + let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind { + match index.and_then(|index| colors.get_mut(index)) { + Some(slot) => *slot = color, + None => colors.push(color), + } + } + Ok(()) + })?; + Ok(json!({ "color": color, "index": index.unwrap_or(color_count) })) +} + +/// The ID map color of the texel a color selection on `owner` reads at the picked point +fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> { + const CMD: &str = "effect.colorSelection.pick"; + let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?; + let set = session.doc.project.texture_set(set_index)?; + let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id)); + let Some(baked) = baked else { + return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + }; + + let uv = match params.get("uv") { + Some(uv) => uv_param(uv)?, + None => { + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { + return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`")); + }; + + let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params)) + .ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; + if material != set.material { + return Err(bad(CMD, "that surface belongs to another texture set")); + } + uv + } + }; + + // The same texel the mask evaluates, so a picked color always selects where it was picked + let size = set.size(); + let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32]; + if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) { + return Err(bad(CMD, "that point is outside the texture set's UV space")); + } + baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there")) +} + +/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray +fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> { + let viewport = viewport.max(Vec2::ONE); + let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0); + let ray = session.camera.ray(device, viewport.x / viewport.y); + let sets = &session.doc.project.texture_sets; + let visible = |triangle: u32| { + let material = session.mesh.material_of(triangle as usize).unwrap_or(0); + sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible) + }; + + let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0))) +} + +/// A `[u, v]` param of finite numbers +fn uv_param(uv: &Value) -> Result { + match finite_numbers::<2>(uv) { + Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)), + _ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")), + } +} + +/// Validate the shape before reading components, without allocating for oversized input +fn finite_numbers(list: &Value) -> Option<[f64; N]> { + let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?; + let mut numbers = [0.0; N]; + for (number, item) in numbers.iter_mut().zip(items) { + *number = item.as_f64().filter(|value| value.is_finite())?; + } + Some(numbers) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 94bb350c..d9a31b39 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::color_selection_cmds::specs()); v.extend(crate::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); @@ -65,11 +66,11 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); + v.extend(crate::meshmap_import_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); - v.extend(crate::bake_cmds::specs()); - v.extend(crate::bake_paint_cmds::specs()); + v.extend(crate::bake::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 48d4e8b2..ae2f00b5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -132,7 +132,7 @@ impl Session { fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result>> { let opts = ExportOptions { atlas: true, ..opts }; (0..materials) - .map(|m| match self.doc.project.texture_sets.iter().position(|t| t.material == m) { + .map(|m| match self.texture_set_of_material(m) { Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts), _ => Ok(Vec::new()), }) @@ -331,6 +331,11 @@ mod native { strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required"))) } + /// `path` made absolute (as given when that fails), for [`Project::mesh_path`]. + pub fn absolute(path: &str) -> String { + std::path::absolute(Path::new(path)).map_or_else(|_| path.to_string(), |p| p.display().to_string()) + } + /// Mesh file `path` with the files it references next to it folded in (a `.gltf`'s buffers /// and images, a loose USD layer's textures), ready to import and store in the project. pub fn read_mesh(cmd: &str, path: &str) -> Result { @@ -349,6 +354,7 @@ mod native { } else { let f = read_mesh("file.open", path)?; let mut s = Session::from_mesh_bytes(&f.name, &f.bytes, 2048, &stem_of(path))?; + s.doc.project.mesh_path = absolute(path); s.log.extend(f.warnings); Ok(s) } @@ -367,8 +373,10 @@ mod native { } #[cfg(not(target_arch = "wasm32"))] -pub use native::{open_path, read_mesh}; +pub use native::{absolute, open_path, read_mesh}; +/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`, +/// remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] fn new_from_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "mesh", "file.new")?; @@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result { let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048); let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?; + next.doc.project.mesh_path = native::absolute(path); next.log.extend(f.warnings); if let Some(t) = &template { next.apply_template(t); @@ -414,14 +423,28 @@ fn save_copy(s: &mut Session, p: &Value) -> Result { native::save_to(s, &path, false) } +/// `file.reimportMesh {path?, preserveStrokes?}`: reimport from `path`, or from the project's own +/// copy of the mesh when there is none. A path given is remembered as the project's mesh path. +/// The remembered path is never read implicitly (a project file could point it anywhere on the +/// host); callers that may read host files pass [`Session::remembered_mesh_path`] as `path`. #[cfg(not(target_arch = "wasm32"))] fn reimport(s: &mut Session, p: &Value) -> Result { - let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?; - s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false)) + let path = strp(p, "path"); + let file = path.map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?; + let reply = s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))?; + if let Some(path) = path { + s.doc.project.mesh_path = native::absolute(path); + } + Ok(reply) } #[cfg(not(target_arch = "wasm32"))] impl Session { + /// The file the mesh was imported from, when it is still there: what Reimport mesh reads again. + pub fn remembered_mesh_path(&self) -> Option<&str> { + Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file()) + } + /// Replace the mesh with `file` (or re-read the project's own copy) and keep the project: /// texture sets map by material index. Nothing changes unless the new mesh fits the project. /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies @@ -448,6 +471,8 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.modified = true; + next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); self.switch_to(next); Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) @@ -610,6 +635,59 @@ fn close(s: &mut Session, _: &Value) -> Result { mod tests { use super::*; + /// Reimport mesh reads the mesh file again from where it was imported, so a change saved to + /// the file since shows up (it used to re-read the project's own copy and change nothing). + #[test] + fn reimport_picks_up_changes_saved_to_the_mesh_file() { + let dir = std::env::temp_dir().join(format!("tc_reimport_disk_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("tri.obj"); + let obj = |z: f32| { + format!( + "v -1 -1 {z} +v 1 -1 0 +v 1 1 0 +vt 0 0 +vt 1 0 +vt 1 1 +f 1/1 2/2 3/3 +" + ) + }; + std::fs::write(&file, obj(0.0)).unwrap(); + let path = file.display().to_string(); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap(); + let low = |s: &Session| s.mesh.positions.iter().map(|p| p.z.abs()).fold(0.0_f32, f32::max); + assert_eq!(low(&s), 0.0); + // Edit the file, save the project, reopen it, then reimport with no path. + std::fs::write(&file, obj(0.5)).unwrap(); + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(low(&reopened), 0.0, "the project still holds the old copy"); + // A command without a path never reads the remembered host path (automation allows it). + crate::execute(&mut reopened, "file.reimportMesh", &Value::Null).unwrap(); + assert_eq!(low(&reopened), 0.0, "no path: the project's own copy"); + let remembered = reopened.remembered_mesh_path().map(str::to_string).expect("the imported file is remembered"); + crate::execute(&mut reopened, "file.reimportMesh", &json!({ "path": remembered })).unwrap(); + assert!(low(&reopened) > 0.0, "the edited file must be read again"); + // The file gone: nothing is remembered, so the UI asks for one. + std::fs::remove_file(&file).unwrap(); + assert!(reopened.remembered_mesh_path().is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn reimporting_a_saved_project_marks_it_modified() { + let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n"; + let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap(); + let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap(); + assert!(!saved.modified); + let project = saved.project_id; + crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap(); + assert!(saved.modified, "reimport must trigger the unsaved-changes prompt"); + assert_eq!(saved.project_id, project, "a reimport stays the same project"); + } + #[test] fn export_mesh_writes_obj_by_default_and_textured_glb() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs new file mode 100644 index 00000000..b30b2452 --- /dev/null +++ b/crates/engine/src/fill_hit_test.rs @@ -0,0 +1,83 @@ +//! Which polygons a polygon fill box selects. + +use serde::{Deserialize, Serialize}; +use texturecraft_geom::glam::Vec2; + +/// How a polygon fill box decides whether it selects a polygon +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillHitTest { + /// Any part of the polygon inside the box or crossing it + #[default] + Intersection, + /// The polygon's center point inside the box + ContainedCenter, +} + +impl FillHitTest { + /// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners) + pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool { + match self { + FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)), + FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()), + } + } +} + +/// Area-weighted center of the triangles (their corners' mean when they have no area) +fn center(triangles: &[[Vec2; 3]]) -> Option { + if triangles.is_empty() { + return None; + } + + // One pass: total area, area-weighted centroids and plain centroids + let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| { + let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = (corners[0] + corners[1] + corners[2]) / 3.0; + (total_area + area, weighted + centroid * area, centroids + centroid) + }); + Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 }) +} + +/// Separating axis test of a triangle against an axis-aligned box +fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool { + let triangle_low = corners[0].min(corners[1]).min(corners[2]); + let triangle_high = corners[0].max(corners[1]).max(corners[2]); + if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() { + return false; + } + + let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)]; + (0..3).all(|edge| { + let axis = (corners[(edge + 1) % 3] - corners[edge]).perp(); + let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point)))); + let (triangle_min, triangle_max) = span(&corners); + let (box_min, box_max) = span(&box_corners); + triangle_max >= box_min && box_max >= triangle_min + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; + + #[test] + fn intersection_selects_any_overlap() { + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge"); + } + + #[test] + fn contained_center_selects_only_by_the_center() { + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside"); + assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); + } + + #[test] + fn a_polygon_center_weighs_its_triangles_by_area() { + let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]]; + assert_eq!(center(&square), Some(Vec2::ONE)); + assert_eq!(center(&[]), None); + } +} diff --git a/crates/engine/src/fill_mode.rs b/crates/engine/src/fill_mode.rs new file mode 100644 index 00000000..f314562e --- /dev/null +++ b/crates/engine/src/fill_mode.rs @@ -0,0 +1,17 @@ +//! What one polygon fill target grows to. + +use serde::{Deserialize, Serialize}; + +/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillMode { + /// The triangle itself + #[default] + Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, + /// The UV island: triangles sharing edges in UV space + UvIsland, + /// The connected geometry: triangles sharing edges by position + Mesh, +} diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index f3168c9d..7856f565 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -19,6 +19,20 @@ pub struct FilterDef { pub mask: bool, } +impl FilterDef { + /// Whether it builds a filter effect (levels and material finishes are effect types of their own) + pub fn is_filter_effect(&self) -> bool { + matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_))) + } +} + +/// The library entries that build filter effects, in shelf order, worked out once +pub fn filter_effects() -> &'static [&'static FilterDef] { + static FILTER_EFFECTS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect()); + &FILTER_EFFECTS +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..00d54d7b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -2,7 +2,7 @@ //! without a screenshot. use serde_json::{Value, json}; -use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source}; use crate::Session; use crate::session::StackTarget; @@ -34,38 +34,49 @@ fn fill_json(f: &Fill) -> Value { } /// A mask or content (`content`) effect. -fn effect_json(s: &Session, e: &Effect, content: bool) -> Value { - let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity }); - match &e.kind { - EffectKind::Generator(g) => { - ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }) +fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { + let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity }); + let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); + let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::(); + + match &effect.kind { + EffectKind::Generator(generator) => out["generator"] = generator_json(generator), + EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]), + EffectKind::ColorSelection { colors, tolerance } => { + out["colors"] = json!(colors); + out["tolerance"] = json!(tolerance); } - EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]), EffectKind::Path(paths) => { - ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::>()); - ej["tiles"] = json!(if content { - s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::() - } else { - s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0) - }); + out["paths"] = json!( + paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::>() + ); + out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() }); } - EffectKind::Paint if content => { - ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::()) - } - EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)), - EffectKind::Fill { source, .. } => ej["source"] = source_json(source), - EffectKind::Material(f) => ej["fill"] = fill_json(f), - EffectKind::Filter(f) => { - ej["filter"] = json!(f); - match f { - Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]), - Filter::Blur { radius } => ej["radius"] = json!(radius), + EffectKind::Paint if content => out["tiles"] = json!(content_tiles()), + EffectKind::Paint => out["tiles"] = json!(mask_tiles()), + EffectKind::Fill { source, .. } => out["source"] = source_json(source), + EffectKind::Material(fill) => out["fill"] = fill_json(fill), + EffectKind::Filter(filter) => { + out["filter"] = json!(filter); + match filter { + Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]), + Filter::Blur { radius } => out["radius"] = json!(radius), _ => {} } } _ => {} } - ej + out +} + +/// A generator's settings, with its curvature mode and detail size weights when it has them. +fn generator_json(generator: &Generator) -> Value { + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert }); + if let Some(detail) = &generator.detail { + out["mode"] = json!(format!("{:?}", detail.mode)); + out["sizes"] = json!(detail.weights); + } + out } fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { @@ -129,26 +140,34 @@ pub fn texture_sets(s: &Session) -> Value { json!((0..s.set_count()).map(|i| texture_set(s, i)).collect::>()) } -/// One texture set; UV-tiled sets list their tiles and where each sits in the texel atlas. -pub fn texture_set(s: &Session, i: usize) -> Value { - let Some(t) = s.doc.project.texture_sets.get(i) else { return Value::Null }; - let grid = t.tile_grid(); - let tiles: Vec = - t.uv_tiles.iter().filter_map(|u| grid?.block(*u).map(|(x, y)| json!({ "udim": u, "block": [x, y], "resolution": t.tile_resolution(*u) }))).collect(); +/// One texture set, including UV tile layout and bake selection +pub fn texture_set(session: &Session, index: usize) -> Value { + let Some(texture_set) = session.doc.project.texture_sets.get(index) else { return Value::Null }; + + let grid = texture_set.tile_grid(); + let tiles: Vec = texture_set + .uv_tiles + .iter() + .filter_map(|tile| { + grid?.block(*tile).map(|(x, y)| { + json!({"udim": tile, "block": [x, y], "resolution": texture_set.tile_resolution(*tile), "bakeEnabled": !texture_set.bake_excluded_tiles.contains(tile)}) + }) + }) + .collect(); json!({ - "index": i, - "name": t.name, - "resolution": t.resolution, - "size": t.size(), - "blockResolution": t.block_resolution(), - "uvTiles": t.uv_tiles, + "index": index, + "name": texture_set.name, + "resolution": texture_set.resolution, + "size": texture_set.size(), + "blockResolution": texture_set.block_resolution(), + "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": t.channels.iter().map(|(c, f)| json!({ "channel": c.id(), "format": f.label() })).collect::>(), - "layers": s.doc.project.walk(i).len(), - "parts": crate::set_cmds::parts(s, i), - "baked": crate::project_cmds::baked_json(s.doc.baked.get(&i)), - "visible": t.visible, - "active": i == s.ts(), + "channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), + "layers": session.doc.project.walk(index).len(), + "parts": crate::set_cmds::parts(session, index), + "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "visible": texture_set.visible, + "active": index == session.ts(), }) } @@ -161,7 +180,7 @@ pub fn session(s: &Session) -> Value { "path": s.path, "modified": s.modified, "textureSets": texture_sets(s), - "bakeMeshes": crate::bake_cmds::meshes_json(s), + "bakeMeshes": crate::bake::meshes_json(s), "activeTextureSet": ts, "selectedLayer": s.selected_layer().map(|l| l.0), "target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) }, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..40ebd7bc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,16 +8,16 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod bake_cmds; -#[path = "bake/mod.rs"] -mod bake_data; -mod bake_paint_cmds; +pub mod bake; pub mod brush_preset_cmds; pub mod camera_cmds; +pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; +pub mod fill_hit_test; +pub mod fill_mode; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -25,12 +25,20 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; +mod mask_preview_pixel; pub mod material_lib; +mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod meshmap_file_name; +pub mod meshmap_import_cmds; +mod orb_camera; +pub mod orb_preview; pub mod painting; pub mod path_tool; +mod polygon_fill; +mod polygon_fill_drag; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] mod preserve; @@ -45,17 +53,20 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod triangle_partition; +mod uv_stroke_state; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_data::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; +pub use fill_hit_test::FillHitTest; +pub use fill_mode::FillMode; pub use path_tool::PathState; pub use project_cmds::sample_session; -pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; +pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; pub use set_cmds::{ResizeOutput, ResizeTask}; -pub use texturecraft_bake as bake; pub use texturecraft_compose as compose; pub use texturecraft_core as core; pub use texturecraft_formats as formats; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..b8aad872 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Project, Source, + BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, + Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -314,39 +314,76 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { push_effect(s, p, EffectKind::Fill { source, projection }, blend) } -fn generator_from(p: &Value, g: &mut Generator) { - if let Some(v) = f32p(p, "level") { - g.level = v.clamp(0.0, 1.0); +/// Apply `params` to `generator`, using `command` in errors +fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if let Some(level) = f32p(params, "level") { + generator.level = level.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "softness") { - g.softness = v.clamp(0.0, 1.0); + if let Some(softness) = f32p(params, "softness") { + generator.softness = softness.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "noise") { - g.noise_amount = v.clamp(0.0, 2.0); + if let Some(noise) = f32p(params, "noise") { + generator.noise_amount = noise.clamp(0.0, 2.0); } - if let Some(v) = f32p(p, "noiseScale") { - g.noise_scale = v.clamp(0.01, 1000.0); + if let Some(noise_scale) = f32p(params, "noiseScale") { + generator.noise_scale = noise_scale.clamp(0.01, 1000.0); } - if let Some(v) = u64p(p, "seed") { - g.seed = v as u32; + if let Some(seed) = u64p(params, "seed") { + generator.seed = seed as u32; } - if let Some(v) = boolp(p, "invert") { - g.invert = v; + if let Some(invert) = boolp(params, "invert") { + generator.invert = invert; } - if let Some(d) = color_param(p, "direction") { - g.direction = d; + if let Some(direction) = color_param(params, "direction") { + generator.direction = direction; } + + // A mode or sizes also give a curvature generator saved before detail sizes its detail + let mode = params + .get("mode") + .map(|value| { + let name = value.as_str().ok_or_else(|| bad(command, "`mode` must be a string"))?; + CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`"))) + }) + .transpose()?; + let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?; + if mode.is_none() && weights.is_none() { + return Ok(()); + } + if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes")); + } + + let detail = generator.detail.get_or_insert_with(CurvatureDetail::default); + if let Some(mode) = mode { + detail.mode = mode; + } + if let Some(weights) = weights { + detail.weights = weights; + } + Ok(()) } -fn add_generator(s: &mut Session, p: &Value) -> Result { - let kind = match strp(p, "generator") { - Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?, +/// Read one weight (0..1) per size of [`CurvatureDetail::SIZES`], finest first +fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> { + let invalid = || bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len())); + let items = value.as_array().filter(|items| items.len() == CurvatureDetail::SIZES.len()).ok_or_else(invalid)?; + let mut weights = [0.0; CurvatureDetail::SIZES.len()]; + for (weight, item) in weights.iter_mut().zip(items) { + *weight = item.as_f64().ok_or_else(invalid)?.clamp(0.0, 1.0) as f32; + } + Ok(weights) +} + +fn add_generator(session: &mut Session, params: &Value) -> Result { + let kind = match strp(params, "generator") { + Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, None => GeneratorKind::EdgeWear, }; - let mut g = Generator::new(kind); - generator_from(p, &mut g); - let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal); - push_effect(s, p, EffectKind::Generator(g), blend) + let mut generator = Generator::new(kind); + generator_from("effect.add.generator", params, &mut generator)?; + let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); + push_effect(session, params, EffectKind::Generator(generator), blend) } pub(crate) fn levels_from(p: &Value, l: &mut Levels) { @@ -413,55 +450,79 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } -fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { +/// Edit visibility, blending, name, effect parameters, or a filter's type +fn set(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "effect.set"; + let effect = effect_id(session, params, CMD)?; + let blend = blend_param(CMD, params, "blend")?; + + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one + let anchor = match session.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; - match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + let channel_param = channel_param(CMD, params, "anchorChannel")?; + match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { + Some(anchor) => Some(anchor_source(session, CMD, owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; - s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + + // Naming the filter the effect already is edits its parameters like a plain effect.set + let swapped = match strp(params, "filter") { + Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None, + Some(filter) => Some(swapped_filter(session, effect, filter, params)?), + None => None, + }; + let swaps_filter = swapped.is_some(); + + session.edit("Edit effect", |session| { + let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some((kind, label)) = swapped { + if let EffectKind::Filter(old) = &edited.kind + && edited.name == old.label() + { + edited.name = label.to_string(); + } + edited.kind = kind; } - if let Some(b) = blend { - e.blend = b; + + if let Some(visible) = boolp(params, "visible") { + edited.visible = visible; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(blend) = blend { + edited.blend = blend; } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(opacity) = f32p(params, "opacity") { + edited.opacity = opacity.clamp(0.0, 1.0); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + if let Some(name) = name_param(params) { + edited.name = name.to_string(); + } + + match &mut edited.kind { + EffectKind::Generator(generator) => generator_from(CMD, params, generator)?, + EffectKind::Levels(levels) => levels_from(params, levels), + // The swapped filter was built with the parameters already + EffectKind::Filter(_) if swaps_filter => {} + EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } - EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, + EffectKind::Compare { tolerance, .. } => { + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} @@ -471,6 +532,38 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The library id of the filter effect `effect` is, if it is one +fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { + match &s.doc.project.effect(effect)?.1.kind { + EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id), + _ => None, + } +} + +/// Filter `id` built with `p` and its label, to replace filter effect `effect` +fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { + const CMD: &str = "effect.set"; + let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if !matches!(current.kind, EffectKind::Filter(_)) { + return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase()))); + } + + let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; + let mut kind = crate::filter_lib::build(def.id, &Value::Null)?; + let EffectKind::Filter(filter) = &mut kind else { + return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label))); + }; + + let mask = s.doc.project.layer(owner)?.mask.as_ref(); + let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect)); + if on_mask && !def.mask { + return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); + } + + crate::filter_lib::apply(p, filter, CMD)?; + Ok((kind, def.label)) +} + /// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { project.layers.values_mut().find_map(|l| { diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs new file mode 100644 index 00000000..14ad5842 --- /dev/null +++ b/crates/engine/src/mask_preview_pixel.rs @@ -0,0 +1,14 @@ +//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`]) + +use texturecraft_geom::glam::Vec3; + +/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaskPreviewPixel { + /// Mask value (0..=1). + pub mask: f32, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer). + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline). + pub coverage: f32, +} diff --git a/crates/engine/src/material_preview_pixel.rs b/crates/engine/src/material_preview_pixel.rs new file mode 100644 index 00000000..7b83422e --- /dev/null +++ b/crates/engine/src/material_preview_pixel.rs @@ -0,0 +1,16 @@ +//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`]) + +use texturecraft_geom::glam::Vec3; + +use crate::preview::Sample; + +/// The material values seen at a preview pixel, with what a display needs to light the shape +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialPreviewPixel { + /// Linear material values, averaged over the pixel + pub sample: Sample, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer) + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline) + pub coverage: f32, +} diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 2220df34..4524b361 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; - let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; - // Every mesh map of a set shares one size: the other maps', or what a bake would make (a - // block of the bake resolution per tile of the atlas). - let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); - let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { - Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => { - let (width, height) = set.bake.common.output_size(); - (width.saturating_mul(cols), height.saturating_mul(rows)) - } + let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let texture_set = s.doc.project.texture_set(ts)?; + let images = match texture_set.tile_grid() { + Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?, + None => BTreeMap::from([(FIRST_TILE, image)]), }; - if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); - } - let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; - let data = match &tiles { - None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), - // An atlas texel reads the image of the tile its mesh UV falls in. - Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { - let uv = set.from_atlas(grid, [u, v]); - udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) - }), - }; - s.edit("Use image as mesh map", |s| { - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(()) - })?; - Ok(json!({ "map": map.id(), "resolution": res })) + + let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?; + Ok(json!({ "map": map.id(), "resolution": resolution })) } -/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for -/// each tile's. -fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result>> { - const CMD: &str = "textureSet.meshMap.set"; - let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; +/// The tile number a set without UV tiles keys its one image by +pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); + +/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width +pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { + return Err(bad(cmd, format!("no image for UV tile {tile}"))); + } + + let (width, height) = image_map_size(s, cmd, ts)?; + + let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = match (grid, images.values().next()) { + (_, None) => return Err(bad(cmd, "no image to use")), + (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), + // An atlas texel reads the image of the tile its mesh UV falls in + (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { + let uv = grid.from_atlas([u, v]); + udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) + }), + }; + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = width; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(width) +} + +/// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels +pub(crate) fn image_map_size(s: &Session, cmd: &str, ts: usize) -> Result<(u32, u32)> { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) + let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) { + Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))), + None => { + let (width, height) = texture_set.bake.common.output_size(); + (width.saturating_mul(columns), height.saturating_mul(rows)) + } + }; + let empty = width == 0 || height == 0; + let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS; + let too_wide = grid.is_none() && width > MAX_RESOLUTION; + if empty || too_many_texels || too_wide { + return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty"))); + } + + Ok((width, height)) +} + +/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's +fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { + let tile_at = + udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default()); tiles .iter() - .map(|&t| { - let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}"))) + .map(|&tile| { + let tile_name = format!("{before_tile}{tile}{after_tile}"); + images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}"))) }) .collect() } +/// The UV tile number in a file name (`Body_ao.1002.png` → 1002) +pub(crate) fn tile_number(file_name: &str) -> Option { + udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok()) +} + /// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts. fn udim_in(name: &str) -> Option { let b = name.as_bytes(); diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs new file mode 100644 index 00000000..fde32d5e --- /dev/null +++ b/crates/engine/src/meshmap_file_name.rs @@ -0,0 +1,159 @@ +//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion) + +use std::path::Path; + +use texturecraft_core::{BakedMap, UDIM_RANGE}; + +/// Mesh maps named by two words anywhere in the file name; they win over the one-word names +const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[ + ("world", &["normal", "normals"], BakedMap::WorldNormal), + ("bent", &["normal", "normals"], BakedMap::BentNormal), + ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), +]; + +/// Mesh maps named by one word, including the two-word names written as one +const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[ + ("worldnormal", BakedMap::WorldNormal), + ("worldnormals", BakedMap::WorldNormal), + ("bentnormal", BakedMap::BentNormal), + ("bentnormals", BakedMap::BentNormal), + ("ambientocclusion", BakedMap::AmbientOcclusion), + ("normal", BakedMap::Normal), + ("normals", BakedMap::Normal), + ("nrm", BakedMap::Normal), + ("occlusion", BakedMap::AmbientOcclusion), + ("ao", BakedMap::AmbientOcclusion), + ("curvature", BakedMap::Curvature), + ("curv", BakedMap::Curvature), + ("id", BakedMap::Id), + ("position", BakedMap::Position), + ("pos", BakedMap::Position), + ("thickness", BakedMap::Thickness), + ("height", BakedMap::Height), + ("displacement", BakedMap::Height), + ("opacity", BakedMap::Opacity), + ("alpha", BakedMap::Opacity), +]; + +fn is_separator(c: char) -> bool { + matches!(c, '_' | '-' | '.' | ' ') +} + +/// The lowercase file name without its folder and extension +fn lowercase_stem(path: &str) -> String { + Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase() +} + +/// What follows `set_name` at the start of a lowercase stem, when a separator follows it +fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> { + if set_name.is_empty() { + return None; + } + + stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator)) +} + +/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option { + let stem = lowercase_stem(path); + let rest = after_set_name(&stem, set_name).unwrap_or(&stem); + let is_tile_number = |word: &str| word.len() == 4 && word.parse::().is_ok_and(|number| UDIM_RANGE.contains(&number)); + let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect(); + + let has = |name: &str| words.contains(&name); + TWO_WORD_NAMES + .iter() + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second))) + .map(|(_, _, map)| *map) + .or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map))) +} + +/// The set a file is for: the longest set name its name starts with before a separator (any name with one set) +pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option { + if set_names.len() == 1 { + return Some(0); + } + + let stem = lowercase_stem(path); + set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_word_names_its_map() { + let cases = [ + ("Body_normal.png", BakedMap::Normal), + ("Body_normals.png", BakedMap::Normal), + ("Body_nrm.png", BakedMap::Normal), + ("Body_world_normal.png", BakedMap::WorldNormal), + ("Body_normals_world.png", BakedMap::WorldNormal), + ("Body_WorldNormal.png", BakedMap::WorldNormal), + ("Body_bent_normals.png", BakedMap::BentNormal), + ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion), + ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion), + ("Body_occlusion.png", BakedMap::AmbientOcclusion), + ("Body AO.png", BakedMap::AmbientOcclusion), + ("Body_curvature.png", BakedMap::Curvature), + ("Body_curv.png", BakedMap::Curvature), + ("Body_ID.png", BakedMap::Id), + ("Body_position.png", BakedMap::Position), + ("Body_pos.png", BakedMap::Position), + ("Body_thickness.png", BakedMap::Thickness), + ("Body_height.png", BakedMap::Height), + ("Body_displacement.png", BakedMap::Height), + ("Body_opacity.png", BakedMap::Opacity), + ("Body_alpha.png", BakedMap::Opacity), + ]; + for (file, map) in cases { + assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}"); + } + } + + #[test] + fn tile_numbers_and_folders_are_ignored() { + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal)); + assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); + } + + #[test] + fn unknown_words_match_no_map() { + assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None); + assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None); + assert_eq!(baked_map_from_file_name("", "Body"), None); + } + + #[test] + fn the_set_name_is_not_read_as_a_map() { + assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None); + assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion)); + } + + #[test] + fn the_longest_set_name_wins() { + let sets = ["Body", "Body_Upper", "Head"]; + assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1)); + assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0)); + assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2)); + } + + #[test] + fn a_set_name_must_end_at_a_separator() { + let sets = ["Body", "Head"]; + assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Body.png", &sets), None); + } + + #[test] + fn one_set_takes_every_file() { + assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("ao.png", &[]), None); + } +} diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs new file mode 100644 index 00000000..20913de2 --- /dev/null +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -0,0 +1,162 @@ +//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names + +use std::collections::BTreeMap; +use std::path::Path; + +use serde_json::{Value, json}; +use texturecraft_core::BakedMap; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images}; +use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; +use crate::resource_cmds::read_image_file; +use crate::{Result, Session, cmd}; + +const CMD: &str = "textureSet.meshMap.import"; + +/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles +const MAX_FILES: usize = 512; + +/// Bound retained file bytes, decoded RGBA floats and resampled maps together, before allocating pixels +const MAX_TOTAL_BYTES: u64 = 2 << 30; + +pub fn specs() -> Vec { + vec![cmd!( + "textureSet.meshMap.import", + "Import baked maps", + [], + None, + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); at most 512 files and 2 GiB of file bytes, decoded images and mesh maps; desktop only", + always, + import + )] +} + +fn import(s: &mut Session, p: &Value) -> Result { + import_with_budget(s, p, MAX_TOTAL_BYTES) +} + +fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result { + let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?; + if files.len() > MAX_FILES { + return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); + } + + let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + let mut slots: BTreeMap<(usize, BakedMap), BTreeMap> = BTreeMap::new(); + let mut unmatched = Vec::new(); + for file in files { + let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; + let given_map = match file.get("map") { + None | Some(Value::Null) => None, + Some(Value::String(id)) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), + Some(_) => return Err(bad(CMD, "`map` must be a mesh map id string")), + }; + + match slot_of(s, &set_names, path, given_map) { + Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => { + slots.entry(slot).or_default().insert(tile, path); + } + _ => unmatched.push(path), + } + } + + // A UV-tiled map needs a file for every tile of its set + slots.retain(|(ts, _), tiles| { + let complete = + s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile))); + if !complete { + unmatched.extend(tiles.values()); + } + complete + }); + if slots.is_empty() { + return Ok(json!({ "assigned": [], "unmatched": unmatched })); + } + + let result = s.edit("Import baked maps", |s| { + let mut assigned = Vec::new(); + let mut remaining_bytes = max_bytes; + for ((ts, map), tiles) in &slots { + let (width, height) = image_map_size(s, CMD, *ts)?; + let map_bytes = u64::from(width) * u64::from(height) * map.components() as u64 * size_of::() as u64; + reserve_bytes(&mut remaining_bytes, map_bytes)?; + + let mut images = BTreeMap::new(); + for (tile, path) in tiles { + let bytes = read_image_file(CMD, path, remaining_bytes)?; + reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?; + + let bytes_per_texel = size_of::<[f32; 4]>() as u64; + let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; + reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; + images.insert(*tile, image.clone()); + assigned.push(json!({"path": path, "ts": ts, "map": map.id()})); + } + use_images(s, CMD, *ts, *map, &images)?; + } + Ok(assigned) + }); + // A failed edit leaves the document as it was; forget the images it decoded + if result.is_err() { + s.sync_images(); + } + + Ok(json!({ "assigned": result?, "unmatched": unmatched })) +} + +fn reserve_bytes(remaining_bytes: &mut u64, bytes: u64) -> Result<()> { + *remaining_bytes = remaining_bytes.checked_sub(bytes).ok_or_else(|| bad(CMD, "the files, decoded images and mesh maps exceed the import memory budget"))?; + Ok(()) +} + +/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles) +fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option) -> Option<((usize, BakedMap), u32)> { + let ts = texture_set_from_file_name(path, set_names)?; + let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?; + let texture_set = s.doc.project.texture_sets.get(ts)?; + let tile = match texture_set.tile_grid() { + Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?, + None => FIRST_TILE, + }; + Some(((ts, map), tile)) +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::BakeResolution; + + #[test] + fn import_budget_counts_decoded_images_and_resampled_maps() { + let dir = std::env::temp_dir().join(format!("texturecraft-import-budget-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths = [dir.join("ao.png"), dir.join("height.png")]; + for path in &paths { + image::RgbaImage::from_pixel(16, 16, image::Rgba([128, 128, 128, 255])).save(path).unwrap(); + } + let file_bytes: u64 = paths.iter().map(|path| std::fs::metadata(path).unwrap().len()).sum(); + let decoded_bytes = 2 * 16 * 16 * 16; + let map_bytes = 2 * 16 * 16 * 4; + let required_bytes = file_bytes + decoded_bytes + map_bytes; + let params = json!({"files": paths.map(|path| json!({"path": path}))}); + let mut session = Session::new_project("budget", texturecraft_geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R16; + let revision = session.revision; + + for budget in [file_bytes, file_bytes + decoded_bytes, required_bytes - 1] { + let result = import_with_budget(&mut session, ¶ms, budget); + assert!(result.is_err(), "budget {budget} must cover decoded pixels and mesh maps: {result:?}"); + assert!(session.doc.resources.is_empty() && session.images.is_empty()); + assert!(session.doc.baked.values().all(|baked| baked.maps.is_empty())); + assert_eq!(session.revision, revision); + assert!(!session.modified); + assert!(session.undo_label().is_none()); + } + + let result = import_with_budget(&mut session, ¶ms, required_bytes).unwrap(); + assert_eq!(result["assigned"].as_array().unwrap().len(), 2); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/engine/src/orb_camera.rs b/crates/engine/src/orb_camera.rs new file mode 100644 index 00000000..d0015361 --- /dev/null +++ b/crates/engine/src/orb_camera.rs @@ -0,0 +1,63 @@ +//! Cached camera rays for one preview orb size + +use std::collections::HashMap; + +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::surface_at; + +use crate::Session; + +/// Camera angles expose the front, left and top panels +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss +pub(crate) type CameraSample = Option<(usize, Vec3)>; + +/// What each ray of a square orthographic view of the orb sees +pub(crate) struct OrbCamera { + /// Rays along each side of the view + pub rays_per_side: usize, + /// The texels (x, y) the camera sees, each once + pub texels: Vec<(u32, u32)>, + /// Per ray, row-major `rays_per_side²` + pub samples: Vec, +} + +impl OrbCamera { + /// Trace a square orthographic view onto a `texture_px²` texture + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera { + let (min, max) = session.mesh.bounds(); + let center = (min + max) * 0.5; + let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = texture_px.saturating_sub(1); + + let mut texels = Vec::new(); + let mut index_of = HashMap::new(); + let samples = (0..rays_per_side * rays_per_side) + .map(|ray| { + let side = rays_per_side as f32; + let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * texture_px as f32) as u32).min(max_texel), ((surface.uv.y * texture_px as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + + let normal = surface.nrm; + Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward)))) + }) + .collect(); + + OrbCamera { rays_per_side, texels, samples } + } +} diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs new file mode 100644 index 00000000..f29a247d --- /dev/null +++ b/crates/engine/src/orb_preview.rs @@ -0,0 +1,297 @@ +//! Smart mask and smart material previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use texturecraft_texel::TILE; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +pub use crate::material_preview_pixel::MaterialPreviewPixel; +use crate::orb_camera::OrbCamera; +use crate::preview::Sample; +use crate::session::Document; +use crate::{EngineError, Result, Session, materials}; + +/// Bake resolution in texels; 256 loses the thin edge lines +const TEXTURE_PX: u32 = 512; +/// Camera rays per preview pixel along each axis (anti-aliased outline) +const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for shelf previews +pub const MAX_PREVIEW_SIZE_PX: usize = 512; +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default +const OCCLUSION_RAYS: u32 = 12; +/// Curvature rays per texel; thumbnail detail needs fewer than the default +const CURVATURE_RAYS: u32 = 12; +/// Radius relative to the bounding box; isolates panel edges from the round body +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read; smart materials build on the same presets +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Keep camera views for the thumbnail and hover preview sizes +const CAMERAS_KEPT: usize = 2; +/// The channels a material preview shows, in [`Sample`] order +const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; +/// The orb's only texture set +const SET: usize = 0; + +/// The baked orb and, per preview size, what its camera sees +pub struct OrbPreview { + session: Session, + /// The layer smart masks are applied to + layer: LayerId, + /// The baked document and selection, restored before each material + bare: (Document, BTreeMap), + /// Cached camera views, least recently used first + cameras: Vec, +} + +impl OrbPreview { + /// Bake the orb once (previews of any size reuse it) + pub fn new() -> Result { + let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(SET)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(SET, false)?; + + let bare = (session.doc.clone(), session.selected.clone()); + Ok(OrbPreview { session, layer, bare, cameras: Vec::new() }) + } + + /// Row-major `size²` pixels of smart mask `id`, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn mask(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Previews need no undo history; retaining snapshots grows memory across presets + self.session.undo.clear(); + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + mask_sum += values.get(texel).copied().unwrap_or(0.0); + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } + + /// Row-major `size²` pixels of built-in material `id`, with None outside the shape + /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn material(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each material goes on the bare shape, not over the previous one + (self.session.doc, self.session.selected) = self.bare.clone(); + let applied = materials::apply(&mut self.session, id); + // Previews need no undo history; retaining snapshots grows memory across materials + self.session.undo.clear(); + applied.ok()?; + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = material_at(&self.session, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 }; + let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + let Some(value) = values.get(texel) else { continue }; + + sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]); + sum.metallic += value.metallic; + sum.roughness += value.roughness; + sum.height += value.height; + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| { + let mean = Sample { + base: sum.base.map(|component| component / hits), + metallic: sum.metallic / hits, + roughness: sum.roughness / hits, + height: sum.height / hits, + }; + MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels } + }) + }) + .collect(); + Some(pixels) + } +} + +/// Preview sizes the camera may allocate +fn valid_size(size: usize) -> bool { + (1..=MAX_PREVIEW_SIZE_PX).contains(&size) +} + +/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal) +fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator + '_ { + let (x, y) = (pixel % size, pixel / size); + (0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| { + let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE); + let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x; + camera.samples.get(ray).copied().flatten() + }) +} + +/// The material values at `texels`, compositing only the tiles that hold them +fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option> { + let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect(); + let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); + + session.with_inputs(SET, |inputs| { + let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX); + texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles); + + let samples = texels + .iter() + .map(|&(x, y)| { + let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y)); + Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] } + }) + .collect(); + Some(samples) + }) +} + +/// Cache one camera per preview size, evicting the least recently used view +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a OrbCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) { + Some(index) => cameras.remove(index), + None => OrbCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } + + cameras.push(camera); + cameras.last() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + /// Mean mask value over the pixels a preview sees + fn mean_mask(pixels: &[Option]) -> f32 { + pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 + } + + #[test] + fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { + let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let layer = session.doc.project.texture_set(SET).unwrap().stack[0]; + let bare = (session.doc.clone(), session.selected.clone()); + let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() }; + let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len(); + for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { + assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); + assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); + assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material"); + } + } + + #[test] + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for smart_mask in crate::smart_masks::SMART_MASKS { + let id = smart_mask.id; + let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame"); + for pixel in seen { + assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite(), "{id}: {pixel:?}"); + } + } + + let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap()); + let shows = |pixels: &[Option]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.mask("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.mask("edges_sharp", size * 3).unwrap(); + assert_eq!(big.len(), size * size * 9); + assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges)); + + preview.mask("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); + } + + #[test] + fn smart_materials_render_on_the_orb_and_show_their_wear() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for material in materials::MATERIALS.iter().filter(|material| material.smart) { + let id = material.id; + let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + for pixel in pixels.iter().flatten() { + let sample = pixel.sample; + let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]); + assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}"); + } + } + assert!(preview.material("nope", size).is_none()); + + // Paint chipped at the edges shows the steel under it: the smart material is not its base + let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap()); + let metallic_pixels = |pixels: &[Option]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count(); + let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel)); + assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}"); + + let base_colors = |pixels: &[Option]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::>(); + assert_ne!(base_colors(&worn), base_colors(&steel)); + + // Each material starts from the bare orb: rendering another one in between changes nothing + preview.material("iron_rusted", size).unwrap(); + assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn); + } +} diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..27377af1 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -7,13 +7,23 @@ use texturecraft_compose::PaintTarget; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ - CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, - fill_triangles, pick, rasterize, + CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick, + rasterize, }; -use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool}; +use crate::uv_stroke_state::UvStrokeState; use crate::{EngineError, Result}; +/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke. +const MIN_UV_STAMP_STEP: f32 = 1e-5; + +/// 2D view stamps rasterized together, bounding the memory of one batch. +const UV_STAMP_BATCH: usize = 4096; + +/// Covers a UV diagonal at the minimum step (about 142k stamps), including light pen pressure, while bounding hostile coordinates +const MAX_UV_STAMPS_PER_SAMPLE: usize = 150_000; + impl Session { /// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change). fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc { @@ -35,6 +45,16 @@ impl Session { pick(&ctx, screen) } + /// The texture set that paints mesh material `material` (a [`SurfaceHit::material`]) + pub fn texture_set_of_material(&self, material: usize) -> Option { + self.doc.project.texture_sets.iter().position(|t| t.material == material) + } + + /// The texture set of the surface under viewport pixel `screen` + pub fn texture_set_at(&self, screen: Vec2, viewport: Vec2) -> Option { + self.pick(screen, viewport).and_then(|hit| self.texture_set_of_material(hit.material)) + } + /// Resolve what a stroke on the selected layer paints into, creating the mask paint effect /// when painting a mask. Must run inside the stroke's history snapshot. fn paint_target(&mut self) -> Result { @@ -224,7 +244,7 @@ impl Session { stroke, canvas, depth, - uv: uv_mode.then_some((None, 0.0)), + uv: uv_mode.then(UvStrokeState::default), camera: self.camera, viewport, values, @@ -291,12 +311,15 @@ impl Session { Ok(self.continue_stroke(screen, pressure)) } - /// Start a stroke in the 2D view at texture coordinate `uv`. + /// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there). pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> { self.cancel_stroke(); - if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) { - return Err(EngineError::Other("use this tool in the 3D view".into())); + match self.tool.tool { + Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()), + Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())), + _ => {} } + self.start_stroke(self.viewport, true, Some(uv))?; self.continue_stroke_uv(uv, pressure); Ok(()) @@ -304,40 +327,49 @@ impl Session { /// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square. pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) { - let Some(st) = self.stroke.as_mut() else { return }; - let Some((last, carry)) = st.uv.as_mut() else { return }; - let Some(cache) = self.caches.get_mut(st.ts) else { return }; - let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; - let step = (b.spacing * 2.0 * radius).max(1e-5); - let mut points = Vec::new(); - match *last { - None => points.push(uv), - Some(prev) => { - let seg = uv - prev; - let len = seg.length(); - let mut t = step - *carry; - while t <= len && points.len() < 4096 { - points.push(prev + seg * (t / len.max(1e-9))); - t += step; - } - *carry = len - (t - step); - } - } - // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down). - let angle = match *last { - Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0, - _ => b.angle, + let Some(active) = self.stroke.as_mut() else { return }; + let Some(progress) = active.uv.as_mut() else { return }; + let Some(cache) = self.caches.get_mut(active.ts) else { return }; + + let settings = &active.stroke.settings; + let pressure = pressure.clamp(0.0, 1.0); + let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 }; + let radius = settings.size * 2.0 * size_scale; + let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP); + + // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down) + let angle = match progress.last { + Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0, + _ => settings.angle, }; - *last = Some(uv); - let n0 = st.stroke.stamps.len() as u32; - let stamps: Vec = points - .iter() - .enumerate() - .map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 }) - .collect(); - texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps); + + // The first sample is one stamp; a later one stamps every `step` along the segment from the previous + let (start, segment, mut distance) = match progress.last.replace(uv) { + None => (uv, Vec2::ZERO, 0.0), + // Pressure can shrink the step below the carry from the preceding sample + Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)), + }; + let length = segment.length(); + let shape = Self::shape(&self.images, settings); + let mut batch = Vec::new(); + let mut stamped = 0; + while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE { + let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped); + batch.clear(); + while distance <= length && batch.len() < batch_size { + let center = start + segment * (distance / length.max(f32::MIN_POSITIVE)); + let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32); + batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed }); + distance += step; + } + + stamped += batch.len(); + texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch); + } + + // At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards + progress.carry = (length - (distance - step)).min(step); + progress.stamps = progress.stamps.wrapping_add(stamped as u32); self.stroke_painted(); } @@ -472,21 +504,6 @@ impl Session { Ok(tiles) } - /// Polygon fill: fill the triangle / UV island / whole mesh under `screen`. - pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { - let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.ts(); - let material = self.doc.project.texture_set(ts)?.material; - if hit.material != material { - return Err(EngineError::Other("that surface belongs to another texture set".into())); - } - let tris = self.fill_set(hit.tri, material); - let (gbuf, mut canvas) = self.fill_canvas(ts)?; - fill_triangles(&mut canvas, &gbuf, &tris); - self.commit_fill("Polygon fill", ts, &canvas)?; - Ok(tris.len()) - } - /// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the /// quick mask unless the fill edits it. pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc, StrokeCanvas)> { @@ -500,67 +517,37 @@ impl Session { /// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask. pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { - let size = (canvas.alpha.width(), canvas.alpha.height()); - let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; if self.quick_mask.editing { - self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); - return Ok(()); + return self.paint_fill(ts, canvas); } - self.edit(label, |s| { - let target = s.paint_target()?; - let values = s.stroke_values(target); - match target { - PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()), - PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()), - } - Ok(()) - }) + + // Each fill is its own step, never merged into a box drag's step of the same label + self.edit_merging(label, false, |session| session.paint_fill(ts, canvas)) } - /// Triangles filled by the current fill mode starting from `tri`. - fn fill_set(&self, tri: u32, material: usize) -> BTreeSet { - let m = &self.mesh; - match self.tool.fill_mode { - FillMode::Triangle => [tri].into_iter().collect(), - FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(), - FillMode::UvIsland => { - // Triangles sharing an edge in UV space form a UV island: imported meshes often - // split vertices along hard edges (or per face) where the UVs run on, so shared - // vertex indices alone break an island into its polygons. - let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]); - let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) { - Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(), - _ => Vec::new(), - }; - let mut by_edge: BTreeMap<_, Vec> = BTreeMap::new(); - for t in m.triangles_of(material) { - for e in edges(t) { - by_edge.entry(e).or_default().push(t as u32); - } - } - let mut seen = BTreeSet::new(); - let mut stack = vec![tri]; - while let Some(t) = stack.pop() { - if !seen.insert(t) { - continue; - } - for e in edges(t as usize) { - for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) { - if !seen.contains(n) { - stack.push(*n); - } - } - } - } - seen - } + /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) + pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> { + let size = (canvas.alpha.width(), canvas.alpha.height()); + let opacity = self.tool.brush.opacity; + let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.quick_mask.editing { + self.commit_quick_mask(ts, size, source); + return Ok(()); } + + let target = self.paint_target()?; + let values = self.stroke_values(target); + match target { + PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()), + PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()), + } + Ok(()) } /// Color picker: copy the material under the cursor into the tool's paint values. pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.doc.project.texture_sets.iter().position(|t| t.material == hit.material).unwrap_or(self.ts()); + let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; let (w, h) = (cache.size.0 as f32, cache.size.1 as f32); let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32); @@ -617,34 +604,3 @@ fn with_commit_source( let carried = st.canvas.pickup.as_ref().map(|p| &p.values); f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) } - -#[cfg(test)] -mod tests { - use texturecraft_geom::glam::{Vec2, Vec3}; - use texturecraft_geom::mesh::Mesh; - use texturecraft_geom::primitives; - - use crate::session::{FillMode, Session}; - - #[test] - fn uv_island_fill_follows_uvs_across_split_vertices() { - // Two copies of a plane, each triangle with its own three vertices (as hard edges or - // per-face imports leave a mesh), the second copy apart in UV space. - let plane = primitives::plane(2.0, 4); - let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); - for shift in [0.0, 0.5] { - for i in plane.indices.iter().map(|i| *i as usize) { - positions.push(plane.positions[i] + Vec3::Y * shift); - uvs.push(plane.uvs[i] * 0.5 + shift); - } - } - let indices = (0..positions.len() as u32).collect(); - let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); - let n = plane.triangle_count(); - assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared"); - let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap(); - s.tool.fill_mode = FillMode::UvIsland; - assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island"); - assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island"); - } -} diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs new file mode 100644 index 00000000..ea7270f5 --- /dev/null +++ b/crates/engine/src/polygon_fill.rs @@ -0,0 +1,607 @@ +//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view. + +use std::borrow::Cow; +use std::collections::{BTreeSet, HashSet}; + +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::{Mesh, NO_TRI}; +use texturecraft_paint::{EyeDepth, fill_triangles, screen_point}; + +use crate::fill_mode::FillMode; +use crate::polygon_fill_drag::PolygonFillDrag; +use crate::session::Session; +use crate::triangle_partition::TrianglePartition; +use crate::{EngineError, Result}; + +/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner +const CORNER_GRID_STEPS: f32 = 1e5; + +impl Session { + /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` + pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { + let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + if hit.material != self.fill_material()? { + return Err(EngineError::Other("that surface belongs to another texture set".into())); + } + + self.fill_group_of(hit.tri) + } + + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked + pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { + let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let size = Vec2::new(gbuf.width as f32, gbuf.height as f32); + let texel = (uv * size).floor(); + let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all()) + .then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied()) + .flatten() + .filter(|triangle| *triangle != NO_TRI) + .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + + self.fill_group_of(triangle) + } + + /// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step) + pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + // A scripted box stands alone: it finishes any drag under way, and ends even when it fails + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box(corner, opposite, viewport); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) + } + + /// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step) + pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box_uv(corner, opposite); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) + } + + /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` + pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + // Whole pixels, as the visibility buffer is rendered at + self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE))) + } + + /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) + pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + self.drag_polygon_fill(corner, opposite, None) + } + + /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count + pub fn end_polygon_fill_box(&mut self) -> usize { + let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; + + let filled = drag.filled.len(); + // Quick mask edits keep no history, as with its strokes + if filled > 0 && drag.quick_mask_before.is_none() { + self.push_history("Polygon fill", drag.before); + } + filled + } + + /// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None + fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option) -> Result { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + let (low, high) = (corner.min(opposite), corner.max(opposite)); + self.start_polygon_fill_drag(viewport)?; + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + + if drag.failed || drag.last_box == Some((low, high)) { + return Ok(drag.filled.len()); + } + + drag.last_box = Some((low, high)); + let selected = self.box_selection(low, high); + self.show_box_fill(selected) + } + + /// Continue a box drag only while its view, paint target and quick mask state still match + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + let ts = self.ts(); + let target = (self.selected_layer(), self.target); + let quick_mask = self.quick_mask.editing; + // Finish the old target before another preview can restore its earlier document snapshot + if let Some(drag) = &self.polygon_fill_drag { + if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask { + // A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera + if drag.camera != self.camera { + let (points, depth) = self.box_space(viewport); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + (drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None); + } + } + + return Ok(()); + } + + self.end_polygon_fill_box(); + } + + let material = self.fill_material()?; + let (points, depth) = self.box_space(viewport); + let polygons = match self.tool.fill_mode { + FillMode::Triangle | FillMode::Polygon => None, + FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)), + }; + self.polygon_fill_drag = Some(PolygonFillDrag { + ts, + target, + viewport, + camera: self.camera, + before: self.doc.clone(), + quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()), + points, + depth, + fill_groups: self.fill_partition(material), + polygons, + filled: BTreeSet::new(), + last_box: None, + failed: false, + }); + Ok(()) + } + + /// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees + fn box_space(&self, viewport: Option) -> (Vec>, Option) { + let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) }; + + let view_proj = self.camera.view_proj(size.x / size.y); + let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); + let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32)); + (points, depth) + } + + /// The mesh material of the texture set being painted + fn fill_material(&self) -> Result { + Ok(self.doc.project.texture_set(self.ts())?.material) + } + + /// The triangles the current fill mode fills together, for `material` + fn fill_partition(&self, material: usize) -> TrianglePartition { + match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges), + FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges), + FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges), + } + } + + /// Fill the fill-mode group holding `triangle` (one undo step) + fn fill_group_of(&mut self, triangle: u32) -> Result { + let ts = self.ts(); + let groups = self.fill_partition(self.fill_material()?); + let triangles: BTreeSet = groups.group(triangle).unwrap_or_default().iter().copied().collect(); + + let (gbuf, mut canvas) = self.fill_canvas(ts)?; + fill_triangles(&mut canvas, &gbuf, &triangles); + self.commit_fill("Polygon fill", ts, &canvas)?; + Ok(triangles.len()) + } + + /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden + fn shown_mesh(&self) -> Cow<'_, Mesh> { + let sets = &self.doc.project.texture_sets; + if sets.iter().all(|set| set.visible) { + return Cow::Borrowed(&self.mesh); + } + + let mut mesh = (*self.mesh).clone(); + for set in sets.iter().filter(|set| !set.visible) { + for triangle in self.mesh.triangles_of(set.material) { + if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) { + let first = corners[0]; + corners.fill(first); + } + } + } + Cow::Owned(mesh) + } + + /// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode + fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet { + let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; + + let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high)); + let point = |vertex: usize| drag.points.get(vertex).copied().flatten(); + let corners = |triangle: u32| { + let [first, second, third] = self.mesh.tri(triangle as usize)?; + Some([point(first)?, point(second)?, point(third)?]) + }; + let hit_test = self.tool.fill_hit_test; + let mut polygon_corners = Vec::new(); + let mut groups = BTreeSet::new(); + for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups { + let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); + if !seen { + continue; + } + + polygon_corners.clear(); + polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle))); + if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) { + groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); + } + } + + groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect() + } + + /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed + fn show_box_fill(&mut self, selected: BTreeSet) -> Result { + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + if drag.filled == selected { + return Ok(selected.len()); + } + + let ts = drag.ts; + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + } + + let painted = if selected.is_empty() { + Ok(()) + } else { + self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| { + fill_triangles(&mut canvas, &gbuf, &selected); + self.paint_fill(ts, &canvas) + }) + }; + self.invalidate_changed(&previous); + + // A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing + let selected_count = selected.len(); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + drag.failed = painted.is_err(); + drag.filled = if drag.failed { BTreeSet::new() } else { selected }; + } + painted.map(|_| selected_count) + } +} + +/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included +fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { + let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel); + let columns = pixel_span(low.x, high.x, depth.width); + let rows = pixel_span(low.y, high.y, depth.height); + + rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) + .copied() + .filter(|triangle| *triangle != NO_TRI) + .collect() +} + +/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside) +fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range { + let first = low.floor().clamp(0.0, count as f32) as usize; + let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize; + first..end.max(first) +} + +/// Texture coordinates of `triangle`'s corners +fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) +} + +/// The polygon diagonals of `triangle`: edges the importer added to split a polygon +fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { + let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); + let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() }; + + (0..3) + .filter(|edge| hidden >> edge & 1 == 1) + .map(|edge| { + let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]); + (from.min(to), from.max(to)) + }) + .collect() +} + +/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart +fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> { + let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); + let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected +fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> { + let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64)); + let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() }; + let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +#[cfg(test)] +mod tests { + use texturecraft_core::Channel; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + use texturecraft_geom::primitives; + + use crate::fill_hit_test::FillHitTest; + use crate::fill_mode::FillMode; + use crate::session::{Session, Tool}; + + /// The roughness the test fills paint, to tell filled texels apart + const FILL_ROUGHNESS: f32 = 0.9; + + /// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`] + fn fill_session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.tool.tool = Tool::PolygonFill; + session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]); + session.update(); + session + } + + /// Whether the texel at texture coordinate `uv` shows the fill's roughness + fn filled_at(session: &Session, uv: Vec2) -> bool { + let (width, height) = session.caches[0].size; + let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32); + (roughness[0] - FILL_ROUGHNESS).abs() < 0.01 + } + + /// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh) + fn split_planes() -> (Mesh, usize) { + let plane = primitives::plane(2.0, 4); + let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); + for shift in [0.0, 0.5] { + for vertex in plane.indices.iter().map(|index| *index as usize) { + positions.push(plane.positions[vertex] + Vec3::Y * shift); + uvs.push(plane.uvs[vertex] * 0.5 + shift); + } + } + let indices = (0..positions.len() as u32).collect(); + let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); + assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared"); + (mesh, plane.triangle_count()) + } + + #[test] + fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() { + let (mesh, per_plane) = split_planes(); + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + + for fill_mode in [FillMode::UvIsland, FillMode::Mesh] { + session.tool.fill_mode = fill_mode; + let groups = session.fill_partition(0); + assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane"); + assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane"); + } + } + + #[test] + fn polygon_mode_groups_the_two_triangles_of_each_quad() { + let mut session = fill_session(primitives::plane(2.0, 2)); + + session.tool.fill_mode = FillMode::Triangle; + assert_eq!(session.fill_partition(0).group(0), Some(&[0][..])); + + session.tool.fill_mode = FillMode::Polygon; + let mut quad = session.fill_partition(0).group(0).unwrap().to_vec(); + quad.sort_unstable(); + assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad"); + } + + #[test] + fn a_uv_box_over_half_a_plane_fills_that_half() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap(); + session.update(); + + assert_eq!(filled, 16, "the left two columns of quads"); + assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9))); + assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1))); + } + + #[test] + fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() { + let mut session = fill_session(primitives::plane(2.0, 2)); + session.tool.fill_mode = FillMode::Polygon; + let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2)); + + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside"); + assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step"); + + session.tool.fill_hit_test = FillHitTest::Intersection; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts"); + } + + #[test] + fn visible_only_skips_the_back_of_a_cube() { + let mut session = fill_session(primitives::cube(1.0)); + session.camera.yaw = 0.6; + session.camera.pitch = 0.4; + let (low, high) = (Vec2::ZERO, session.viewport); + let every_triangle = session.mesh.triangle_count(); + + session.tool.fill_visible_only = true; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees"); + + session.tool.fill_visible_only = false; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle); + } + + #[test] + fn visible_only_sees_through_a_hidden_texture_set() { + let mut session = fill_session(primitives::material_ball()); + let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap(); + session.active_set = base; + let (low, high) = (Vec2::ZERO, session.viewport); + + let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap(); + session.doc.project.texture_sets[0].visible = false; + let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap(); + + assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}"); + } + + #[test] + fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills"); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging"); + assert_eq!(session.history_labels().len(), history, "no undo step yet"); + + assert_eq!(session.end_polygon_fill_box(), 16); + assert_eq!(session.history_labels().len(), history + 1); + session.undo().unwrap(); + session.update(); + assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); + } + + #[test] + fn a_failed_box_fill_leaves_no_drag_behind() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let layer = session.selected.remove(&0).unwrap(); + assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on"); + + session.selected.insert(0, layer); + assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again"); + } + + #[test] + fn undo_and_tool_changes_finish_a_box_drag_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished"); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step"); + } + + #[test] + fn an_unmoved_box_keeps_its_fill() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let narrow_box = Vec2::new(0.3, 1.0); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches"); + + // Contained center would select one column, so a second selection would show 8 + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again"); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again"); + } + + #[test] + fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { + let mut session = fill_session(primitives::udim_plane()); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let every_triangle = session.mesh.triangle_count(); + assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); + } + + #[test] + fn a_2d_click_skips_a_triangle_with_collapsed_uvs() { + // A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them + let plane = primitives::plane(2.0, 1); + let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z]; + let mut uvs = vec![Vec2::ZERO; 3]; + positions.extend(&plane.positions); + uvs.extend(&plane.uvs); + let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect(); + let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap()); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one"); + } + + #[test] + fn a_failing_drag_reports_once_and_records_nothing() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + session.selected.clear(); + + assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err()); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing"); + assert_eq!(session.end_polygon_fill_box(), 0); + assert_eq!(session.history_labels().len(), history); + } + + #[test] + fn an_edit_during_a_drag_records_the_fill_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + + let layers = session.doc.project.layers.len(); + crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + let labels = session.history_labels(); + assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}"); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(); + assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer"); + } + + #[test] + fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() { + let mut session = fill_session(primitives::cube(1.0)); + let center = (session.viewport * 0.5).floor(); + + assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0); + } + + #[test] + fn a_camera_move_mid_drag_keeps_one_drag() { + let mut session = fill_session(primitives::cube(1.0)); + let viewport = session.viewport; + let history = session.history_labels().len(); + + let (corner, opposite) = (viewport * 0.4, viewport * 0.6); + + let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.camera.zoom(0.5); + let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.end_polygon_fill_box(); + + assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera"); + assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it"); + } + + #[test] + fn pixel_spans_include_both_edges_and_nothing_outside() { + assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel"); + assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel"); + assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel"); + assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100); + } + + #[test] + fn a_2d_click_fills_the_triangle_under_it() { + let mut session = fill_session(primitives::plane(2.0, 1)); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + + assert!(filled_at(&session, Vec2::new(0.2, 0.7))); + assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays"); + assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs"); + } +} diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs new file mode 100644 index 00000000..09c20905 --- /dev/null +++ b/crates/engine/src/polygon_fill_drag.rs @@ -0,0 +1,42 @@ +//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move. + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_core::LayerId; +use texturecraft_geom::OrbitCamera; +use texturecraft_geom::glam::Vec2; +use texturecraft_paint::EyeDepth; +use texturecraft_texel::TileImage; + +use crate::session::{Document, StackTarget}; +use crate::triangle_partition::TrianglePartition; + +/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends +pub(crate) struct PolygonFillDrag { + /// The texture set it fills + pub ts: usize, + /// The selected layer and content, mask or effect being filled + pub target: (Option, StackTarget), + /// The 3D view's size in pixels, or None for a drag in the 2D view + pub viewport: Option, + /// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with + pub camera: OrbitCamera, + /// The document before the drag, refilled each time the selection changes + pub before: Document, + /// The quick mask's coverage before the drag, when the drag paints the quick mask + pub quick_mask_before: Option>, + /// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view + pub points: Vec>, + /// What the camera sees (3D view, visible polygons only) + pub depth: Option, + /// What the fill mode fills together + pub fill_groups: TrianglePartition, + /// The polygons the box tests, when they differ from the fill groups + pub polygons: Option, + /// The triangles filled so far + pub filled: BTreeSet, + /// The box last shown, lowest corner first: an unmoved box isn't selected again + pub last_box: Option<(Vec2, Vec2)>, + /// The fill failed (reported once): the rest of the drag fills nothing + pub failed: bool, +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..ce45b9ff 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,12 +1,8 @@ -//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z, -//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space -//! noise). Cheap enough for lazily rendered thumbnails. +//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`]) -use texturecraft_compose::pattern::{Coords, procedural, world_noise}; -use texturecraft_core::{ - Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, - Projection, Source, TextureSet, blend1, -}; +use rayon::prelude::*; +use texturecraft_compose::pattern::{Coords, procedural}; +use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -48,74 +44,40 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> { } } -/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities). -fn generator(g: &Generator, c: &Coords) -> f32 { - let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y); - let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2; - let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1; - let s = match g.kind { - GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5, - GeneratorKind::EdgeWear => wear, - GeneratorKind::Curvature => 0.5 + wear * 0.5, - GeneratorKind::AmbientOcclusion => 1.0 - cavity, - _ => cavity, - }; - // Same thresholding as the compositor. - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let soft = g.softness.max(1e-3); - let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } -} - -fn mask(m: &Mask, c: &Coords) -> f32 { - if !m.enabled { - return 1.0; - } - let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 }; - for e in m.effects.iter().filter(|e| e.visible) { - let val = match &e.kind { - EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]), - EffectKind::Generator(g) => Some(generator(g, c)), - EffectKind::Levels(l) => Some(l.apply(v)), - EffectKind::Filter(Filter::Invert) => Some(1.0 - v), - _ => None, - }; - if let Some(val) = val { - let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) }; - v += (blended - v) * e.opacity.clamp(0.0, 1.0); - } - } - v.clamp(0.0, 1.0) -} - const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; -/// Preview of built-in material `id` (None for an unknown id). +/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps) pub fn material(id: &str, size: usize) -> Option>> { - let mut p = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut p, channels: CHANNELS.to_vec() }, id).ok()?; - Some( - sphere_normals(size) - .map(|n| { - let c = coords(n?); - let mut acc = CHANNELS.map(Channel::default_value); - for l in layers.iter().filter(|l| l.visible) { - let LayerKind::Fill(f) = &l.kind else { continue }; - let w = l.mask.as_ref().map_or(1.0, |m| mask(m, &c)); - for (a, ch) in acc.iter_mut().zip(CHANNELS) { - if let (Some(b), Some(v)) = (l.blend(ch), f.sources.get(&ch).and_then(|s| source(s, &f.projection, &c))) { - let t = w * b.opacity.clamp(0.0, 1.0); - *a = [0, 1, 2].map(|k| a[k] + (v[k] - a[k]) * t); - } + let plain = crate::materials::find(id).filter(|found| !found.smart)?; + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?; + + // Pixels evaluate independently and big previews take long on one core + let normals: Vec<_> = sphere_normals(size).collect(); + let samples = normals + .into_par_iter() + .map(|normal| { + let at = coords(normal?); + let mut values = CHANNELS.map(Channel::default_value); + for layer in layers.iter().filter(|layer| layer.visible) { + // Plain materials are unmasked fills + let LayerKind::Fill(fill) = &layer.kind else { continue }; + + for (value, channel) in values.iter_mut().zip(CHANNELS) { + let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at)); + if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { + let weight = blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight); } } - let [base, metal, rough, height] = acc; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) - }) - .collect(), - ) + } + + let [base, metallic, roughness, height] = values; + Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }) + }) + .collect(); + + Some(samples) } /// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K). @@ -164,6 +126,7 @@ pub fn filter(id: &str, size: usize) -> Option>> { gbuf: &gbuf, pixels: &pixels, baked: &baked, + block_scales: p.texture_set(0).map(|set| set.block_scales()).unwrap_or_default(), preview: None, images: &images, bounds: mesh.bounds(), @@ -183,36 +146,44 @@ pub fn filter(id: &str, size: usize) -> Option>> { ) } -/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id). -pub fn smart_mask(id: &str, size: usize) -> Option>> { - let (bg, fx) = crate::smart_masks::preset(id)?; - let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx); - Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect()) -} - #[cfg(test)] mod tests { use super::*; + /// Whether every value of `sample` is finite + fn finite(sample: &Sample) -> bool { + sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite) + } + #[test] fn previews_cover_the_sphere_with_finite_values() { - for m in crate::materials::MATERIALS { - let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id)); - let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id)); - assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); - assert!(px[0].is_none(), "corners are outside the sphere"); + let size = 16; + for built_in in crate::materials::MATERIALS { + let id = built_in.id; + if built_in.smart { + assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb"); + continue; + } + + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap(); + assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks"); + + let pixels = material(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); + assert!(pixels[0].is_none(), "corners are outside the sphere"); } - for sm in crate::smart_masks::SMART_MASKS { - let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id)); - assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id); + assert!(material("nope", size).is_none() && filter("nope", size).is_none()); + + let size = 24; + for library_filter in crate::filter_lib::FILTERS { + let id = library_filter.id; + let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); } - assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none()); - for f in crate::filter_lib::FILTERS { - let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); - let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); - assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id); - } - let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap()); + let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } } diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..86e7c9b8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { } impl Session { - /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. + /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX)) + } + + /// Add an image within a decoded texel budget, inside the caller's edit + pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec, max_texels: u64) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } - let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; + + let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); @@ -50,11 +56,8 @@ impl Session { name = format!("{n}_{base}"); n += 1; } - let key = name.clone(); - self.edit("Import resource", |s| { - s.doc.resources.insert(key, Arc::new(bytes)); - Ok(()) - })?; + + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); Ok(name) } @@ -98,15 +101,44 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; - let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; - if meta.len() > MAX_BYTES as u64 { - return Err(bad("resource.import", format!("{path} is too large"))); - } - let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; + let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; let name = s.import_resource_bytes(path, bytes)?; Ok(json!({ "name": name })) } +/// Read a regular image file within both the per-file cap and the caller's remaining byte budget +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result> { + use std::io::Read; + + let max_bytes = max_bytes.min(MAX_BYTES as u64); + let read_error = |error| bad(cmd, format!("cannot read {path}: {error}")); + let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)")); + let metadata = std::fs::metadata(path).map_err(read_error)?; + // Pipes can block on open, and devices may never reach EOF + if !metadata.is_file() { + return Err(bad(cmd, format!("{path} is not a regular file"))); + } + if metadata.len() > max_bytes { + return Err(too_large()); + } + + // Bound the read even if the file grows after the metadata check + let file = std::fs::File::open(path).map_err(read_error)?; + let mut bytes = Vec::with_capacity(metadata.len() as usize); + file.take(max_bytes + 1).read_to_end(&mut bytes).map_err(read_error)?; + if bytes.len() as u64 > max_bytes { + return Err(too_large()); + } + + Ok(bytes) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_image_file(cmd: &str, _: &str, _: u64) -> Result> { + Err(bad(cmd, "file paths are not available in the browser")) +} + #[cfg(target_arch = "wasm32")] fn import(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into())) @@ -165,3 +197,24 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "layer": id.0 })) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn file_reads_obey_the_remaining_byte_budget() { + let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); + std::fs::write(&path, b"1234").unwrap(); + let name = path.to_str().unwrap(); + assert!(read_image_file("test", name, 3).unwrap_err().to_string().contains("too large")); + assert_eq!(read_image_file("test", name, 4).unwrap(), b"1234"); + std::fs::remove_file(path).unwrap(); + } + + #[cfg(unix)] + #[test] + fn devices_are_rejected_before_reading() { + assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file")); + } +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..298f7f61 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; use texturecraft_texel::DilationMap; +use crate::fill_mode::FillMode; use crate::{EngineError, Result}; /// Padding (texels) applied to composites for display. @@ -160,15 +161,6 @@ impl ViewMode { } } -/// Polygon fill granularity. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum FillMode { - #[default] - Triangle, - UvIsland, - Mesh, -} - /// A screen-pinned image for the Projection tool (a stencil). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { @@ -210,6 +202,12 @@ pub struct ToolState { /// Gray painted into masks. pub mask_value: f32, pub fill_mode: FillMode, + /// How a polygon fill box decides which polygons it selects + #[serde(default)] + pub fill_hit_test: crate::fill_hit_test::FillHitTest, + /// Polygon fill boxes in the 3D view select only the polygons the camera sees + #[serde(default = "default_fill_visible_only")] + pub fill_visible_only: bool, /// Stencil used by the Projection tool. #[serde(default)] pub stencil: Option, @@ -231,6 +229,10 @@ fn default_smudge_strength() -> f32 { 0.5 } +fn default_fill_visible_only() -> bool { + true +} + /// What the Clone tool copies (the clone source modes). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum CloneFrom { @@ -260,6 +262,8 @@ impl Default for ToolState { enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), mask_value: 1.0, fill_mode: FillMode::Triangle, + fill_hit_test: Default::default(), + fill_visible_only: default_fill_visible_only(), stencil: None, smudge_strength: default_smudge_strength(), clone_source: None, @@ -291,8 +295,8 @@ pub(crate) struct ActiveStroke { pub canvas: StrokeCanvas, /// Camera visibility for 3D strokes (None for strokes in the 2D view). pub depth: Option>, - /// 2D view strokes: last UV point and the distance carried to the next stamp. - pub uv: Option<(Option, f32)>, + /// 2D view strokes: where the stroke is between samples. + pub uv: Option, pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, @@ -314,6 +318,9 @@ pub struct Session { pub mesh: Arc, /// Unique per loaded mesh and UV layout (GPU caches compare it). pub mesh_id: u64, + /// Unique per open project: a mesh reimport or UV layout change keeps it, and opening, closing + /// or creating a project replaces it. + pub project_id: u64, /// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas). pub(crate) source: Arc, pub bvh: Arc, @@ -356,6 +363,8 @@ pub struct Session { /// The last stroke's camera visibility buffer: reused while the camera, view size and mesh /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, + /// The polygon fill box being dragged + pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). pub export_presets: crate::preset_cmds::UserPresets, /// The user's project templates (kept when another project opens). @@ -378,6 +387,7 @@ impl Session { Ok(Session { doc, mesh_id: next_mesh_id(), + project_id: next_mesh_id(), source, mesh, bvh: Arc::new(bvh), @@ -405,6 +415,7 @@ impl Session { revision: 1, log: Vec::new(), depth_cache: None, + polygon_fill_drag: None, export_presets: Default::default(), templates: Default::default(), }) @@ -489,22 +500,24 @@ impl Session { self.edit_merging(label, self.merge_edits, f) } - /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the - /// same label (a drag in the viewport is one step however many updates it makes). - pub fn edit_merging(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result) -> Result { + /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes). + pub fn edit_merging(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result) -> Result { + // A box fill under way becomes its own step first, so this edit isn't written over or folded into it + self.end_polygon_fill_box(); + let before = self.doc.clone(); - let result = f(self).and_then(|v| match self.doc.project.instance_cycle() { + let result = change(self).and_then(|value| match self.doc.project.instance_cycle() { Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))), - None => Ok(v), + None => Ok(value), }); match result { - Ok(v) => { + Ok(value) => { self.record(label, before, merge); - Ok(v) + Ok(value) } - Err(e) => { + Err(error) => { self.doc = before; - Err(e) + Err(error) } } } @@ -530,7 +543,7 @@ impl Session { /// Mark dirty every texture set whose composite differs between `other` and the current /// document (after an edit, undo or redo). - fn invalidate_changed(&mut self, other: &Document) { + pub(crate) fn invalidate_changed(&mut self, other: &Document) { self.follow_uv_layouts(&other.project); self.sync_caches(); let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); @@ -625,25 +638,29 @@ impl Session { } pub fn undo(&mut self) -> Result { + // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); self.stop_path_edit(); - let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; - let now = std::mem::replace(&mut self.doc, doc); - self.after_history(&now); - self.redo.push((label.clone(), now)); + + let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) } pub fn redo(&mut self) -> Result { + // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); self.stop_path_edit(); - let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; - let now = std::mem::replace(&mut self.doc, doc); - self.after_history(&now); - self.undo.push((label.clone(), now)); + + let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) } @@ -728,6 +745,7 @@ impl Session { gbuf: &cache.gbuf, pixels: &self.doc.pixels, baked: self.doc.baked.get(&ts).unwrap_or(&empty), + block_scales: cache.composite.block_scales.clone(), preview, images: &self.images, bounds: self.mesh.bounds(), @@ -816,6 +834,7 @@ impl Session { gbuf: &cache.gbuf, pixels: &self.doc.pixels, baked: self.doc.baked.get(&ts).unwrap_or(&empty), + block_scales: cache.composite.block_scales.clone(), preview: None, images: &self.images, bounds: self.mesh.bounds(), @@ -829,6 +848,13 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Mask values at texture-set coordinates in request order; None without an enabled mask + /// Uncovered and out-of-range texels read zero; neighbourhood filters also read surrounding texels + pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let (texture_set, _, _) = self.doc.project.locate(id)?; + self.with_inputs(texture_set, |inputs| texturecraft_compose::mask_at(inputs, id, texels)) + } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 5038abbb..dd0111f3 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup. +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes). pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) } /// A triplanar grayscale pattern fill. diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..a3f92bba 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -7,7 +7,9 @@ use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::fill_hit_test::FillHitTest; +use crate::fill_mode::FillMode; +use crate::session::{CloneFrom, CloneSource, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -69,7 +71,16 @@ pub fn specs() -> Vec { always, clone_source ), - cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode), + cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode), + cmd!( + "tool.fillSelection", + "Polygon fill selection", + [], + None, + "{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}", + always, + fill_selection + ), cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke), cmd!( "tool.strokeUv", @@ -80,16 +91,26 @@ pub fn specs() -> Vec { always, stroke_uv ), - cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click), + cmd!( + "tool.click", + "Tool click", + [], + None, + "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", + always, + click + ), cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))), ] } -pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result { - s.cancel_stroke(); - s.tool.tool = t; - s.revision = s.revision.wrapping_add(1); - Ok(json!({ "tool": t.id() })) +pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result { + session.cancel_stroke(); + // A box fill under way keeps what it filled as one undo step + session.end_polygon_fill_box(); + session.tool.tool = tool; + session.revision = session.revision.wrapping_add(1); + Ok(json!({ "tool": tool.id() })) } fn select(s: &mut Session, p: &Value) -> Result { @@ -319,13 +340,29 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null)) } -fn fill_mode(s: &mut Session, p: &Value) -> Result { - s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { +fn fill_mode(session: &mut Session, params: &Value) -> Result { + session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, + "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), }; + + Ok(Value::Null) +} + +fn fill_selection(session: &mut Session, params: &Value) -> Result { + match strp(params, "hitTest") { + None => {} + Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), + } + if let Some(visible_only) = boolp(params, "visibleOnly") { + session.tool.fill_visible_only = visible_only; + } + Ok(Value::Null) } @@ -369,22 +406,48 @@ fn stroke(s: &mut Session, p: &Value) -> Result { Ok(json!({ "stamps": stamps })) } -fn click(s: &mut Session, p: &Value) -> Result { - let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; - let vp = viewport_of(s, p); - let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }), +fn click(session: &mut Session, params: &Value) -> Result { + if session.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(session, params)? + { + session.update(); + return Ok(json!({ "triangles": triangles })); + } + + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; + + let point = Vec2::new(x, y); + let viewport = viewport_of(session, params); + let out = match session.tool.tool { + Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let v = s.color_pick(Vec2::new(x, y), vp)?; - json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>()) + let picked = session.color_pick(point, viewport)?; + json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?, - _ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?, + _ => json!({ "stamps": session.stroke_points(&[point], viewport)? }), }; - s.update(); + session.update(); Ok(out) } +/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point +fn polygon_fill_click(session: &mut Session, params: &Value) -> Result> { + let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1")); + let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?, + _ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")), + (_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?, + _ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")), + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?, + _ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")), + _ => return Ok(None), + }; + + Ok(Some(filled)) +} + fn stroke_uv(s: &mut Session, p: &Value) -> Result { let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?; let tiles = s.stroke_uv_points(&points)?; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs new file mode 100644 index 00000000..d6ad31cb --- /dev/null +++ b/crates/engine/src/triangle_partition.rs @@ -0,0 +1,123 @@ +//! Triangles of one material grouped into the pieces polygon fill selects and fills. + +use std::collections::HashMap; +use std::hash::Hash; + +use texturecraft_geom::Mesh; + +/// A material's triangles split into groups joined across shared edges +pub struct TrianglePartition { + /// The triangles of each group + pub groups: Vec>, + /// The index of each triangle's group + group_of: HashMap, +} + +impl TrianglePartition { + /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + // Each triangle's edges once, in mesh order so the groups come out the same every time + let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); + let position_of: HashMap = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect(); + let mut edge_lists: Vec> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect(); + let mut by_edge: HashMap> = HashMap::new(); + for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) { + for edge in triangle_edges { + by_edge.entry(edge.clone()).or_default().push(*triangle); + } + } + + let mut groups = Vec::new(); + let mut group_of = HashMap::with_capacity(triangles.len()); + for &start in &triangles { + if group_of.contains_key(&start) { + continue; + } + + let mut members = Vec::new(); + let mut stack = vec![start]; + group_of.insert(start, groups.len()); + while let Some(triangle) = stack.pop() { + members.push(triangle); + let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default(); + // Visit a shared edge once, including when many collapsed faces share the same key + for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) { + if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) { + entry.insert(groups.len()); + stack.push(neighbour); + } + } + } + groups.push(members); + } + TrianglePartition { groups, group_of } + } + + /// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material) + pub fn index_of(&self, triangle: u32) -> Option { + self.group_of.get(&triangle).copied() + } + + /// The group holding `triangle` (None for a triangle of another material) + pub fn group(&self, triangle: u32) -> Option<&[u32]> { + self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice) + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::primitives; + + use super::*; + + #[test] + fn triangles_sharing_a_key_join_one_group() { + let mesh = primitives::plane(2.0, 2); + let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]); + + assert_eq!(singles.groups.len(), mesh.triangle_count()); + assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2); + assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2)); + assert_eq!(pairs.group(99), None); + } + + #[test] + fn shared_edges_keep_transitive_neighbors() { + let mesh = primitives::plane(2.0, 4); + let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]); + + assert_eq!(groups.groups.len(), 1); + assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count()); + } + + #[test] + #[ignore = "release performance measurement"] + fn benchmark_shared_edges() { + use std::hint::black_box; + use std::time::Instant; + + for subdivisions in [32, 64] { + let mesh = primitives::plane(2.0, subdivisions); + for collapsed in [false, true] { + let mut times = Vec::new(); + for _ in 0..5 { + let start = Instant::now(); + let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| { + if collapsed { + vec![(0, 0); 3] + } else { + let [first, second, third] = mesh.tri(triangle).unwrap(); + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() + } + }); + assert_eq!(groups.groups.len(), 1); + black_box(groups); + times.push(start.elapsed().as_secs_f64() * 1000.0); + } + times.sort_by(f64::total_cmp); + eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]); + } + } + } +} diff --git a/crates/engine/src/uv_stroke_state.rs b/crates/engine/src/uv_stroke_state.rs new file mode 100644 index 00000000..5ce5ae2f --- /dev/null +++ b/crates/engine/src/uv_stroke_state.rs @@ -0,0 +1,14 @@ +//! Where a stroke in the 2D view is between pointer samples. + +use texturecraft_geom::glam::Vec2; + +/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct UvStrokeState { + /// The last sample's texture coordinates (None before the first sample). + pub last: Option, + /// Distance from the last stamp to the last sample, at most one stamp step. + pub carry: f32, + /// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample. + pub stamps: u32, +} diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index d4659943..cd8c3a76 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -39,61 +39,69 @@ pub fn specs() -> Vec { ] } -fn tile_resolution(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.tile.resolution"; - let ts = ts_param(s, p, CMD)?; - let tile = u64p(p, "tile").and_then(|t| u32::try_from(t).ok()).ok_or_else(|| bad(CMD, "`tile` (a UDIM number) is required"))?; - let r = u64p(p, "resolution").ok_or_else(|| bad(CMD, "`resolution` is required"))?; - let r = check_resolution(u32::try_from(r).unwrap_or(0))?; - let set = s.doc.project.texture_set(ts)?; - if !set.uv_tiles.contains(&tile) { - return Err(bad(CMD, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", set.name, set.uv_tiles))); +fn tile_resolution(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.tile.resolution"; + let texture_set_index = ts_param(session, params, COMMAND)?; + let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` (a UDIM number) is required"))?; + let resolution = u64p(params, "resolution").ok_or_else(|| bad(COMMAND, "`resolution` is required"))?; + let resolution = check_resolution(u32::try_from(resolution).unwrap_or(0))?; + let texture_set = session.doc.project.texture_set(texture_set_index)?; + if !texture_set.uv_tiles.contains(&tile) { + return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles))); } - if set.tile_resolution(tile) == r { - return Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": set.size() })); + + let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile); + if texture_set.tile_resolution(tile) == resolution && !removes_override { + return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() })); } - s.cancel_stroke(); - let size = s.edit("UV tile resolution", |s| { - let set = s.doc.project.texture_set_mut(ts)?; - let old = set.clone(); - if r == set.resolution { - set.tile_resolutions.remove(&tile); + + session.cancel_stroke(); + let size = session.edit("UV tile resolution", |session| { + let texture_set = session.doc.project.texture_set_mut(texture_set_index)?; + let previous = texture_set.clone(); + if resolution == texture_set.resolution { + texture_set.tile_resolutions.remove(&tile); } else { - set.tile_resolutions.insert(tile, r); + texture_set.tile_resolutions.insert(tile, resolution); + } + check_size(texture_set)?; + let size = texture_set.size(); + if previous.tile_resolution(tile) != resolution { + relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)?; } - check_size(set)?; - let size = set.size(); - relayout(&mut s.doc, ts, &old, &mut s.log)?; Ok(size) })?; - Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": size })) + Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": size })) } -fn uv_tiles(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.uvTiles"; - let ts = ts_param(s, p, CMD)?; - let enabled = boolp(p, "enabled").ok_or_else(|| bad(CMD, "`enabled` (true or false) is required"))?; - let set = s.doc.project.texture_set(ts)?; +fn uv_tiles(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.uvTiles"; + let texture_set_index = ts_param(session, params, COMMAND)?; + let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` (true or false) is required"))?; + let texture_set = session.doc.project.texture_set(texture_set_index)?; let tiles = if enabled { - detect_uv_tiles(&s.source, set.material, Some(true), &mut Vec::new()).map_err(|e| bad(CMD, format!("texture set \"{}\": {e}", set.name)))? + detect_uv_tiles(&session.source, texture_set.material, Some(true), &mut Vec::new()) + .map_err(|error| bad(COMMAND, format!("texture set \"{}\": {error}", texture_set.name)))? } else { Vec::new() }; - if tiles == set.uv_tiles { - return Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": [] })); + if tiles == texture_set.uv_tiles { + return Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": [] })); } - // Leaving UV tile mode keeps tile 1001 (UV 0..1), the area a classic set paints. - let dropped: Vec = set.uv_tiles.iter().copied().filter(|t| !enabled && *t != 1001).collect(); - s.cancel_stroke(); - s.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |s| { - let set = s.doc.project.texture_set_mut(ts)?; - let old = set.clone(); - set.tile_resolutions.retain(|u, _| tiles.contains(u)); - set.uv_tiles = tiles.clone(); - check_size(set)?; - relayout(&mut s.doc, ts, &old, &mut s.log) + + // Leaving UV tile mode keeps tile 1001, the area a classic set paints + let dropped: Vec = texture_set.uv_tiles.iter().copied().filter(|tile| !enabled && *tile != 1001).collect(); + session.cancel_stroke(); + session.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |session| { + let texture_set = session.doc.project.texture_set_mut(texture_set_index)?; + let previous = texture_set.clone(); + texture_set.tile_resolutions.retain(|tile, _| tiles.contains(tile)); + texture_set.bake_excluded_tiles.retain(|tile| tiles.contains(tile)); + texture_set.uv_tiles = tiles.clone(); + check_size(texture_set)?; + relayout(&mut session.doc, texture_set_index, &previous, &mut session.log) })?; - Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": dropped })) + Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": dropped })) } /// Mesh UV → normalized atlas position of UV tile layout `set` (None where the layout holds @@ -119,23 +127,30 @@ fn from_layout(set: &TextureSet, a: [f32; 2]) -> Option<[f32; 2]> { (set.uv_tiles.contains(&udim) && local.0 <= scale && local.1 <= scale).then(|| set.from_atlas(&g, a)) } -/// Resample texture set `ts`'s painted images and baked maps from layout `old` into the set's -/// current layout (inside [`Session::edit`] after changing the set). Notes go to `log`. +/// Move painted images into the working layout and baked maps only when the tile grid changes pub(crate) fn relayout(doc: &mut Document, ts: usize, old: &TextureSet, log: &mut Vec) -> Result<()> { let new = doc.project.texture_set(ts)?.clone(); - let map = |a: [f32; 2]| from_layout(&new, a).and_then(|m| to_layout(old, m)); - let ((ow, oh), (nw, nh)) = (old.size(), new.size()); - let texel = |x: f32, y: f32| map([x / nw as f32, y / nh as f32]).map(|o| (o[0] * ow as f32, o[1] * oh as f32)); - let all = TileImage::new(nw, nh, 1); + let map = |uv: [f32; 2]| from_layout(&new, uv).and_then(|mesh_uv| to_layout(old, mesh_uv)); + let (old_size, new_size) = (old.size(), new.size()); + let texel = |x: f32, y: f32| map([x / new_size.0 as f32, y / new_size.1 as f32]).map(|uv| (uv[0] * old_size.0 as f32, uv[1] * old_size.1 as f32)); + let all = TileImage::new(new_size.0, new_size.1, 1); let tiles: Vec<(u32, u32)> = (0..all.tiles_y()).flat_map(|ty| (0..all.tiles_x()).map(move |tx| (tx, ty))).collect(); - // Blocks and tiles are multiples of 64 texels (resolutions are powers of two ≥ 128), so the - // map is affine (or None) over each destination tile. - crate::layer_ops::map_set_images(doc, ts, |img, empty| remap_image(img, (nw, nh), empty, &texel, &tiles, true)); + + // Atlas blocks align with the 64-texel storage tiles, making each mapping affine + crate::layer_ops::map_set_images(doc, ts, |image, empty| remap_image(image, new_size, empty, &texel, &tiles, true)); remap_bake_paint(doc, ts, old, &new, &map)?; - if let Some(baked) = doc.baked.get(&ts) { - match remap_baked(baked, old, &new, &map) { - Some(b) => { - doc.baked.insert(ts, b); + + if old.uv_tiles != new.uv_tiles + && let Some(baked) = doc.baked.get(&ts) + { + let mut old_bake = old.clone(); + let mut new_bake = new.clone(); + old_bake.tile_resolutions.clear(); + new_bake.tile_resolutions.clear(); + let bake_map = |uv| from_layout(&new_bake, uv).and_then(|mesh_uv| to_layout(&old_bake, mesh_uv)); + match remap_baked(baked, &old_bake, &new_bake, &bake_map) { + Some(baked) => { + doc.baked.insert(ts, baked); } None => { doc.baked.remove(&ts); @@ -326,6 +341,28 @@ mod tests { assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1001, "resolution": 100})).is_err()); } + #[test] + fn removing_a_tile_override_at_the_sets_current_resolution_restores_inheritance() { + let mut session = udim_session(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + execute(&mut session, "textureSet.resolution", &json!({"resolution": 128})).unwrap(); + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + + assert!(session.doc.project.texture_sets[0].tile_resolutions.is_empty()); + assert_eq!(session.history_labels().len(), history_steps + 1); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert!(reopened.doc.project.texture_sets[0].tile_resolutions.is_empty()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + execute(&mut session, "textureSet.resolution", &json!({"resolution": 256})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].tile_resolution(1002), 256); + assert_eq!(session.doc.project.texture_sets[0].bake, before.texture_sets[0].bake); + } + #[test] fn export_writes_each_tile_at_its_own_size() { let mut s = udim_session(); diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/it/bake.rs similarity index 100% rename from crates/engine/tests/bake.rs rename to crates/engine/tests/it/bake.rs diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs new file mode 100644 index 00000000..620de675 --- /dev/null +++ b/crates/engine/tests/it/bake_resolution.rs @@ -0,0 +1,130 @@ +use std::sync::Arc; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Bake detail", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 128, "maps": ["position"], "dilation": 0, "patch": {"common": {"apply_diffusion": false}}})) + .unwrap(); + session +} + +#[test] +fn working_tile_resolution_preserves_bake_samples_and_pixels() { + let mut session = session(); + let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + let task = session.bake_task(0).unwrap(); + let output = task.run(&Progress::new()).unwrap(); + assert_eq!((output.resolution, output.height), (256, 128)); + + let gbuffer = UvGBuffer::new(&task.mesh, task.material, output.resolution, output.height); + let mut samples = [0usize; 2]; + for (index, triangle) in gbuffer.tri.iter().enumerate() { + if *triangle != NO_TRI { + samples[(index % 256) / 128] += 1; + } + } + assert_eq!(samples, [128 * 128; 2], "each tile receives the full Bake Output Size"); + assert_eq!(output.maps, original.maps); +} + +#[test] +fn changing_working_resolution_never_resamples_stored_bakes() { + let mut session = session(); + let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + session.apply_bake(0, output).unwrap(); + let original = session.doc.baked[&0].clone(); + for resolution in [128, 512, 256] { + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": resolution})).unwrap(); + let current = &session.doc.baked[&0]; + assert!(Arc::ptr_eq(¤t.maps[&BakedMap::Position], &original.maps[&BakedMap::Position]), "working resize must retain the bake buffer"); + assert_eq!(current, &original); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.baked[&0], original); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked[&0], original); + session.redo().unwrap(); + assert_eq!(session.doc.baked[&0], original); + + for resolution in [512, 128] { + execute(&mut session, "textureSet.resolution", &json!({"resolution": resolution})).unwrap(); + assert!(Arc::ptr_eq(&session.doc.baked[&0].maps[&BakedMap::Position], &original.maps[&BakedMap::Position])); + } +} + +#[test] +fn rectangular_bakes_and_excluded_vertical_tiles_ignore_working_resolution() { + let mut mesh = primitives::udim_plane(); + let second_plane = mesh.uvs.len() / 2; + for uv in mesh.uvs.iter_mut().skip(second_plane) { + uv.x -= 1.0; + uv.y -= 1.0; + } + let mut session = Session::new_project("Vertical bake", mesh, "builtin:udim_plane", None, 256).unwrap(); + execute( + &mut session, + "bake.settings", + &json!({"resolution": 64, "maps": ["position"], "dilation": 0, "patch": {"common": {"resolution_height": "R128", "apply_diffusion": false}}}), + ) + .unwrap(); + let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + assert_eq!((original.resolution, original.height), (64, 256)); + let pixels = original.maps.clone(); + session.apply_bake(0, original).unwrap(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1011, "resolution": 128})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap(); + let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + assert_eq!(output.maps, pixels, "rebaked and excluded tiles both keep their full rectangular detail"); +} + +#[test] +fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { + use texturecraft_engine::compose::{DisplayKind, tile_bytes}; + use texturecraft_engine::formats::export::{Dest, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef}; + + let mut session = session(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + let image = image::GrayImage::from_fn(128, 128, |x, y| image::Luma([(x + y) as u8])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + for tile in [1001, 1002] { + session.import_resource_bytes(&format!("ao.{tile}.png"), bytes.clone()).unwrap(); + } + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": "ao.1001.png"})).unwrap(); + while session.update() {} + + let baked = &session.doc.baked[&0]; + let map = BakedMap::AmbientOcclusion; + assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001); + let composite = &session.caches[0].composite; + let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1); + assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile"); + + let options = ExportOptions::new(ExportPreset { + name: "Bake detail".into(), + maps: vec![MapSpec { + file: "ao.$udim".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })], + }], + }); + let files = session.export_files(&[0], &options).unwrap(); + let file = files.iter().find(|file| file.name == "ao.1002.png").unwrap(); + let exported = image::load_from_memory(&file.bytes).unwrap().to_luma8(); + assert_eq!(exported.dimensions(), (128, 128)); + assert_eq!(exported.get_pixel(120, 120)[0], 240); + assert_eq!(exported.get_pixel(10, 10)[0], 20); + + let layer = session.doc.project.texture_sets[0].stack[0]; + execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); + let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); + assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout"); +} diff --git a/crates/engine/tests/it/bake_settings.rs b/crates/engine/tests/it/bake_settings.rs new file mode 100644 index 00000000..b22c53d9 --- /dev/null +++ b/crates/engine/tests/it/bake_settings.rs @@ -0,0 +1,112 @@ +use serde_json::json; +use texturecraft_engine::core::{BakeResolution, BakeSettings}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Bake settings", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake; + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.min_distance = 0.25; + second.maps.ao.parameters.rays.rays = 16; + second.maps.height.parameters.scaling_divisor = 2.0; + session +} + +#[test] +fn nested_settings_patch_preserves_other_fields_and_is_one_undo_step() { + let mut session = session(); + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + let patch = json!({"maps": {"ao": {"parameters": {"rays": {"rays": 128}}}}}); + + let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap(); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters.rays.rays = 128; + } + assert_eq!(session.doc.project, expected); + assert_eq!(result.as_array().unwrap().len(), 2); + assert_eq!(result[1]["model"], json!(expected.texture_sets[1].bake)); + assert_eq!(session.history_labels().len(), history_steps + 1); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets, expected.texture_sets); + + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, expected); +} + +#[test] +fn settings_patch_validates_every_target_before_changing_any() { + let mut session = session(); + let before = session.doc.project.clone(); + let history = session.history_labels(); + + // This maximum is valid for the active set but below the second set's minimum + let patch = json!({"maps": {"ao": {"parameters": {"rays": {"max_distance": 0.1}}}}}); + let error = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap_err(); + assert!(error.to_string().contains("minimum occluder distance"), "{error}"); + assert_eq!(session.doc.project, before); + assert_eq!(session.history_labels(), history); +} + +#[test] +fn settings_patch_rejects_unknown_fields_and_invalid_shapes() { + let mut session = session(); + let before = session.doc.project.clone(); + let history = session.history_labels(); + + for patch in [ + json!(null), + json!([]), + json!({"unknown": 1}), + json!({"common": null}), + json!({"common": {"resolution": "invalid"}}), + json!({"common": {"antialiasing": true}}), + json!({"maps": {"ao": {"parameters": {"rays": {"rays": 257}}}}}), + json!({"maps": {"ao": {"parameters": {"rays": {"rayz": 128}}}}}), + ] { + assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).is_err(), "{patch}"); + assert_eq!(session.doc.project, before); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn settings_patch_can_clear_optional_height_and_keeps_target_selection() { + let mut session = session(); + let first = session.doc.project.texture_sets[0].bake.clone(); + let mut second = session.doc.project.texture_sets[1].bake.clone(); + let patch = json!({"common": {"resolution_height": null}}); + + execute(&mut session, "bake.settings", &json!({"ts": [1], "patch": patch})).unwrap(); + + second.common.resolution_height = None; + assert_eq!(session.doc.project.texture_sets[0].bake, first); + assert_eq!(session.doc.project.texture_sets[1].bake, second); + + let history_steps = session.history_labels().len(); + execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {}})).unwrap(); + execute(&mut session, "bake.settings", &json!({"ts": 1, "patch": patch})).unwrap(); + assert_eq!(session.history_labels().len(), history_steps); +} + +#[test] +fn settings_patch_can_reset_one_section_without_replacing_other_settings() { + let mut session = session(); + let mut expected = session.doc.project.clone(); + let defaults = BakeSettings::default().maps.ao.parameters; + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters = defaults; + } + + execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {"maps": {"ao": {"parameters": defaults}}}})).unwrap(); + + assert_eq!(session.doc.project, expected); +} diff --git a/crates/engine/tests/it/bake_tiles.rs b/crates/engine/tests/it/bake_tiles.rs new file mode 100644 index 00000000..3f000321 --- /dev/null +++ b/crates/engine/tests/it/bake_tiles.rs @@ -0,0 +1,172 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::compose::BakedMaps; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Tile baking", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2})).unwrap(); + session +} + +#[test] +fn tile_selection_is_inspectable_saved_and_undoable() { + let mut session = session(); + let before = session.doc.project.clone(); + let result = execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + assert_eq!(result, json!({"ts": 0, "tile": 1002, "enabled": false})); + let selected = session.doc.project.clone(); + let inspected = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap(); + assert_eq!(inspected["tiles"][0]["bakeEnabled"], true); + assert_eq!(inspected["tiles"][1]["bakeEnabled"], false); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project, selected); + + let history = session.history_labels(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + assert_eq!(session.history_labels(), history); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, selected); + + for params in [json!({}), json!({"tile": 1003, "enabled": false}), json!({"tile": u64::MAX, "enabled": false}), json!({"tile": 1001, "enabled": 1})] { + assert!(execute(&mut session, "bake.tile.set", ¶ms).is_err()); + assert_eq!(session.doc.project, selected); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { + let mut session = session(); + session.doc.baked.insert(0, BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32]))].into() }); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + + // Editing the checkboxes while a bake runs affects the next bake + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); + let before = session.doc.baked.clone(); + let output = task.run(&Progress::new()).unwrap(); + session.apply_bake(0, output).unwrap(); + + let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; + for row in pixels.chunks_exact(64) { + assert!(row[..32].iter().all(|value| *value > 0.99)); + assert!(row[32..].iter().all(|value| *value == 0.25)); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked, before); +} + +#[test] +fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { + let mut session = session(); + session.doc.baked.insert( + 0, + BakedMaps { + resolution: 64, + maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])), (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3]))].into(), + }, + ); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([0])); + + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64)); + for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) { + assert!(row[..64].iter().all(|value| *value > 0.99)); + assert!(row[64..].iter().all(|value| *value == 0.25)); + } + assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3); + assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4)); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.baked, session.doc.baked); +} + +#[test] +fn tile_selection_preserves_the_correct_udim_row() { + let mut mesh = primitives::udim_plane(); + let second_plane = mesh.uvs.len() / 2; + for uv in mesh.uvs.iter_mut().skip(second_plane) { + uv.x -= 1.0; + uv.y -= 1.0; + } + let mut session = Session::new_project("Vertical UV tiles", mesh, "builtin:udim_plane", None, 128).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1011]); + session.doc.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 64]))].into() }); + execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap(); + execute(&mut session, "bake.run", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2, "cpu": true})).unwrap(); + + let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; + assert!(pixels[..32 * 32].iter().all(|value| *value == 0.25)); + assert!(pixels[32 * 32..].iter().all(|value| *value > 0.99)); +} + +#[test] +fn excluded_tiles_without_previous_pixels_use_neutral_values() { + let mut session = session(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); + execute(&mut session, "bake.run", &json!({"maps": ["normal", "ambientOcclusion"], "cpu": true})).unwrap(); + let baked = &session.doc.baked[&0]; + for map in [BakedMap::Normal, BakedMap::AmbientOcclusion] { + for row in baked.maps[&map].chunks_exact(64 * map.components()) { + for pixel in row[..32 * map.components()].chunks_exact(map.components()) { + assert_eq!(pixel, &map.neutral()[..map.components()]); + } + } + } +} + +#[test] +fn no_selected_tiles_is_a_noop_and_old_projects_include_every_tile() { + let mut session = session(); + let serialized = serde_json::to_value(&session.doc.project).unwrap(); + assert!(serialized["texture_sets"][0].get("bake_excluded_tiles").is_none()); + let legacy: texturecraft_engine::core::Project = serde_json::from_value(serialized).unwrap(); + assert!(legacy.texture_sets[0].has_enabled_bake_tiles()); + + for tile in [1001, 1002] { + execute(&mut session, "bake.tile.set", &json!({"tile": tile, "enabled": false})).unwrap(); + } + let before = session.doc.project.clone(); + let history = session.history_labels(); + let result = execute(&mut session, "bake.run", &json!({"ts": "selected", "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([])); + assert_eq!(session.doc.project, before); + assert!(session.doc.baked.is_empty()); + assert_eq!(session.history_labels(), history); + assert!(session.bake_task(0).is_err()); + + execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap(); + assert!(session.doc.project.texture_sets[0].bake_excluded_tiles.is_empty()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +#[ignore] +fn partial_bake_timing() { + let mut session = session(); + execute(&mut session, "bake.run", &json!({"resolution": 256, "rays": 64, "cpu": true})).unwrap(); + for enabled in [true, false] { + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": enabled})).unwrap(); + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + let mut times = Vec::new(); + for _ in 0..5 { + let started = std::time::Instant::now(); + task.run(&Progress::new()).unwrap(); + times.push(started.elapsed()); + } + times.sort(); + eprintln!("{} of 2 UV tiles, 256 square, AO 64 rays, CPU: median {:?}, runs {:?}", if enabled { 2 } else { 1 }, times[2], times); + } +} diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs new file mode 100644 index 00000000..bdb984b5 --- /dev/null +++ b/crates/engine/tests/it/color_selection.rs @@ -0,0 +1,309 @@ +//! Color selection effects: editing their ID colors and picking them from the ID mesh map + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const TOP_LEFT_ID: [u8; 3] = [200, 30, 10]; +const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30]; +const BOTTOM_ID: [u8; 3] = [30, 10, 200]; +const NO_PART: [f32; 3] = [0.0, 0.0, 0.0]; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// An 8×8 ID map: two parts on the top half, one on the bottom half +fn id_map_png() -> Vec { + let image = image::RgbaImage::from_fn(8, 8, |x, y| { + let [red, green, blue] = match (x < 4, y < 4) { + (true, true) => TOP_LEFT_ID, + (false, true) => TOP_RIGHT_ID, + _ => BOTTOM_ID, + }; + image::Rgba([red, green, blue, 255]) + }); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +fn stored(id: [u8; 3]) -> [f32; 3] { + id.map(|channel| channel as f32 / 255.0) +} + +fn assert_close(actual: [f32; 3], expected: [f32; 3]) { + assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}"); +} + +/// A fill layer masked by a color selection that selects no part yet: (layer, effect) +fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) { + if with_id_map { + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + } + + let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap()); + execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); + let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + (layer, effect) +} + +fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> { + match &session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection { colors, .. } => colors.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +#[test] +fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + let center = Vec2::new(200.0, 200.0); + let hit = session.pick(center, session.viewport).unwrap(); + let (width, height) = session.caches[0].size; + let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick"); + + let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap(); + + assert_eq!(picked["index"], json!(1)); + assert_eq!(colors(&session, effect).len(), 2); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step"); +} + +#[test] +fn a_uv_pick_adds_the_color_there_or_replaces_one() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); + assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID)); + + let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap(); + assert_eq!(replaced["index"], json!(0)); + let picked = colors(&session, effect); + assert_eq!(picked.len(), 2); + assert_close(picked[0], stored(BOTTOM_ID)); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step"); +} + +#[test] +fn the_colors_param_replaces_the_list_in_one_undo_step() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)]; + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap(); + assert_eq!(colors(&session, effect), edited.to_vec()); + let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") }; + assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2)); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART]); +} + +#[test] +fn bad_colors_are_refused_and_change_nothing() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; + + for colors_param in &refused { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}"); + } + assert_eq!(colors(&session, effect), vec![NO_PART]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap(); + assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1"); +} + +#[test] +fn picking_explains_what_is_missing() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, false); + let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", ¶ms).unwrap_err().to_string(); + + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map")); + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point")); + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside")); + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7")); + assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`")); + + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap(); + assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection")); + assert_eq!(colors(&session, effect), vec![NO_PART]); +} + +#[test] +fn hostile_params_never_crash_the_color_selection_commands() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let hostile = [ + json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}), + json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}), + json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}), + json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}), + json!({"effect": u64::MAX, "uv": [0.5, 0.5]}), + ]; + + for params in &hostile { + let _ = execute(&mut session, "effect.colorSelection.pick", params); + let _ = execute(&mut session, "effect.set", params); + session.update(); + } +} + +#[test] +fn a_hidden_texture_set_does_not_block_a_pick_behind_it() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.update(); + let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap(); + let (base, ball) = (set_named("Base"), set_named("Ball")); + execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap(); + let (_, effect) = masked_layer(&mut session, true); + let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y})); + let ball_in_front = |session: &Session, y: f32| { + session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball)) + }; + + // Down the middle until a pixel where the hidden ball covers the base: the pick reads the base + execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap(); + let mut covered = None; + for y in (200..400).map(|y| y as f32) { + if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() { + covered = Some(y); + break; + } + } + let y = covered.expect("a pixel where the ball covers the base"); + assert_eq!(colors(&session, effect).len(), 2); + + execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap(); + assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it"); +} + +#[test] +fn malformed_replacement_indices_are_rejected_without_editing() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let history = session.history_labels(); + + for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] { + let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index})); + assert!(result.is_err(), "invalid index {index} was accepted: {result:?}"); + assert_eq!(colors(&session, effect), vec![NO_PART]); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn the_color_limit_rejects_additions_but_allows_replacement() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let full = vec![NO_PART; 256]; + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap(); + let history = session.history_labels(); + let project = session.doc.project.clone(); + + for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] { + assert!(execute(&mut session, "effect.colorSelection.pick", ¶ms).is_err()); + assert_eq!(colors(&session, effect), full); + assert_eq!(session.history_labels(), history); + } + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err()); + assert_eq!(session.history_labels(), history); + assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields"); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap(); + assert_eq!(colors(&session, effect).len(), 256); + assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID)); +} + +#[test] +fn inspect_exposes_the_selected_colors_and_tolerance() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap(); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap(); + let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap(); + let found = &layer["mask"]["effects"][0]; + assert_eq!(found["colors"], json!(colors(&session, effect))); + assert_eq!(found["tolerance"], json!(0.25)); +} + +#[test] +fn picks_use_the_working_texel_on_a_smaller_uv_tile() { + let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + for tile in [1001, 1002] { + session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap(); + } + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap(); + let (layer, effect) = masked_layer(&mut session, false); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap(); + let size = session.doc.project.texture_sets[0].size(); + let uv = [0.625, 0.25]; + let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap(); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]); + let before = colors(&session, effect); + let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]})); + assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample"); + assert_eq!(colors(&session, effect), before); +} + +#[test] +#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"] +fn benchmark_color_selection_edits() { + use std::time::{Duration, Instant}; + + const SAMPLES: u32 = 10; + for resolution in [256, 1024] { + let started = Instant::now(); + let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap(); + let (_, effect) = masked_layer(&mut session, true); + session.update(); + let construction = started.elapsed(); + + for count in [1, 256] { + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap(); + session.update(); + let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1}); + let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO); + for _ in 0..SAMPLES { + let started = Instant::now(); + execute(&mut session, "effect.colorSelection.pick", ¶ms).unwrap(); + command_time += started.elapsed(); + let started = Instant::now(); + session.update(); + composite_time += started.elapsed(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + session.update(); + } + println!( + "{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes", + command_time / SAMPLES, + composite_time / SAMPLES, + session.memory().total() + ); + } + } +} diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/it/content_effects.rs similarity index 100% rename from crates/engine/tests/content_effects.rs rename to crates/engine/tests/it/content_effects.rs diff --git a/crates/engine/tests/export_colour_space.rs b/crates/engine/tests/it/export_colour_space.rs similarity index 100% rename from crates/engine/tests/export_colour_space.rs rename to crates/engine/tests/it/export_colour_space.rs diff --git a/crates/engine/tests/it/filter_swap.rs b/crates/engine/tests/it/filter_swap.rs new file mode 100644 index 00000000..0bfa03f4 --- /dev/null +++ b/crates/engine/tests/it/filter_swap.rs @@ -0,0 +1,172 @@ +//! Swapping a filter effect's type in place through `effect.set {filter}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// A sphere project with its default layer selected +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap() +} + +/// Runs effect-adding `command` and returns the new effect, which it selects +fn add(s: &mut Session, command: &str, params: Value) -> LayerId { + execute(s, command, ¶ms).unwrap(); + let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) }; + + added +} + +/// A copy of effect `id` +fn effect(s: &Session, id: LayerId) -> Effect { + s.doc.project.effect(id).unwrap().1.clone() +} + +/// Ids of the selected layer's content effects, bottom first +fn content_order(s: &Session) -> Vec { + let layer = s.selected_layer().unwrap(); + s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect() +} + +#[test] +fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + assert_eq!(blur.name, "Blur", "a default name follows the new filter"); + assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false)); + assert_eq!(content_order(&s), vec![below, swapped, above]); +} + +#[test] +fn swapping_a_filter_keeps_a_name_the_user_chose() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap(); + + assert_eq!(effect(&s, id).name, "Flip"); +} + +#[test] +fn one_undo_restores_the_old_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + let restored = effect(&s, id); + assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind); + assert_eq!(restored.name, "Threshold"); +} + +#[test] +fn a_mask_refuses_a_content_only_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err(); + + assert!(err.to_string().contains("not on masks"), "{err}"); + assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); +} + +#[test] +fn a_mask_filter_swaps_in_place_on_the_mask() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); + assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4)); + let layer = s.selected_layer().unwrap(); + let mask_order: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask_order, vec![below, swapped, above]); +} + +#[test] +fn naming_the_current_filter_edits_it_in_place() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap(); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, id); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); +} + +#[test] +fn a_name_given_with_the_swap_wins() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap(); + + let swapped = effect(&s, id); + assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind); + assert_eq!(swapped.name, "Edges"); +} + +#[test] +fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); + let before = effect(&s, id); + + for refused in [ + json!({"effect": id.0, "filter": "grayscale"}), + json!({"effect": id.0, "filter": "nope"}), + json!({"effect": id.0, "filter": "levels"}), + json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}), + ] { + assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); + } + + assert_eq!(effect(&s, id), before); + // The last step is still the blend, opacity and name edit + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect(&s, id).name, "Invert"); +} + +#[test] +fn only_filter_effects_swap_and_only_to_filters() { + let mut s = session(); + let levels = add(&mut s, "effect.add.levels", json!({"target": "content"})); + let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); + assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); +} + +#[test] +fn invalid_swap_parameters_report_effect_set_and_preserve_history() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let before = effect(&s, id); + let history = s.history_labels(); + + let error = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "colorBalance", "shadows": "invalid", "name": "Changed"})).unwrap_err(); + + assert!(matches!(error, texturecraft_engine::EngineError::BadParams { ref cmd, .. } if cmd == "effect.set"), "{error}"); + assert_eq!(effect(&s, id), before); + assert_eq!(s.history_labels(), history); +} diff --git a/crates/engine/tests/filters.rs b/crates/engine/tests/it/filters.rs similarity index 100% rename from crates/engine/tests/filters.rs rename to crates/engine/tests/it/filters.rs diff --git a/crates/engine/tests/it/high_poly_missed.rs b/crates/engine/tests/it/high_poly_missed.rs new file mode 100644 index 00000000..c5b132fa --- /dev/null +++ b/crates/engine/tests/it/high_poly_missed.rs @@ -0,0 +1,57 @@ +use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed}; +use texturecraft_engine::geom::glam::Vec3; + +fn vertex(height: f32) -> Option { + Some(VertexReach { + low_position: Vec3::ZERO, + start: RayStart::Distance { up: Vec3::Y, scale: 1.0 }, + high_position: Vec3::new(0.0, height, 0.0), + high_facing: Vec3::Y, + name_matches: true, + }) +} + +fn reach(vertices: Vec>) -> Option { + Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false }) +} + +fn sets() -> Vec> { + vec![None, reach(vec![vertex(0.5), vertex(-0.25), None, None, None]), reach(vec![None, None, vertex(0.5), vertex(-0.25), None])] +} + +const DISTANCES: [(f32, f32); 3] = [(9.0, 9.0), (0.25, 0.25), (0.5, 0.125)]; + +#[test] +fn each_owning_set_uses_its_own_frontal_and_rear_distances() { + let reaches = sets(); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, None, 6), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + let expanded = [(9.0, 9.0), (0.5, 0.25), (0.5, 0.25)]; + assert_eq!(high_poly_missed(&reaches, &expanded, None, 6), vec![0.0; 6]); +} + +#[test] +fn selected_set_filter_leaves_other_sets_unmarked() { + let reaches = sets(); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + for only_set in [0, reaches.len(), usize::MAX] { + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]); + } +} + +#[test] +fn missing_reach_or_distances_leave_vertices_unmarked() { + assert_eq!(high_poly_missed(&[], &DISTANCES, None, 6), vec![0.0; 6]); + assert_eq!(high_poly_missed(&sets(), &[], None, 6), vec![0.0; 6]); + assert_eq!(high_poly_missed(&sets(), &DISTANCES[..2], None, 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(high_poly_missed(&sets(), &DISTANCES, None, 1), vec![1.0]); + assert!(high_poly_missed(&sets(), &DISTANCES, None, 0).is_empty()); +} + +#[test] +fn a_reached_vertex_is_not_overridden_by_a_later_set() { + let reaches = [reach(vec![vertex(0.5)]), reach(vec![vertex(0.5)])]; + let distances = [(0.5, 0.0), (0.25, 0.0)]; + assert_eq!(high_poly_missed(&reaches, &distances, None, 1), vec![0.0]); + assert_eq!(high_poly_missed(&reaches, &distances, Some(1), 1), vec![1.0]); +} diff --git a/crates/engine/tests/instances.rs b/crates/engine/tests/it/instances.rs similarity index 100% rename from crates/engine/tests/instances.rs rename to crates/engine/tests/it/instances.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs new file mode 100644 index 00000000..7f13db57 --- /dev/null +++ b/crates/engine/tests/it/main.rs @@ -0,0 +1,27 @@ +//! One integration-test executable avoids linking the same dependencies for every feature. +//! Keep feature tests in their own modules; the standalone session.rs target remains available. + +mod bake; +mod bake_resolution; +mod bake_settings; +mod bake_tiles; +mod color_selection; +mod content_effects; +mod export_colour_space; +mod filter_swap; +mod filters; +mod high_poly_missed; +mod instances; +mod materialcraft_link; +mod materialx; +mod materialx_import; +mod meshmap_import; +mod painter_gaps; +mod path_tool; +mod perf; +mod polygon_fill; +mod project_recovery; +mod sample; +mod tools; +mod udim; +mod uv_strokes; diff --git a/crates/engine/tests/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs similarity index 100% rename from crates/engine/tests/materialcraft_link.rs rename to crates/engine/tests/it/materialcraft_link.rs diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/it/materialx.rs similarity index 100% rename from crates/engine/tests/materialx.rs rename to crates/engine/tests/it/materialx.rs diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/it/materialx_import.rs similarity index 100% rename from crates/engine/tests/materialx_import.rs rename to crates/engine/tests/it/materialx_import.rs diff --git a/crates/engine/tests/it/meshmap_import.rs b/crates/engine/tests/it/meshmap_import.rs new file mode 100644 index 00000000..33dc2ec8 --- /dev/null +++ b/crates/engine/tests/it/meshmap_import.rs @@ -0,0 +1,298 @@ +//! Importing baked map files at once: each lands in the texture set and mesh map its name names + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The material ball: texture sets "Ball" and "Base" +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +/// A folder of 4×4 gray PNGs named `files`, each with its own gray level +fn bake_folder(test: &str, files: &[&str]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (index, file) in files.iter().enumerate() { + let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX); + image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); + } + dir +} + +fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value { + let files: Vec = files + .iter() + .map(|(file, map)| { + let path = dir.join(file).display().to_string(); + match map { + Some(map) => json!({"path": path, "map": map}), + None => json!({"path": path}), + } + }) + .collect(); + execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap() +} + +fn file_names(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap())) + .map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string()) + .collect() +} + +fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { + s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) +} + +#[test] +fn files_go_to_the_set_and_map_their_names_name() { + let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"]; + let dir = bake_folder("sets", &files); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + let assigned = &result["assigned"]; + assert_eq!(file_names(assigned).len(), 5, "{result}"); + for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { + assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); + assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}"); + } + assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); + assert_eq!(s.undo_label(), Some("Import baked maps")); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported image resources"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_given_map_overrides_the_name() { + let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + assert!(has_map(&s, 0, BakedMap::Thickness)); + assert!(has_map(&s, 1, BakedMap::Height)); + assert!(!has_map(&s, 1, BakedMap::Normal)); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_second_file_for_one_slot_is_left_out() { + let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]); + + assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]); + assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn an_undecodable_file_imports_nothing() { + let dir = bake_folder("undecodable", &["Ball_ao.png"]); + std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]}); + + let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); + + assert!(error.contains("Base_ao.png"), "{error}"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty())); + assert!(s.doc.resources.is_empty() && s.images.is_empty()); + assert_eq!(s.undo_label().map(str::to_string), label_before); + std::fs::remove_dir_all(dir).ok(); +} + +/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002 +fn tiled_session() -> Session { + Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap() +} + +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() { + let files = ["Plane_ao.1001.png", "plane-AO-1002.png"]; + let dir = bake_folder("tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + let baked = &s.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let middle_row = ao.len() / width / 2 * width; + assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn tiled_files_without_their_tiles_are_left_out_alone() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"]; + let dir = bake_folder("partial-tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]); + assert!(has_map(&s, 0, BakedMap::AmbientOcclusion)); + assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn nothing_matched_makes_no_undo_step() { + let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]); + + assert_eq!(file_names(&result["assigned"]), Vec::::new()); + assert_eq!(file_names(&result["unmatched"]).len(), 2); + assert_eq!(s.undo_label().map(str::to_string), label_before); + assert!(!s.modified); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn an_invalid_map_override_does_not_fall_back_to_the_file_name() { + let dir = bake_folder("invalid-map", &["Ball_ao.png"]); + let mut session = session(); + for map in [json!(true), json!(42), json!([]), json!({}), json!("unknown")] { + let params = json!({"files": [{"path": dir.join("Ball_ao.png"), "map": map}]}); + let result = execute(&mut session, "textureSet.meshMap.import", ¶ms); + assert!(result.is_err(), "invalid map {map} must be rejected: {result:?}"); + assert!(session.doc.resources.is_empty()); + assert!(!session.modified); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"] +fn benchmark_baked_map_import() { + use std::time::Instant; + use texturecraft_engine::core::BakeResolution; + + let dir = std::env::temp_dir().join(format!("texturecraft-import-benchmark-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (size, tiled) in [(1024, false), (2048, false), (1024, true)] { + let mut files = Vec::new(); + let mut encoded_bytes = 0; + for map in ["normal", "ao", "curvature"] { + for tile in 1001..=if tiled { 1002 } else { 1001 } { + let path = dir.join(format!("mesh_{map}.{tile}.png")); + image::RgbaImage::from_fn(size, size, |x, y| { + let value = (x.wrapping_mul(73) ^ y.wrapping_mul(151) ^ tile) as u8; + image::Rgba([value, value.wrapping_add(37), 255, 255]) + }) + .save(&path) + .unwrap(); + encoded_bytes += std::fs::metadata(&path).unwrap().len(); + files.push(json!({"path": path})); + } + } + let params = json!({"files": files}); + let mut milliseconds = Vec::new(); + for iteration in 0..6 { + let mesh = if tiled { primitives::udim_plane() } else { primitives::cube(2.0) }; + let mut session = Session::new_project("benchmark", mesh, "builtin:cube", None, 128).unwrap(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::from_pixels(size).unwrap(); + let started = Instant::now(); + let result = execute(&mut session, "textureSet.meshMap.import", ¶ms).unwrap(); + let elapsed = started.elapsed().as_secs_f64() * 1000.0; + assert_eq!(result["assigned"].as_array().unwrap().len(), files.len()); + assert_eq!(session.doc.baked[&0].maps.len(), 3); + if iteration > 0 { + milliseconds.push(elapsed); + } + } + milliseconds.sort_by(f64::total_cmp); + eprintln!( + "import size={size} tiles={} files={} encoded_bytes={encoded_bytes} median_ms={:.3} min_ms={:.3} max_ms={:.3}", + if tiled { 2 } else { 1 }, + files.len(), + milliseconds[2], + milliseconds[0], + milliseconds[4] + ); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn tiled_import_uses_new_images_when_resource_names_collide() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png"]; + let dir = bake_folder("collisions", &files); + let mut session = tiled_session(); + let old_bytes = std::fs::read(dir.join(files[0])).unwrap(); + for name in files { + session.import_resource_bytes(name, old_bytes.clone()).unwrap(); + } + let revision_before = session.revision; + + import(&mut session, &dir, &files.map(|file| (file, None))); + + let baked = &session.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let row = ao.len() / width / 2 * width; + assert!((ao[row + width / 4] - 20.0 / 255.0).abs() < 1e-5); + assert!((ao[row + 3 * width / 4] - 40.0 / 255.0).abs() < 1e-5); + assert_eq!(session.revision, revision_before + 1); + assert_eq!(session.doc.resources.len(), 4); + + session.undo().unwrap(); + assert_eq!(session.doc.resources.len(), 2); + assert_eq!(session.images.len(), 2); + session.redo().unwrap(); + assert_eq!(session.images.len(), 4); + assert!(has_map(&session, 0, BakedMap::AmbientOcclusion)); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn too_many_files_are_rejected_before_reading_any() { + let mut session = session(); + let files = vec![json!({"path": "Ball_ao.png"}); 513]; + let error = execute(&mut session, "textureSet.meshMap.import", &json!({"files": files})).unwrap_err().to_string(); + assert!(error.contains("at most 512 files"), "{error}"); + assert!(session.doc.resources.is_empty()); + assert!(!session.modified); +} + +#[test] +fn tga_maps_survive_undo_redo_and_project_reload() { + let dir = bake_folder("tga", &["Ball_normal.tga", "Base_ao.png"]); + let mut session = session(); + let result = import(&mut session, &dir, &[("Ball_normal.tga", None), ("Base_ao.png", None)]); + assert_eq!(result["assigned"].as_array().unwrap().len(), 2); + assert!(has_map(&session, 0, BakedMap::Normal)); + let image = session.images["Ball_normal.tga"].clone(); + + session.undo().unwrap(); + assert!(session.images.is_empty()); + session.redo().unwrap(); + assert_eq!(session.images["Ball_normal.tga"].rgba, image.rgba); + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.images["Ball_normal.tga"].rgba, image.rgba); + assert_eq!(reloaded.doc.baked, session.doc.baked); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs similarity index 100% rename from crates/engine/tests/painter_gaps.rs rename to crates/engine/tests/it/painter_gaps.rs diff --git a/crates/engine/tests/path_tool.rs b/crates/engine/tests/it/path_tool.rs similarity index 100% rename from crates/engine/tests/path_tool.rs rename to crates/engine/tests/it/path_tool.rs diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/it/perf.rs similarity index 100% rename from crates/engine/tests/perf.rs rename to crates/engine/tests/it/perf.rs diff --git a/crates/engine/tests/it/polygon_fill.rs b/crates/engine/tests/it/polygon_fill.rs new file mode 100644 index 00000000..6f5b5d0a --- /dev/null +++ b/crates/engine/tests/it/polygon_fill.rs @@ -0,0 +1,88 @@ +//! Polygon fill drag transitions preserve already painted targets + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::{glam::Vec2, primitives}; +use texturecraft_engine::{Session, execute}; + +#[test] +fn changing_layers_during_a_box_drag_preserves_the_first_fill() { + let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); + let first = session.selected_layer().unwrap(); + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + let second = session.selected_layer().unwrap(); + execute(&mut session, "layer.select", &json!({"layer": first.0})).unwrap(); + let history = session.history_labels().len(); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": second.0})).unwrap(); + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap(); + session.end_polygon_fill_box(); + + assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some(), "the first layer keeps its fill"); + assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_some(), "the new target receives the next fill"); + assert_eq!(session.history_labels().len(), history + 2, "each target has its own undo step"); + session.undo().unwrap(); + assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some()); + assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_none()); +} + +#[test] +fn changing_from_content_to_mask_during_a_box_drag_preserves_content() { + let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); + let layer = session.selected_layer().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap(); + let history = session.history_labels().len(); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap(); + session.end_polygon_fill_box(); + + assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some(), "switching to the mask keeps the content fill"); + assert_eq!(session.history_labels().len(), history + 2); + session.undo().unwrap(); + assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some()); + assert!(session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.is_empty()); +} + +#[test] +#[ignore = "release performance measurement"] +fn benchmark_live_box_fill() { + use std::hint::black_box; + use std::time::Instant; + + for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] { + let triangles = mesh.triangle_count(); + let mut session = Session::new_project("benchmark", mesh, "test", None, 1024).unwrap(); + let viewport = Vec2::new(1920.0, 1080.0); + let start = Instant::now(); + session.drag_polygon_fill_box(viewport * 0.4, viewport * 0.6, viewport).unwrap(); + let first_ms = start.elapsed().as_secs_f64() * 1000.0; + let mut times = Vec::new(); + for step in 1..=12 { + let radius = 0.1 + step as f32 * 0.02; + let start = Instant::now(); + black_box(session.drag_polygon_fill_box(viewport * (0.5 - radius), viewport * (0.5 + radius), viewport).unwrap()); + times.push(start.elapsed().as_secs_f64() * 1000.0); + } + let (corner, opposite) = (viewport * 0.16, viewport * 0.84); + session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + let start = Instant::now(); + for _ in 0..1000 { + black_box(session.drag_polygon_fill_box(corner, opposite, viewport).unwrap()); + } + let unchanged_us = start.elapsed().as_secs_f64() * 1000.0; + session.end_polygon_fill_box(); + let start = Instant::now(); + session.update(); + let composite_ms = start.elapsed().as_secs_f64() * 1000.0; + times.sort_by(f64::total_cmp); + let memory = session.memory(); + eprintln!( + "{name}: {triangles} triangles, first={first_ms:.3} ms, growing median={:.3} ms max={:.3} ms, unchanged mean={unchanged_us:.3} us, composite={composite_ms:.3} ms, pixels={} bytes composites={} bytes cache={} bytes", + times[6], times[11], memory.pixels, memory.composites, memory.cache + ); + } +} diff --git a/crates/engine/tests/project_recovery.rs b/crates/engine/tests/it/project_recovery.rs similarity index 100% rename from crates/engine/tests/project_recovery.rs rename to crates/engine/tests/it/project_recovery.rs diff --git a/crates/engine/tests/sample.rs b/crates/engine/tests/it/sample.rs similarity index 100% rename from crates/engine/tests/sample.rs rename to crates/engine/tests/it/sample.rs diff --git a/crates/engine/tests/tools.rs b/crates/engine/tests/it/tools.rs similarity index 100% rename from crates/engine/tests/tools.rs rename to crates/engine/tests/it/tools.rs diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/it/udim.rs similarity index 87% rename from crates/engine/tests/udim.rs rename to crates/engine/tests/it/udim.rs index bcfab00b..aff12622 100644 --- a/crates/engine/tests/udim.rs +++ b/crates/engine/tests/it/udim.rs @@ -48,20 +48,24 @@ fn paint_red_at(s: &mut Session, p: Vec3) { #[test] fn uv_tiles_are_detected_and_inspected() { - let mut s = session(); - let set = execute(&mut s, "textureSet.inspect", &Value::Null).unwrap(); + let mut session = session(); + let set = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap(); assert_eq!(set["uvTiles"], json!([1001, 1002])); assert_eq!(set["size"], json!([2 * RES, RES])); - assert_eq!(set["tiles"], json!([{ "udim": 1001, "block": [0, 0], "resolution": RES }, { "udim": 1002, "block": [1, 0], "resolution": RES }])); - assert_eq!(s.caches[0].size, (2 * RES, RES)); - // Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh. - execute(&mut s, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap(); - assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty()); - execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap(); - assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic"); - execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap(); - assert_eq!(s.doc.project.texture_sets[0].uv_tiles, vec![1001]); - assert_eq!(s.caches[0].size, (RES, RES)); + assert_eq!( + set["tiles"], + json!([{ "udim": 1001, "block": [0, 0], "resolution": RES, "bakeEnabled": true }, { "udim": 1002, "block": [1, 0], "resolution": RES, "bakeEnabled": true }]) + ); + assert_eq!(session.caches[0].size, (2 * RES, RES)); + + // Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh + execute(&mut session, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap(); + assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty()); + execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap(); + assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic"); + execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, vec![1001]); + assert_eq!(session.caches[0].size, (RES, RES)); } #[test] diff --git a/crates/engine/tests/it/uv_strokes.rs b/crates/engine/tests/it/uv_strokes.rs new file mode 100644 index 00000000..18a33fda --- /dev/null +++ b/crates/engine/tests/it/uv_strokes.rs @@ -0,0 +1,105 @@ +//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// Texture size: 1e-4 UV is 0.0256 texels +const RESOLUTION: u32 = 256; + +/// A sphere project painting red with `brush` settings (the UI's 0–100 scales) +fn red_brush_session(brush: serde_json::Value) -> Session { + let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &brush).unwrap(); + session +} + +/// The composite base color at texel (`x`, `y`) +fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] { + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Whether the composite base color at (`u`, `v`) is the painted red +fn red_at(session: &Session, u: f32, v: f32) -> bool { + let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +#[test] +fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() { + // 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap(); + + for u in [0.1, 0.5, 0.9] { + assert!(red_at(&session, u, 0.5), "painted at u = {u}"); + } +} + +#[test] +fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() { + // 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off before reaching the texture + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap(); + + assert!(red_at(&session, 0.55, 0.5), "the last segment is painted"); + assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start"); +} + +#[test] +fn each_sample_of_a_stroke_stamps_new_noise() { + // A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5 + let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap(); + + let patch = |centre_x: u32| -> Vec<[f32; 3]> { + (centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect() + }; + let first_stamp = patch(64); + assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted"); + assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise"); +} + +#[test] +fn a_hostile_segment_stays_bounded() { + // The finest brush the settings allow: 2e-5 UV between stamps + let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0})); + + let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]})); + + assert!(result.is_ok(), "{result:?}"); +} + +#[test] +fn a_light_pressure_diagonal_reaches_the_far_corner() { + let mut session = red_brush_session(json!({"size": 0.2, "minSize": 0.0, "spacing": 1.0, "hardness": 90})); + + // Half pressure reaches the minimum stamp step: a diagonal needs about 142k stamps + session.begin_stroke_uv([0.0, 0.0].into(), 0.5).unwrap(); + session.continue_stroke_uv([1.0, 1.0].into(), 0.5); + session.end_stroke().unwrap(); + session.update(); + + assert!(red_at(&session, 0.5, 0.5), "the diagonal paints through its midpoint"); + assert!(red_at(&session, 0.97, 0.97), "the diagonal reaches the far corner"); +} + +#[test] +fn decreasing_pressure_does_not_stamp_behind_a_turn() { + let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "spacing": 100.0, "hardness": 90})); + + session.begin_stroke_uv([0.25, 0.5].into(), 1.0).unwrap(); + session.continue_stroke_uv([0.33, 0.5].into(), 1.0); + session.continue_stroke_uv([0.33, 0.6].into(), 0.1); + session.end_stroke().unwrap(); + session.update(); + + assert!(red_at(&session, 0.33, 0.55), "the new segment is painted"); + assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..4dd04032 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -105,6 +105,42 @@ fn polygon_fill_and_color_picker() { assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } +#[test] +fn polygon_fill_boxes_survive_hostile_params() { + let hostile = [ + json!({"x0": 1e30, "y0": -1e30, "x1": f64::MAX, "y1": 0, "viewport": [1e9, 1e9]}), + json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0, "viewport": [16, 16]}), + json!({"uv0": [1e30, -1e30], "uv1": [0, 0]}), + json!({"uv0": [0.5], "uv1": "x", "uv": [f64::MIN, 2]}), + json!({"hitTest": "nope", "visibleOnly": "yes", "mode": 7}), + ]; + for visible_only in [true, false] { + for hit_test in ["intersection", "containedCenter"] { + let mut session = session(); + execute(&mut session, "tool.polygonFill", &Value::Null).unwrap(); + execute(&mut session, "tool.fillSelection", &json!({"hitTest": hit_test, "visibleOnly": visible_only})).unwrap(); + for params in &hostile { + let _ = execute(&mut session, "tool.click", params); + let _ = execute(&mut session, "tool.fillSelection", params); + session.update(); + } + } + } +} + +/// A small project still gets the production bake defaults; only panic_hunt overrides them. +#[test] +fn new_project_keeps_full_resolution_bake_defaults() { + let s = session(); + assert!(!s.doc.project.texture_sets.is_empty()); + for texture_set in &s.doc.project.texture_sets { + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.bake, texturecraft_engine::core::BakeSettings::default()); + assert_eq!(texture_set.bake.common.output_size(), (2048, 2048)); + assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 64); + } +} + /// Every command must return Ok or Err — never panic — for hostile params. #[test] fn panic_hunt() { @@ -122,6 +158,11 @@ fn panic_hunt() { } for p in &hostile { let mut s = session(); + // Match the 256px fixture: otherwise empty/irrelevant bake.run params perform + // repeated 2048px default bakes. Keep every input, ray count and fresh session. + for texture_set in &mut s.doc.project.texture_sets { + texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256; + } let _ = execute(&mut s, spec.id, p); s.update(); } @@ -380,3 +421,28 @@ fn background_resizes_match_the_command_and_keep_later_edits() { b.update(); assert_eq!(b.caches[0].size, (512, 512)); } + +#[test] +fn curvature_generators_take_a_mode_and_detail_sizes() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities"})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""mode":"Cavities""#) && inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}"); + + let too_few = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, 0.5]})); + assert!(too_few.is_err(), "sizes takes one weight per detail size"); + let not_numbers = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, "a", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]})); + assert!(not_numbers.is_err(), "a size that isn't a number is rejected, not skipped"); + let unknown = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": "ridges"})); + assert!(unknown.is_err(), "unknown modes are rejected"); + let wrong_type = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": 1, "level": 0.1})); + assert!(wrong_type.is_err(), "a mode must be a string and an invalid edit must be rejected"); + let dirt = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "mode": "edges"})); + assert!(dirt.is_err(), "only curvature generators have a mode"); + assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); +} diff --git a/crates/formats/README.md b/crates/formats/README.md index 7b28004e..a52e80a5 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -145,6 +145,11 @@ pub fn load_project(path: &Path) -> Result; // native allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless). Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE. +Project format version 2 stores baked maps in uniform UV tile blocks, independent of working +tile-resolution overrides. Older projects load their stored bake pixels as-is, without converting +the old layout; their appearance may change until rebaked. Painted layers and cage/skew correction +maps retain their working atlas layout. + Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`), checks every tile against its texture set's resolution and component count, rejects repeated or out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f8fc1b97..24fc9833 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -596,7 +596,9 @@ impl Sampler<'_> { fn baked(&self, m: BakedMap, at: At) -> [f32; 3] { match at { - At::Texel(x, y) if self.set.baked.contains(&m) => self.baked.sample(m, x, y, (self.res, self.comp.height)).unwrap_or(m.neutral()), + At::Texel(x, y) if self.set.baked.contains(&m) => { + self.baked.sample_working(m, x, y, (self.res, self.comp.height), &self.scales).unwrap_or(m.neutral()) + } _ => m.neutral(), } } diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 49e1e014..85590d9d 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -21,20 +21,27 @@ pub fn decode_image(bytes: &[u8]) -> Result { /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the /// header, before any pixel is decoded or allocated. pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result { - let reader = + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; - let (w, h) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; - if w == 0 || h == 0 || w > MAX_IMAGE_SIZE || h > MAX_IMAGE_SIZE { - return Err(FormatError::TooLarge(format!("image is {w}x{h} (limit {MAX_IMAGE_SIZE})"))); + + // TGA has no magic signature; its decoder validates the header when no format was recognized + let format = reader.format().unwrap_or(image::ImageFormat::Tga); + reader.set_format(format); + + let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; + if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE { + return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})"))); } - if u64::from(w) * u64::from(h) > max_texels { - return Err(FormatError::TooLarge(format!("image is {w}x{h}, more than {max_texels} texels"))); + if u64::from(width) * u64::from(height) > max_texels { + return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels"))); } - let img = crate::guard("image", || image::load_from_memory(bytes).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?; - let srgb = !matches!(img, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); - let f = img.into_rgba32f(); - let (width, height) = f.dimensions(); - let rgba = f.pixels().map(|p| p.0).collect(); + + let image = + crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?; + let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); + let float_image = image.into_rgba32f(); + let (width, height) = float_image.dimensions(); + let rgba = float_image.pixels().map(|pixel| pixel.0).collect(); Ok(DecodedImage { width, height, rgba, srgb }) } @@ -69,6 +76,19 @@ mod tests { assert!(coverage_png(2, 2, &[0], [255; 3]).is_err()); } + #[test] + fn tga_without_a_magic_signature_decodes_within_the_texel_budget() { + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap(); + let image = decode_image_within(&bytes, 16).unwrap(); + assert_eq!((image.width, image.height), (4, 4)); + assert!((image.rgba[0][1] - 0.2).abs() < 1e-6); + assert!(image.srgb); + let header = &bytes[..18]; + assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_)))); + assert!(decode_image(header).is_err()); + } + #[test] fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() { let png = { diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 3d8d35f7..eef089a8 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -499,6 +499,8 @@ fn load(reader: R) -> Result { // Ignore other entries from newer minor revisions } + pf.project.format_version = FORMAT_VERSION; + if recovered { pf.warnings.push( "Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(), diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index cc2bd385..c0870f01 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -82,6 +82,26 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn legacy_bakes_load_as_is_without_layout_conversion() { + let mut sample = sample(); + sample.pf.project.format_version = 1; + sample.pf.pixels.layers.clear(); + let set = &mut sample.pf.project.texture_sets[0]; + set.resolution = 256; + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let pixels: Vec = (0..16).flat_map(|y| (0..32).map(move |x| (y * 32 + x) as f32)).collect(); + sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }); + + let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap(); + assert_eq!(loaded.project.format_version, FORMAT_VERSION); + assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout"); + assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout"); + let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap(); + assert_same(&loaded, &reopened); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn save_and_load_through_files() { diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..917f5838 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4}; use crate::{GeomError, Result}; +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -107,6 +110,47 @@ impl Mesh { .collect() } + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + // Signed zero denotes the same position on either side of an imported seam + let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); + let mut seams = vec![Vec::new(); self.materials.len().max(1)]; + // Match across materials before grouping the lines for texture-set visibility + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for material in 0..seams.len() { + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue }; + + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(edge).or_default().push((pair.0, pair.1, material)); + } + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + for pairs in sides.into_values() { + let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; + + if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + for (from, to, material) in pairs { + if let Some(edges) = seams.get_mut(material) { + edges.push((from.min(to), from.max(to))); + } + } + } + } + for edges in &mut seams { + edges.sort_unstable(); + edges.dedup(); + } + + seams + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -433,6 +477,55 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + + #[test] + fn uv_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = quad(); + mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn uv_seams_between_materials_belong_to_both_materials() { + let mut mesh = quad(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + mesh.materials.push("second".into()); + mesh.submeshes[0].count = 3; + mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); + + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.uvs[4] = mesh.uvs[0]; + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 6403faed..69fab43b 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -63,9 +63,17 @@ impl Builder { } } + /// The mesh of one material, with tangents. fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - let mut m = Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -75,9 +83,7 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }; - m.compute_tangents(); - m + } } } @@ -189,6 +195,132 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize }); } +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; @@ -340,6 +472,8 @@ pub fn builtin(id: &str) -> Option { "plane" => plane(2.0, 16), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), _ => return None, }) } @@ -396,6 +530,22 @@ mod tests { assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + #[test] fn material_ball_has_two_materials() { let m = material_ball(); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..307ccd7f 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -29,4 +29,4 @@ pub use path::{Lasso, spline}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; -pub use visibility::EyeDepth; +pub use visibility::{EyeDepth, screen_point}; diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index 01ce84f8..ed7c575e 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -2,11 +2,26 @@ //! rendered once at the start of a stroke. use rayon::prelude::*; -use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; -use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; +use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; +/// Largest buffer side in pixels. +const MAX_SIZE: u32 = 4096; + +/// Clip-space w below which a vertex counts as behind the camera. +pub const MIN_CLIP_W: f32 = 1e-5; + +/// Screen area (pixels squared) below which a triangle is skipped as degenerate. +const MIN_SCREEN_AREA: f32 = 1e-9; + +/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours. +const EDGE_TOLERANCE: f32 = 1e-4; + +/// [`EyeDepth::bias`] as a fraction of the scene radius. +const BIAS_PER_RADIUS: f32 = 0.004; + /// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty). #[derive(Clone, Debug)] pub struct EyeDepth { @@ -15,73 +30,133 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`]. + pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } +/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera. +pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option { + let clip = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size) +} + impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`]. pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { - let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096)); - let aspect = w as f32 / h as f32; - let vp = camera.view_proj(aspect); + Self::rasterize(mesh, camera, width, height, false) + } + + /// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`]. + pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, true) + } + + /// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set. + fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth { + // Capping storage dimensions must not change the camera's projection + let projection = camera.proj(width.max(1) as f32 / height.max(1) as f32); + let view = camera.view(); + let view_proj = projection * view; + let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() }; + let inverse_projection = projection.inverse(); + let clip_depth = |z: f32| { + let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0); + depth_key(-point.z / point.w) + }; + let depth_range = clip_depth(0.0)..=clip_depth(1.0); + let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); + let size = Vec2::new(width as f32, height as f32); let eye = camera.eye(); - // Project every vertex once. - let clip: Vec = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect(); - let screen: Vec> = - clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect(); - let dist_v: Vec = mesh.positions.iter().map(|p| p.distance(eye)).collect(); - let bands = (h as usize).div_ceil(BAND); - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in 0..mesh.triangle_count() { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0); - let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32); - if y1 <= y0 || !y0.is_finite() || !y1.is_finite() { + // Brush depth closes seams, but expanding triangle IDs can expose hidden faces at silhouettes + let edge_tolerance = if record_triangles { 0.0 } else { EDGE_TOLERANCE }; + + let screen: Vec> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); + // Inverse view depth is affine in perspective and avoids the precision loss of normalized clip depth + let vertex_depth: Vec = mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect(); + + // Bin each triangle into the bands of rows it covers + let mut bands: Vec> = vec![Vec::new(); (height as usize).div_ceil(BAND)]; + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; + + let top = first.y.min(second.y).min(third.y).floor().max(0.0); + let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y); + if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } - let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + + let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let mut dist = vec![f32::MAX; (w * h) as usize]; - dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| { - let row0 = bi * BAND; - let nrows = rows.len() / w as usize; - for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { - let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]); - let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0); - if area.abs() < 1e-9 { + + let mut dist = vec![f32::MAX; (width * height) as usize]; + let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() }; + let band_len = BAND * width as usize; + let mut triangle_bands: Vec> = triangle.chunks_mut(band_len).map(Some).collect(); + triangle_bands.resize_with(dist.len().div_ceil(band_len), || None); + dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| { + let first_row = band * BAND; + let row_count = band_dist.len() / width as usize; + for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { + let Some(corners) = mesh.tri(candidate as usize) else { continue }; + let [first, second, third] = corners; + let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third)) + else { + continue; + }; + + let corner_depth = corners.map(|vertex| vertex_depth.get(vertex).copied().unwrap_or(f32::MAX)); + let area = (*second_point - *first_point).perp_dot(*third_point - *first_point); + if area.abs() < MIN_SCREEN_AREA { continue; } - let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize; - let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize; - let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize; - let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize; - for y in y0.max(row0)..y1 { - for x in x0..x1.min(w as usize) { - let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); - let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area; - let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area; - let w2 = 1.0 - w0 - w1; - if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 { + + let low = first_point.min(*second_point).min(*third_point).floor(); + let high = first_point.max(*second_point).max(*third_point).ceil(); + let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize)); + let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize); + for row in top.max(first_row)..bottom { + for column in left..right { + let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5); + let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area; + let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area; + let third_weight = 1.0 - first_weight - second_weight; + if first_weight < -edge_tolerance || second_weight < -edge_tolerance || third_weight < -edge_tolerance { continue; } - let d = w0 * da + w1 * db + w2 * dc; - if let Some(slot) = rows.get_mut((y - row0) * w as usize + x) - && d < *slot + + let depth = first_weight * corner_depth[0] + second_weight * corner_depth[1] + third_weight * corner_depth[2]; + let at = (row - first_row) * width as usize + column; + if let Some(slot) = band_dist.get_mut(at) + && depth_range.contains(&depth) + && depth < *slot { - *slot = d; + *slot = depth; + if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) { + *nearest = candidate; + } } } } } + + // Convert only the winning depths to eye distances for brush visibility queries + for (row, distances) in band_dist.chunks_mut(width as usize).enumerate() { + let view_y = (1.0 - (first_row as f32 + row as f32 + 0.5) / size.y * 2.0) / projection.y_axis.y; + for (column, distance) in distances.iter_mut().enumerate().filter(|(_, distance)| **distance != f32::MAX) { + let view_x = ((column as f32 + 0.5) / size.x * 2.0 - 1.0) / projection.x_axis.x; + let radial_squared = view_x * view_x + view_y * view_y; + *distance = if camera.ortho { (radial_squared + *distance * *distance).sqrt() } else { (radial_squared + 1.0).sqrt() / -*distance }; + } + } }); - EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 } + + EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS } } /// Whether world point `p` is visible (not hidden behind other geometry, inside the view). diff --git a/crates/paint/tests/visibility.rs b/crates/paint/tests/visibility.rs new file mode 100644 index 00000000..2c4cd77e --- /dev/null +++ b/crates/paint/tests/visibility.rs @@ -0,0 +1,99 @@ +//! Visibility agrees with the surface under each pixel + +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_paint::EyeDepth; + +#[test] +fn a_large_front_triangle_occludes_a_small_rear_triangle() { + let positions = vec![ + Vec3::new(-4.0, -4.0, 0.0), + Vec3::new(4.0, -4.0, 0.0), + Vec3::new(0.0, 4.0, 0.0), + Vec3::new(-0.5, -0.5, -1.0), + Vec3::new(0.5, -0.5, -1.0), + Vec3::new(0.0, 0.5, -1.0), + ]; + let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 6], (0..6).collect(), "m").unwrap(); + + for ortho in [false, true] { + let camera = OrbitCamera { pitch: 0.0, ortho, ..Default::default() }; + let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128); + assert_eq!(depth.triangle[64 * 128 + 64], 0, "orthographic: {ortho}"); + assert!(!depth.visible(Vec3::new(0.0, 0.0, -1.0)), "the rear face is hidden"); + assert!(depth.visible(Vec3::ZERO), "the front face is visible"); + } +} + +#[test] +#[ignore = "release performance measurement"] +fn benchmark_eye_depth() { + use std::hint::black_box; + use std::time::Instant; + use texturecraft_geom::primitives; + + for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] { + let mut camera = OrbitCamera::default(); + let (low, high) = mesh.bounds(); + camera.frame(low, high); + for triangles in [false, true] { + let mut times = Vec::new(); + for iteration in 0..12 { + let start = Instant::now(); + black_box(if triangles { EyeDepth::render_with_triangles(&mesh, &camera, 960, 540) } else { EyeDepth::render(&mesh, &camera, 960, 540) }); + if iteration >= 2 { + times.push(start.elapsed().as_secs_f64() * 1000.0); + } + } + times.sort_by(f64::total_cmp); + eprintln!("{name}: {} triangles, record={triangles}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[5], times[0], times[9]); + } + } +} + +#[test] +fn perspective_depth_matches_ray_intersections() { + use texturecraft_geom::Bvh; + + let positions = vec![Vec3::new(-3.0, -2.0, 2.0), Vec3::new(3.0, -2.0, -2.0), Vec3::new(0.0, 3.0, 0.0)]; + let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap(); + let camera = OrbitCamera { pitch: 0.0, ..Default::default() }; + let bvh = Bvh::new(&mesh); + let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128); + + for (x, y) in [(40, 60), (64, 64), (88, 60)] { + let ndc = Vec2::new((x as f32 + 0.5) / 64.0 - 1.0, 1.0 - (y as f32 + 0.5) / 64.0); + let ray = camera.ray(ndc, 1.0); + let hit = bvh.closest(ray.origin, ray.dir, f32::MAX).unwrap(); + let expected = (ray.origin + ray.dir * hit.t).distance(camera.eye()); + assert!((depth.dist[y * 128 + x] - expected).abs() < 0.001, "pixel {x},{y}: {} vs {expected}", depth.dist[y * 128 + x]); + } +} + +#[test] +fn capped_buffers_keep_the_requested_viewport_aspect() { + let positions = vec![Vec3::new(4.0, -1.0, 0.0), Vec3::new(7.0, -1.0, 0.0), Vec3::new(5.5, 1.0, 0.0)]; + let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap(); + let camera = OrbitCamera { pitch: 0.0, ..Default::default() }; + let depth = EyeDepth::render_with_triangles(&mesh, &camera, 8192, 1024); + let point = camera.project(Vec3::new(5.5, 0.0, 0.0), 8.0).unwrap(); + let x = ((point.x * 0.5 + 0.5) * depth.width as f32) as usize; + let y = ((0.5 - point.y * 0.5) * depth.height as f32) as usize; + + assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position after the buffer is capped"); +} + +#[test] +fn triangle_ids_do_not_expand_hidden_cube_faces_past_the_silhouette() { + use std::collections::HashSet; + use texturecraft_geom::{NO_TRI, primitives}; + + let mesh = primitives::cube(1.0); + let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.4, ..Default::default() }; + let (low, high) = mesh.bounds(); + camera.frame(low, high); + let depth = EyeDepth::render_with_triangles(&mesh, &camera, 400, 400); + let visible: HashSet<_> = depth.triangle.iter().copied().filter(|triangle| *triangle != NO_TRI).collect(); + + assert_eq!(visible.len(), mesh.triangle_count() / 2, "only the three front faces own screen pixels"); +} diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs new file mode 100644 index 00000000..8dbc4927 --- /dev/null +++ b/crates/render/src/bake_visualization.rs @@ -0,0 +1,12 @@ +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly + +/// Which parts of the bake setup the 3D view draws +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BakeVisualization { + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, + /// Draw the cage, seams and low poly of only this texture set + pub only_set: Option, +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs new file mode 100644 index 00000000..3ed4f13f --- /dev/null +++ b/crates/render/src/cage_gpu.rs @@ -0,0 +1,9 @@ +/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs +pub(crate) struct CageGpu { + /// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners` + pub(crate) topology: u64, + pub(crate) corners: wgpu::Buffer, + pub(crate) corner_count: u32, + pub(crate) edges: wgpu::Buffer, + pub(crate) edge_index_count: u32, +} diff --git a/crates/render/src/high_poly_gpu.rs b/crates/render/src/high_poly_gpu.rs new file mode 100644 index 00000000..97da6861 --- /dev/null +++ b/crates/render/src/high_poly_gpu.rs @@ -0,0 +1,11 @@ +/// The high poly bake mode draws over the low poly +pub(crate) struct HighPolyGpu { + /// Which mesh the buffers hold + pub(crate) id: u64, + pub(crate) vertices: wgpu::Buffer, + pub(crate) vertex_count: usize, + pub(crate) indices: wgpu::Buffer, + pub(crate) index_count: u32, + /// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it + pub(crate) missed: wgpu::Buffer, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 01df6c30..bb0967c7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,18 +13,25 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_visualization; +mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_bake; pub mod gpu_trace; #[cfg(not(target_arch = "wasm32"))] pub mod headless; +mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; pub mod readback; pub mod renderer; +pub mod set_highlight; mod subdivide; pub mod trace; +mod uv_seam_gpu; +pub use bake_visualization::BakeVisualization; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; +pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index bf811478..4bfb13dc 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -1,27 +1,46 @@ //! Debug textures for the mesh-map view. use texturecraft_compose::BakedMaps; -use texturecraft_core::BakedMap; -use texturecraft_texel::linear_to_srgb; +use texturecraft_core::{BakedMap, BlockScales}; /// RGBA8 of baked map `m` resampled to `size × size` stretched over the map (mid gray where not /// baked). Scalar maps are shown as grayscale; ID maps as their colors. Values are display /// (sRGB) encoded. -pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec { +pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_size: (u32, u32), scales: &BlockScales) -> Vec { let size = size.max(1); let mut out = vec![128u8; (size * size * 4) as usize]; let Some(b) = baked.filter(|b| b.maps.contains_key(&m)) else { return out }; + for y in 0..size { for x in 0..size { - let v = b.sample(m, x, y, (size, size)).unwrap_or([0.5; 3]); + let uv = [(x as f32 + 0.5) / size as f32, (y as f32 + 0.5) / size as f32]; + let v = scales.bake_uv(uv, working_size).and_then(|uv| b.sample_uv(m, uv)).unwrap_or([0.5; 3]); let i = ((y * size + x) * 4) as usize; for k in 0..3 { - // Data maps are shown as stored, i.e. treated as display values. + // Data maps are shown as stored out[i + k] = (v[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } out[i + 3] = 255; } } - let _ = linear_to_srgb; out } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use texturecraft_core::TextureSet; + + #[test] + fn mesh_map_preview_places_bake_detail_in_the_working_tile() { + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let pixels = (0..128).flat_map(|y| (0..256).map(move |x| ((x % 128) + y) as f32 / 255.0)).collect(); + let baked = BakedMaps { resolution: 256, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }; + let preview = mesh_map_rgba(Some(&baked), BakedMap::AmbientOcclusion, 512, set.size(), &set.block_scales()); + assert_eq!(preview[(240 * 512 + 376) * 4], 240); + assert_eq!(preview[(400 * 512 + 500) * 4], 128, "unused working block area stays neutral"); + } +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ea4757d5..ad2bc2bf 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,9 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::bake_visualization::BakeVisualization; +use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; +use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; +use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; +use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -76,6 +81,8 @@ struct GlobalsRaw { fwd: [f32; 4], disp: [f32; 4], refr: [f32; 4], + highlight: [f32; 4], + highlight_shift: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -96,6 +103,15 @@ struct BlitRaw { dst: [f32; 4], } +/// Width of the highlighted set's edge lines, in pixels +const HIGHLIGHT_WIDTH_PX: f32 = 1.5; + +/// Opacity of the highlighted set's edge lines +const HIGHLIGHT_OPACITY: f32 = 0.9; + +/// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`) +const HIGHLIGHT_SHIFTS: u32 = 4; + /// How the material is shaded (from the project's display settings and the view mode). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Shade { @@ -134,6 +150,8 @@ pub struct Shade { pub grain: f32, /// Draw the mesh edges over the shaded 3D view (depth tested). pub wireframe_3d: bool, + /// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag) + pub highlight: Option, /// Specular/glossiness shading: base color is the diffuse color and the Specular channel the /// F0 color (roughness arrives as 1 - glossiness from the display conversion). pub spec_gloss: bool, @@ -159,6 +177,8 @@ pub struct Shade { /// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in /// the vertex shader at the height-to-normal strength. pub displacement: bool, + /// Bake mode's high poly, cage and UV seams over the 3D view + pub bake: Option, } /// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the @@ -235,6 +255,7 @@ impl Default for Shade { sharpen: 0.0, grain: 0.0, wireframe_3d: false, + highlight: None, spec_gloss: false, parallax: false, taa: false, @@ -244,6 +265,7 @@ impl Default for Shade { sss_blur: None, refraction: false, displacement: false, + bake: None, } } } @@ -513,6 +535,13 @@ pub struct Renderer { uv_pipeline: wgpu::RenderPipeline, wire_pipeline: wgpu::RenderPipeline, wire3d_pipeline: wgpu::RenderPipeline, + /// The highlighted set's mesh edges, wider and in the highlight color + highlight_pipeline: wgpu::RenderPipeline, + /// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams + bake_high_pipeline: wgpu::RenderPipeline, + cage_pipeline: wgpu::RenderPipeline, + cage_wire_pipeline: wgpu::RenderPipeline, + uv_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -546,6 +575,10 @@ pub struct Renderer { /// accumulation. content_rev: u64, mesh: Option, + bake_high: Option, + /// Each texture set's cage, by set index + cages: Vec>, + uv_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -791,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 { const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); +/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves +const SHADOW_SLOPE_BIAS: f32 = 1.5; + +/// Anisotropic filtering of the texture sets' sampler +const MAX_ANISOTROPY: u16 = 8; + +/// Size of the environment texture before the first environment loads +const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256]; + impl Renderer { /// `target_format`: the format of the pass [`Renderer::blit`] draws into. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer { let shader = |label: &str, source: &str| { device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }) }; - let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"))); + let module = + shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl"))); let util_module = shader("tc_util", include_str!("shaders/util.wgsl")); let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl"))); let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl"))); - let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { + + let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }) }; - let globals_bgl = bgl( + let globals_bind_group_layout = bind_group_layout( "tc_globals", &[ uniform_entry(0), @@ -821,44 +865,47 @@ impl Renderer { fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); - // The display textures, the aux texture, the sampler. + // The display textures, the aux texture, the sampler let textures = DisplayKind::ALL.len() as u32 + 1; - // Displacement reads the height (and the sampler) in the vertex shader. - let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32; + // Displacement reads the height (and the sampler) in the vertex shader + let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32; let set_entries: Vec<_> = (0..textures) .map(tex_entry) .chain(std::iter::once(sampler_entry(textures))) - .map(|mut e| { - if e.binding == height || e.binding == textures { - e.visibility |= wgpu::ShaderStages::VERTEX; + .map(|mut entry| { + if entry.binding == height || entry.binding == textures { + entry.visibility |= wgpu::ShaderStages::VERTEX; } - e + entry }) .collect(); - let set_bgl = bgl("tc_set", &set_entries); - let refr_bgl = bgl("tc_refr", &[tex_entry(0)]); - let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); - let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]); - let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); - let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]); - let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { + let set_bind_group_layout = bind_group_layout("tc_set", &set_entries); + let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]); + let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); + let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]); + let effect_bind_group_layout = + bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); + let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]); + + let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 }) }; - let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]); - let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]); - let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]); - let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]); - let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]); - let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]); - let vb = [Some(wgpu::VertexBufferLayout { + let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]); + let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]); + let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]); + let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]); + let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]); + let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]); + + let vertex_layout = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2], })]; - // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode - // (e.g. RGBM) if WebGL2 without float color buffers turns out to matter. + + // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; - let hdr = |fs, blend| Some((fs, hdr_format, blend)); + let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); let mesh_pipeline = pipeline( device, @@ -866,8 +913,8 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_mesh", None), + &vertex_layout, + hdr_target("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); @@ -877,29 +924,103 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_opaque", None), + &vertex_layout, + hdr_target("fs_opaque", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); - let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always()); + let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always()); let blend = Some(wgpu::BlendState::ALPHA_BLENDING); - let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); + let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); - let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth); - let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); + let wire3d_pipeline = + pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = pipeline( + device, + "tc_highlight", + &layout, + &module, + "vs_wire_highlight", + &vertex_layout, + hdr_target("fs_wire_highlight", blend), + MSAA, + wire3d_depth.clone(), + ); + + let [mesh_vertex_layout] = vertex_layout.clone(); + let high_layout = [ + mesh_vertex_layout, + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![4 => Float32], + }), + ]; + let bake_high_pipeline = pipeline( + device, + "tc_bake_high", + &background_layout, + &module, + "vs_bake_high", + &high_layout, + hdr_target("fs_bake_high", None), + MSAA, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let corner_layout = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<[f32; 3]>() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3], + })]; + let cage_pipeline = pipeline( + device, + "tc_cage", + &background_layout, + &module, + "vs_bake_cage", + &corner_layout, + hdr_target("fs_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let cage_wire_pipeline = pipeline( + device, + "tc_cage_wire", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_seam_pipeline = + pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); - let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); - let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))] - .map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None)); - let gbuf_pipeline = - pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); - let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None)); - let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None); + let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); + let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| { + pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None) + }); + let gbuffer_pipeline = pipeline( + device, + "tc_gbuf", + &mesh_layout, + &module, + "vs_mesh", + &vertex_layout, + hdr_target("fs_gbuf", None), + 1, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| { + pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None) + }); + let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None); let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL }); let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("tc_dof_gather"), - layout: Some(&fx_layout), + layout: Some(&effect_layout), vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState::default(), depth_stencil: None, @@ -913,20 +1034,23 @@ impl Renderer { multiview_mask: None, cache: None, }); + let shadow_depth = wgpu::DepthStencilState { - bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 }, + bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 }, ..depth_state(true, wgpu::CompareFunction::Less) }; - let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth)); - // accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average. + let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth)); + + // accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average let average = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Constant, dst_factor: wgpu::BlendFactor::OneMinusConstant, operation: wgpu::BlendOperation::Add, }; - let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]); + let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]); let accum_blend = Some(wgpu::BlendState { color: average, alpha: average }); - let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None); + let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("tc_tex"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -934,7 +1058,7 @@ impl Renderer { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::MipmapFilterMode::Linear, - anisotropy_clamp: 8, + anisotropy_clamp: MAX_ANISOTROPY, ..Default::default() }); let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -953,7 +1077,8 @@ impl Renderer { compare: Some(wgpu::CompareFunction::LessEqual), ..Default::default() }); - let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor { + + let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("tc_shadow"), size: std::mem::size_of::<[[f32; 4]; 5]>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, @@ -967,38 +1092,45 @@ impl Renderer { vp: Mat4::IDENTITY, bg: device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_shadow"), - layout: &shadow_bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }], + layout: &shadow_bind_group_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }], }), - buf: shadow_buf, + buf: shadow_buffer, }; + let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view; - let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor { + let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_refr_black"), - layout: &refr_bgl, + layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); - let mut r = Renderer { + let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + + let mut renderer = Renderer { target_format, hdr_format, - globals_bgl, - set_bgl, - blit_bgl, - mip_bgl, - fx_bgl, - refr_bgl, - refr_black, + globals_bgl: globals_bind_group_layout, + set_bgl: set_bind_group_layout, + blit_bgl: blit_bind_group_layout, + mip_bgl: mip_bind_group_layout, + fx_bgl: effect_bind_group_layout, + refr_bgl: refraction_bind_group_layout, + refr_black: refraction_black, mesh_pipeline, opaque_pipeline, uv_pipeline, wire_pipeline, wire3d_pipeline, + highlight_pipeline, + bake_high_pipeline, + cage_pipeline, + cage_wire_pipeline, + uv_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, bloom_pipelines, - gbuf_pipeline, + gbuf_pipeline: gbuffer_pipeline, sss_pipelines, dof_gather_pipeline, dof_pipeline, @@ -1018,13 +1150,16 @@ impl Renderer { sh: [[0.0; 4]; 9], content_rev: 0, mesh: None, + bake_high: None, + cages: Vec::new(), + uv_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), views: HashMap::new(), }; - r.set_environment(device, queue, "Studio Soft", None); - r + renderer.set_environment(device, queue, "Studio Soft", None); + renderer } pub fn environment_name(&self) -> &str { @@ -1104,6 +1239,94 @@ impl Renderer { self.content_rev += 1; } + /// Upload the high poly when `id` changes; remove it on `None` or when its buffers exceed the device limit + pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) -> Result<(), String> { + if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) { + return Ok(()); + } + + self.bake_high = None; + self.content_rev += 1; + let Some(mesh) = mesh else { return Ok(()) }; + + // Imported high polys can outgrow a viewport buffer even when the CPU baker accepts them + let limit = device.limits().max_buffer_size; + let buffers = [ + (mesh.positions.len(), std::mem::size_of::()), + (mesh.indices.len(), std::mem::size_of::()), + (mesh.positions.len(), std::mem::size_of::()), + ]; + if mesh.indices.len() > u32::MAX as usize || buffers.iter().any(|&(count, stride)| count.checked_mul(stride).is_none_or(|bytes| bytes as u64 > limit)) { + return Err(format!("High-poly visualization exceeds the GPU buffer limit ({limit} bytes). Use a smaller preview mesh or hide the high poly.")); + } + + self.bake_high = Some(HighPolyGpu { + id, + vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX), + vertex_count: mesh.positions.len(), + indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX), + index_count: mesh.indices.len() as u32, + missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX), + }); + Ok(()) + } + + /// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count + pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) { + let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return }; + + queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed)); + self.content_rev += 1; + } + + /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + if self.cages.len() <= texture_set { + self.cages.resize_with(texture_set + 1, || None); + } + let Some(slot) = self.cages.get_mut(texture_set) else { return }; + + match (cage, slot.as_mut()) { + (None, _) => *slot = None, + (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + } + (Some((corners, edges)), _) => { + *slot = Some(CageGpu { + topology, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), + corner_count: corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), + edge_index_count: (edges.len() * 2) as u32, + }); + } + } + self.content_rev += 1; + } + + /// Forget the cages of texture sets from `count` on (sets that were removed) + pub fn truncate_bake_cages(&mut self, count: usize) { + if self.cages.len() > count { + self.cages.truncate(count); + self.content_rev += 1; + } + } + + /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` + pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + let mut line_indices: Vec = Vec::new(); + let mut line_draws = Vec::new(); + for (material, edges) in seams.iter().enumerate() { + let start = line_indices.len() as u32; + line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to])); + line_draws.push((start, line_indices.len() as u32 - start, material)); + } + + let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + self.content_rev += 1; + } + /// Build the mesh's dense copy for displacement (once per mesh). fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { let Some(m) = self.mesh.as_mut() else { return }; @@ -1531,13 +1754,7 @@ impl Renderer { visible: &'a [bool], only: Option, ) -> impl Iterator, &'a SetGpu)> + 'a { - ranges.iter().filter_map(move |&(start, count, material)| { - let ts = self.material_sets.get(material).copied().flatten()?; - if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { - return None; - } - Some((start..start + count, self.sets.get(ts)?)) - }) + drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?))) } /// Keep the key-light shadow map current; returns its view-projection. `light` points to @@ -1707,6 +1924,8 @@ impl Renderer { fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp, refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], + highlight: highlight_globals(s, data), + highlight_shift: highlight_shift(frame.size), }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; let post = PostRaw { @@ -1805,7 +2024,7 @@ impl Renderer { /// The scene without transmissive surfaces into `b` (MSAA resolved into mip 0), then its mips. fn behind_pass(&self, encoder: &mut wgpu::CommandEncoder, v: &ViewTargets, b: &Behind, globals_bg: &wgpu::BindGroup, frame: &Frame) { - self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, &self.refr_black); + self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, None, &self.refr_black); let Some(pipe) = self.mip_pipelines.get(&self.hdr_format) else { return }; for (dst, bg) in &b.mips { fullscreen(encoder, "tc_behind_mip", dst, CLEAR, pipe, bg); @@ -1869,32 +2088,34 @@ impl Renderer { }; // Transmissive surfaces refract what the behind pass rendered this frame. let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg); - self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, refr); + let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set)); + self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe` and the wireframe with `wire`. + /// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, encoder: &mut wgpu::CommandEncoder, - v: &ViewTargets, + targets: &ViewTargets, resolve: &wgpu::TextureView, - globals_bg: &wgpu::BindGroup, + globals_bind_group: &wgpu::BindGroup, frame: &Frame, - pipe: &wgpu::RenderPipeline, + mesh_pipeline: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, - refr: &wgpu::BindGroup, + highlight: Option<(&wgpu::RenderPipeline, usize)>, + refraction_source: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("tc_view"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &v.msaa, + view: &targets.msaa, resolve_target: Some(resolve), depth_slice: None, ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &v.depth, + view: &targets.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), stencil_ops: None, }), @@ -1902,27 +2123,87 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_bind_group(0, globals_bg, &[]); + pass.set_bind_group(0, globals_bind_group, &[]); pass.set_pipeline(&self.bg_pipeline); pass.draw(0..3, 0..1); - let Some(m) = &self.mesh else { return }; - let uv_ts = match frame.kind { + let Some(mesh) = &self.mesh else { return }; + + let uv_set = match frame.kind { ViewKind::Scene => None, ViewKind::Uv { ts, .. } => Some(ts), }; - pass.set_bind_group(2, refr, &[]); - let geo = self.geometry(m, frame); - // The wireframe draws the mesh's own edges (displaced in the vertex shader too). - for (pipe, vb, ib, ranges) in [(Some(pipe), &geo.vb, &geo.ib, &geo.draws), (wire, &m.geo.vb, &m.lines, &m.line_draws)] { - let Some(pipe) = pipe else { continue }; - pass.set_pipeline(pipe); - pass.set_vertex_buffer(0, vb.slice(..)); - pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, uv_ts) { + pass.set_bind_group(2, refraction_source, &[]); + let geometry = self.geometry(mesh, frame); + let bake = frame.shade.bake.filter(|_| uv_set.is_none()); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); + let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); + let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip(); + + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) + let passes = [ + (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + ]; + for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + let Some(pipeline) = pipeline else { continue }; + + pass.set_pipeline(pipeline); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(ranges, &frame.visible, only_set) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..instances); + } + } + + if let Some(bake) = bake { + self.draw_bake(&mut pass, mesh, frame, bake); + } + } + + /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { + if bake.high_poly + && let Some(high) = &self.bake_high + { + pass.set_pipeline(&self.bake_high_pipeline); + pass.set_vertex_buffer(0, high.vertices.slice(..)); + pass.set_vertex_buffer(1, high.missed.slice(..)); + pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..high.index_count, 0, 0..1); + } + + if bake.uv_seams + && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + { + pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } } + + if !bake.cage { + return; + } + + let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); + let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); + // The translucent faces first, then the wireframe over them + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). @@ -1963,6 +2244,39 @@ impl Renderer { } } +/// Index ranges of `ranges` (first, count, material) whose texture set (from `material_sets`) is visible and is `only`, when given, with that set's index +fn drawable_ranges<'a>( + ranges: &'a [(u32, u32, usize)], + material_sets: &'a [Option], + visible: &'a [bool], + only: Option, +) -> impl Iterator, usize)> + 'a { + ranges.iter().filter_map(move |&(start, count, material)| { + let ts = material_sets.get(material).copied().flatten()?; + if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { + return None; + } + + Some((start..start + count, ts)) + }) +} + +/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is +fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { + let Some(highlight) = shade.highlight else { return [0.0; 4] }; + + let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) }; + [r, g, b, HIGHLIGHT_OPACITY] +} + +/// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target +fn highlight_shift(size: [u32; 2]) -> [f32; 4] { + let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5; + let clip_per_pixel = size.map(|pixels| 2.0 / pixels.max(1) as f32); + + [half_extra_width * clip_per_pixel[0], half_extra_width * clip_per_pixel[1], 0.0, 0.0] +} + #[cfg(test)] mod tests { use super::*; @@ -2026,6 +2340,25 @@ mod tests { assert!(!h.renderer.awaiting_gpu()); } + #[test] + fn the_highlight_draws_only_the_highlighted_sets_edges() { + let line_draws = [(0, 4, 0), (4, 6, 1), (10, 2, 2)]; + let material_sets = [Some(0), Some(1), Some(2)]; + let highlighted = |visible: &[bool]| drawable_ranges(&line_draws, &material_sets, visible, Some(1)).collect::>(); + + assert_eq!(highlighted(&[true; 3]), vec![(4..10, 1)]); + assert_eq!(highlighted(&[true, false, true]), vec![], "a hidden set shows no highlight"); + } + + #[test] + fn a_data_view_takes_the_highlight_color_as_it_is() { + let color = [0.8, 0.25, 0.08]; + let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() }; + + assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); + assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping"); + } + #[test] fn a_verdict_that_never_comes_counts_as_a_failure() { let Some((mut h, tx)) = awaiting() else { return }; diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs new file mode 100644 index 00000000..878968c1 --- /dev/null +++ b/crates/render/src/set_highlight.rs @@ -0,0 +1,61 @@ +//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag) + +/// Brightest on-screen value the tone curve can reach without an infinite scene value +const MAX_ACES_SCREEN_VALUE: f32 = 0.99; + +/// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl) +const ACES_INPUT_SCALE: f32 = 0.6; + +/// Draw texture set `set`'s mesh edges over the 3D view in `color` +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SetHighlight { + pub set: usize, + /// The lines' color on screen, linear RGB + pub color: [f32; 3], +} + +impl SetHighlight { + /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] + pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { + let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); + + self.color.map(|screen| { + let screen = screen.max(0.0); + let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; + + exposed / exposure + }) + } +} + +/// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input +fn inverse_aces(screen: f32) -> f32 { + let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen); + let scaled = (-b - (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a); + + scaled / ACES_INPUT_SCALE +} + +#[cfg(test)] +mod tests { + use super::*; + + /// post.wgsl's `aces` with exposure `exposure_ev` + fn tone_mapped(scene: f32, exposure_ev: f32) -> f32 { + let v = scene * 2f32.powf(exposure_ev) * ACES_INPUT_SCALE; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) + } + + #[test] + fn the_scene_color_shows_the_highlight_color_on_screen() { + let highlight = SetHighlight { set: 0, color: [0.9, 0.3, 0.05] }; + for exposure_ev in [-2.0, 0.0, 1.5] { + let scene = highlight.scene_color(exposure_ev, true); + for (scene, screen) in scene.iter().zip(highlight.color) { + assert!((tone_mapped(*scene, exposure_ev) - screen).abs() < 1e-4, "{exposure_ev} EV: {scene} → {screen}"); + } + } + + assert_eq!(highlight.scene_color(1.0, false), [0.45, 0.15, 0.025], "linear: exposure only"); + } +} diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl new file mode 100644 index 00000000..1985f980 --- /dev/null +++ b/crates/render/src/shaders/bake_view.wgsl @@ -0,0 +1,88 @@ +// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams + +struct BakeViewOut { + @builtin(position) clip: vec4, + @location(0) world_position: vec3, + @location(1) normal: vec3, + // 1 where the bake's rays miss the high poly, 0 where they reach it + @location(2) missed: f32, +}; + +const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); +const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); +const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); +const CAGE_OPACITY: f32 = 0.16; +const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); +const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); + +// Brightness of surfaces seen edge-on; facing the camera adds the rest +const HEADLIGHT_AMBIENT: f32 = 0.3; + +// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order +const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001; +const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002; + +// Lit from the camera: surfaces facing it are brightest +fn headlight(color: vec3, normal: vec3, world_position: vec3) -> vec3 { + let facing = abs(dot(normal, normalize(g.eye.xyz - world_position))); + return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing); +} + +fn pulled_toward_eye(world_position: vec3, fraction: f32) -> vec4 { + return g.view_proj * vec4(world_position + (g.eye.xyz - world_position) * fraction, 1.0); +} + +// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it +@vertex +fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3, @location(4) missed: f32) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = normal; + out.missed = missed; + return out; +} + +@fragment +fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { + let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); +} + +@vertex +fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = g.view_proj * vec4(position, 1.0); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +// The cage's own faces: their normal comes from the screen-space change of the position +@fragment +fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); + return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); +} + +// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces +@vertex +fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +@fragment +fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + return CAGE_WIRE_COLOR; +} + +@fragment +fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { + return UV_SEAM_COLOR; +} diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index cd2e8d80..863d6eae 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -24,6 +24,8 @@ struct Globals { fwd: vec4, // xyz camera view direction (unit), w - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - + highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity + highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - }; @group(0) @binding(0) var g: Globals; @@ -659,8 +661,7 @@ fn fs_wire(i: VOut) -> @location(0) vec4 { // 3D wireframe over the shaded mesh: depth-tested, pulled slightly toward the camera so the // lines win against their own triangles. -@vertex -fn vs_wire3d(v: VIn) -> VOut { +fn wire3d(v: VIn) -> VOut { var o: VOut; o.wpos = v.pos; o.nrm = v.nrm; @@ -671,7 +672,26 @@ fn vs_wire3d(v: VIn) -> VOut { return o; } +@vertex +fn vs_wire3d(v: VIn) -> VOut { + return wire3d(v); +} + @fragment fn fs_wire3d(i: VOut) -> @location(0) vec4 { return vec4(0.35, 0.35, 0.35, 0.45); } + +// The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel +@vertex +fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut { + var o = wire3d(v); + let corner = vec2(f32(copy & 1u), f32((copy >> 1u) & 1u)) * 2.0 - 1.0; + o.clip = vec4(o.clip.xy + corner * g.highlight_shift.xy * o.clip.w, o.clip.zw); + return o; +} + +@fragment +fn fs_wire_highlight(i: VOut) -> @location(0) vec4 { + return g.highlight; +} diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/uv_seam_gpu.rs new file mode 100644 index 00000000..0ac80dc9 --- /dev/null +++ b/crates/render/src/uv_seam_gpu.rs @@ -0,0 +1,8 @@ +/// The low poly's UV seams as a line list over its vertex buffer +pub(crate) struct UvSeamGpu { + /// The low-poly mesh the lines belong to + pub(crate) mesh_id: u64, + pub(crate) lines: wgpu::Buffer, + /// (first index, count, material) per material + pub(crate) line_draws: Vec<(u32, u32, usize)>, +} diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..84a6e0e2 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,8 +1,9 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -42,14 +43,18 @@ impl Img { } } +/// The id `setup` uploads the material ball under +const MESH_ID: u64 = 1; + /// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). fn setup() -> Option<(Headless, Frame)> { let Ok(mut h) = Headless::new() else { eprintln!("skipping: no GPU adapter"); return None; }; + eprintln!("headless adapter: {:?}", h.device.adapter_info()); let mesh = primitives::material_ball(); - h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1); + h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID); h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2); let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); @@ -220,6 +225,122 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +#[test] +fn bake_visualization_draws_the_high_poly_and_the_cage() { + // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color + const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3; + const CAGE_SCALE: f32 = 2.5; + const HIGH_POLY_ID: u64 = 7; + const CAGE_TOPOLOGY: u64 = 1; + const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]]; + const COLOR_LEAD: i32 = 30; + + let Some((mut h, frame)) = setup() else { return }; + let ball = primitives::material_ball(); + let (low_min, low_max) = ball.bounds(); + let ball_center = (low_min + low_max) * 0.5; + let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16); + for position in &mut high.positions { + *position += ball_center; + } + h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap(); + let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + let center = (frame.size[0] / 2, frame.size[1] / 2); + + let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); + let low_only = only(&mut h, bake, "bake_low_only"); + let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); + let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); + let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); + assert_same(&hidden, &background, "without the low poly only the background is left"); + let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]); + let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1)); + assert!( + caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue, + "the cage tints the ball tan: {:?} → {:?}", + [low_red, low_green, low_blue], + [caged_red, caged_green, caged_blue] + ); + + // Vertices the bake's rays miss turn red + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); + let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); + assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + + // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out + let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); + assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); + assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); + assert_ne!(first_set.px, second_set.px); + + // UV seams draw over the low poly + h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); + let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + assert_ne!(seams.px, low_only.px, "the seams show"); + + // A new distance with the same topology only moves the corners + let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + assert_ne!(caged.px, bigger.px, "the cage grew"); +} + +#[test] +fn oversized_bake_high_poly_leaves_the_view_renderable() { + let Some((mut headless, frame)) = setup() else { return }; + + let high = primitives::sphere(0.5, 16, 8); + headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap(); + let limit = headless.device.limits().max_buffer_size; + // The viewport vertex contains position, normal, tangent and UV: twelve f32 values + let vertex_count = limit as usize / (12 * std::mem::size_of::()) + 1; + let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() }; + let error = headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&oversized), 2).unwrap_err(); + assert!(error.contains("GPU buffer limit"), "{error}"); + + headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]); + let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared"); + let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background"); + assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible"); + headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 3).unwrap(); + let recovered = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_recovered"); + assert_ne!(recovered.px, background.px, "a later valid high poly still draws"); +} + +#[test] +fn bake_low_poly_visibility_also_filters_its_wireframe() { + let Some((mut headless, frame)) = setup() else { return }; + + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let hidden = shaded(&frame, |shade| { + shade.bake = Some(bake); + shade.wireframe_3d = true; + shade.highlight = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] }); + }); + let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_wire_background"); + let hidden_wire = render(&mut headless, &hidden, "bake_wire_hidden"); + assert_same(&hidden_wire, &background, "hiding the project mesh also hides its wireframe and highlight"); + + for texture_set in [0, 1] { + let selected = shaded(&hidden, |shade| { + shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake }); + shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] }); + }); + let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() }; + let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}")); + let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}")); + assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set"); + } +} + #[test] fn ortho_background_matches_perspective() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 7887bf26..fdc45c70 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -15,6 +15,8 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] egui = { workspace = true } craft-ui = { workspace = true } craft-window = { workspace = true } +craft-keymap = { workspace = true } +craft-quit = { workspace = true } egui-phosphor = { version = "0.14", features = ["regular", "fill"] } serde = { workspace = true } serde_json = { workspace = true } @@ -22,7 +24,6 @@ rayon = { workspace = true } log = { workspace = true } base64 = "0.22" image = { workspace = true } -rfd = { workspace = true } zip = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). @@ -30,6 +31,10 @@ zip = { workspace = true } sys-locale = "0.3" # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } +# Help > Check for Updates and the check at start (updates_ui.rs). +craft-update = { workspace = true } +# Native file dialogs (file_dialogs.rs); the browser build has none. +craft-dialogs = { workspace = true } # build.rs: the interface faces lose their Private Use Area, where the icon font draws (the # versions craft-libs' craft-fonts-build subsets with). @@ -39,6 +44,7 @@ skrifa = { version = "0.48", default-features = false, features = ["std"] } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] +rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs deleted file mode 100644 index c0397a49..00000000 --- a/crates/ui-egui/src/bake_mode.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Bake Mode presentation; persisted settings live in core and edits use engine commands - -mod bake_paint_brush; -mod common_settings; -pub use bake_paint_brush::BakePaintBrush; -mod controls; -mod map_settings; - -use egui::{Ui, vec2}; -use serde_json::json; -use texturecraft_engine::core::{BakeSettings, BakedMap}; - -use crate::TextureCraftApp; -use crate::i18n::{tr, trf}; -use crate::state::Mode; -use crate::widgets::primary_button; - -pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { - for set_index in 0..app.session.set_count() { - let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; - - let name = texture_set.name.clone(); - let (width, height) = texture_set.bake.common.output_size(); - let mut is_enabled = texture_set.bake.common.is_enabled; - ui.push_id(set_index, |ui| { - ui.horizontal(|ui| { - if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { - app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); - } - if ui.selectable_label(set_index == app.session.ts(), format!("{name} ({width} × {height})")).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - } - }); - }); - } - }); -} - -pub fn bake_body(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_maps", |_, ui, settings| { - for map in BakedMap::ALL { - ui.push_id(map, |ui| map_settings::show(ui, map, &mut settings.maps)); - ui.add_space(6.0); - } - }); -} - -pub fn settings_body(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_common_settings", common_settings::show); -} - -fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) { - let set_index = app.session.ts(); - let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; - - let mut settings = before.clone(); - egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)); - if settings != before { - app.run("bake.settings", json!({ "ts": set_index, "model": settings })); - } -} - -pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { - egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( - ctx, - |ui| { - ui.horizontal(|ui| { - if let Some(progress) = app.bake_progress() { - ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); - if ui.button(tr("Cancel")).clicked() { - app.cancel_bake(); - } - } else { - let texture_sets: Vec = app - .session - .doc - .project - .texture_sets - .iter() - .enumerate() - .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) - .map(|(index, _)| index) - .collect(); - let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); - if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { - app.start_bake(texture_sets); - } - } - - if ui.button(tr("Return to Painting Mode")).clicked() { - app.ui.mode = Mode::Painting; - } - }); - }, - ); -} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs new file mode 100644 index 00000000..42da4393 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -0,0 +1,61 @@ +use egui::collapsing_header::CollapsingState; +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::{icon_button_without_tooltip, section_chevron}; + +/// The panel's width and its gap from the 3D view's top-left corner +const PANEL_WIDTH: f32 = 280.0; +const PANEL_MARGIN: f32 = 12.0; + +/// Size of the panel's eye buttons +const EYE_BUTTON_SIZE: f32 = 22.0; + +/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` +pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let toggles = &mut app.ui.bake_visualization; + egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( + ui.ctx(), + |ui| { + ui.set_width(PANEL_WIDTH); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); + let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| { + ui.add_enabled_ui(toggles.on, |ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); + eye_row(ui, &mut toggles.cage, tr("Cage"), None); + eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); + eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); + }); + }); + }, + ); +} + +/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response +fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = match open { + Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), + None => egui::RichText::new(label), + }; + let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { + *shown = !*shown; + } + }); + response + }) + .inner +} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs new file mode 100644 index 00000000..0603c523 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_render::BakeVisualization; + +/// The Baking Visualization panel's switches in bake mode's 3D view +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeVisualizationToggles { + /// The panel's eye: the whole visualization on or off + pub on: bool, + pub selected_set_only: bool, + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, +} + +impl Default for BakeVisualizationToggles { + fn default() -> Self { + Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + } +} + +impl BakeVisualizationToggles { + /// What the renderer draws with these switches while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> Option { + self.on.then_some(BakeVisualization { + high_poly: self.high_poly, + cage: self.cage, + uv_seams: self.uv_seams, + low_poly: self.low_poly, + only_set: self.selected_set_only.then_some(selected_set), + }) + } +} diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs new file mode 100644 index 00000000..14dc7fd5 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -0,0 +1,35 @@ +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use serde_json::json; +use texturecraft_engine::core::BakedMap; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr}; + +/// The texture set and selected map above Mesh Map Settings, each behind a dropdown to switch it +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap) { + let active_set = app.session.ts(); + let set_names: Vec = app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.name.clone()).collect(); + + ui.horizontal(|ui| { + ui.menu_button(icon::CARET_RIGHT, |ui| { + for (set_index, name) in set_names.iter().enumerate() { + if ui.selectable_label(set_index == active_set, name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + ui.close(); + } + } + }); + ui.label(set_names.get(active_set).map_or("", String::as_str)); + + ui.menu_button(icon::CARET_RIGHT, |ui| { + for map in BakedMap::ALL { + if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { + app.ui.selected_baked_map = Some(map); + ui.close(); + } + } + }); + ui.label(RichText::new(tr(baked_map_label(selected))).strong()); + }); +} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index d96fdc85..02d712a0 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -4,15 +4,18 @@ use crate::i18n::tr; use crate::widgets::icon_button; use egui::Ui; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Map, Value, json}; use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { +/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { + let mut reset = Map::new(); ui.push_id("common", |ui| { + // Restore Defaults keeps whether the texture set is included in the bake let is_enabled = settings.common.is_enabled; - if section(ui, tr("Common Parameters"), None, |ui| { + if section(ui, tr("Common Parameters"), |ui| { output_size(ui, &mut settings.common); choice( ui, @@ -29,11 +32,17 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); }) { settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; + let mut defaults = json!(settings.common); + if let Some(fields) = defaults.as_object_mut() { + fields.remove("is_enabled"); + } + reset.insert("common".into(), defaults); } }); + ui.add_space(8.0); ui.push_id("high_poly", |ui| { - if section(ui, tr("High-Poly Parameters"), None, |ui| { + if section(ui, tr("High-Poly Parameters"), |ui| { ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); high_poly_files(app, ui); if !app.session.bake_meshes.high.is_empty() { @@ -50,12 +59,14 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }) { settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); } }); + if !app.session.bake_meshes.high.is_empty() { ui.add_space(8.0); ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), None, |ui| { + if section(ui, tr("Cage"), |ui| { choice( ui, tr("Cage Type"), @@ -74,12 +85,14 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }) { settings.cage = Default::default(); + reset.insert("cage".into(), json!(settings.cage)); } }); + if settings.cage.kind == CageType::DistanceBased { ui.add_space(8.0); ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), None, |ui| { + if section(ui, tr("Skew Correction"), |ui| { choice( ui, tr("Skew Correction Method"), @@ -95,16 +108,20 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); }) { settings.skew = Default::default(); + reset.insert("skew".into(), json!(settings.skew)); } }); } } + + (!reset.is_empty()).then_some(Value::Object(reset)) } fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { ui.label(tr("Output Size")); ui.horizontal(|ui| { - let dropdown_width = ((ui.available_width() - 24.0 - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); + let button_size = ui.spacing().interact_size.y; + let dropdown_width = ((ui.available_width() - button_size - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); let resolution = |ui: &mut Ui, id: &str, value: &mut BakeResolution| { egui::ComboBox::from_id_salt(id).width(dropdown_width).selected_text(value.pixels().to_string()).show_ui(ui, |ui| { for resolution in BakeResolution::ALL { @@ -112,6 +129,7 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { } }); }; + resolution(ui, "output_width", &mut settings.resolution); let locked = settings.resolution_height.is_none(); let mut height = settings.resolution_height.unwrap_or(settings.resolution); @@ -119,7 +137,8 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { if !locked { settings.resolution_height = Some(height); } - if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, 24.0).clicked() { + + if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, button_size).clicked() { settings.resolution_height = if locked { Some(settings.resolution) } else { None }; } }); @@ -131,12 +150,15 @@ fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { let mut remove = None; for (index, name) in meshes.iter().enumerate() { ui.horizontal(|ui| { - ui.add_sized([ui.available_width() - 24.0, 24.0], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, 20.0).clicked() { + let button_size = ui.spacing().interact_size.y; + let label_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); + if icon_button(ui, icon::TRASH, tr("Remove"), false, button_size).clicked() { remove = Some(index); } }); } + if meshes.is_empty() { hint(ui, tr("No High-Poly Meshes")); } @@ -152,11 +174,13 @@ fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(tr("Cage Scene")); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { - ui.add_sized([ui.available_width() - 52.0, 24.0], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, 20.0).clicked() { + let button_size = ui.spacing().interact_size.y; + let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); } - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, 20.0).clicked() { + if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { app.run("bake.cage.clear", json!({})); } }); diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs index 4c2e6b88..f260bf7c 100644 --- a/crates/ui-egui/src/bake_mode/controls.rs +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -3,63 +3,35 @@ use crate::theme::{Tokens, caption}; use egui::collapsing_header::CollapsingState; use egui::{RichText, Ui}; -pub(super) fn section_header(ui: &mut Ui, title: &str, mut is_enabled: Option<&mut bool>, collapsing_state: Option<&mut CollapsingState>) -> bool { +/// A section's title bar with its chevron; clicking it opens or closes the section +fn section_header(ui: &mut Ui, title: &str, collapsing_state: &mut CollapsingState) { let tokens = Tokens::get(ui.ctx()); - let text_color = if is_enabled.as_deref().copied().unwrap_or(true) { tokens.text_strong } else { tokens.text_dim }; - let mut checkbox_rect = None; - let mut arrow_rect = None; - let header = egui::Frame::NONE.fill(tokens.row).corner_radius(tokens.cr()).inner_margin(egui::Margin::symmetric(8, 4)).show(ui, |ui| { ui.set_min_width(ui.available_width()); ui.horizontal(|ui| { ui.set_min_height(ui.spacing().interact_size.y); - let checkbox = is_enabled.as_deref_mut().map(|is_enabled| ui.checkbox(is_enabled, "")); - let title_response = ui.add(egui::Label::new(caption(title).color(text_color)).selectable(false)); - if let Some(checkbox) = checkbox { - checkbox_rect = Some(checkbox.rect); - checkbox.labelled_by(title_response.id); - } - - if collapsing_state.is_some() { - arrow_rect = Some( - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 - }) - .inner, - ); - } - }); + ui.add(egui::Label::new(caption(title).color(tokens.text_strong)).selectable(false)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 + }) + .inner + }) + .inner }); - if let (Some(collapsing_state), Some(arrow_rect)) = (collapsing_state, arrow_rect) { - let mut toggle_rect = header.response.rect; - if let Some(checkbox_rect) = checkbox_rect { - let checkbox_margin = ui.spacing().item_spacing.x * 0.5; - if ui.style().right_to_left { - toggle_rect.max.x = checkbox_rect.left() - checkbox_margin; - } else { - toggle_rect.min.x = checkbox_rect.right() + checkbox_margin; - } - } - - let response = ui.interact(toggle_rect, ui.make_persistent_id("section_header"), egui::Sense::click()); - if response.clicked() { - collapsing_state.toggle(ui); - } - - let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); - ui.put(arrow_rect, egui::Label::new(chevron).selectable(false)); + let response = ui.interact(header.response.rect, ui.make_persistent_id("section_header"), egui::Sense::click()); + if response.clicked() { + collapsing_state.toggle(ui); } - is_enabled.as_deref().copied().unwrap_or(true) + let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); + ui.put(header.inner, egui::Label::new(chevron).selectable(false)); } -pub(super) fn section(ui: &mut Ui, title: &str, is_enabled: Option<&mut bool>, contents: impl FnOnce(&mut Ui)) -> bool { +/// A collapsible section with `contents` and Restore Defaults; returns whether that was clicked +pub(super) fn section(ui: &mut Ui, title: &str, contents: impl FnOnce(&mut Ui)) -> bool { let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("section"), true); - if !section_header(ui, title, is_enabled, Some(&mut collapsing_state)) { - collapsing_state.store(ui.ctx()); - return false; - } + section_header(ui, title, &mut collapsing_state); collapsing_state .show_body_unindented(ui, |ui| { diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index a8cb2d48..5168d341 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,33 +1,42 @@ -use super::controls::{choice, integer, number, section, section_header}; -use crate::i18n::{baked_map_label, tr}; +use super::controls::{choice, hint, integer, number}; +use crate::i18n::tr; use egui::Ui; +use serde::Serialize; +use serde_json::{Value, json}; use texturecraft_engine::core::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization, - HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, - PositionSettings, RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, + HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, + RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, }; -pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) { +/// Draw `map`'s parameters with Restore Defaults; maps without parameters say so +pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) -> Option { match map { BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { - let mut is_enabled = settings.is_enabled(map); - section_header(ui, tr(baked_map_label(map)), Some(&mut is_enabled), None); - settings.set_enabled(map, is_enabled); + hint(ui, tr("No Parameters")); + None } - BakedMap::Id => baker(ui, map, &mut settings.id, id), - BakedMap::AmbientOcclusion => baker(ui, map, &mut settings.ao, ambient_occlusion), - BakedMap::Curvature => baker(ui, map, &mut settings.curvature, curvature), - BakedMap::Position => baker(ui, map, &mut settings.position, position), - BakedMap::Thickness => baker(ui, map, &mut settings.thickness, thickness), - BakedMap::Height => baker(ui, map, &mut settings.height, height), - BakedMap::BentNormal => baker(ui, map, &mut settings.bent_normal, bent_normal), + BakedMap::Id => parameters(ui, "id", &mut settings.id.parameters, id), + BakedMap::AmbientOcclusion => parameters(ui, "ao", &mut settings.ao.parameters, ambient_occlusion), + BakedMap::Curvature => parameters(ui, "curvature", &mut settings.curvature.parameters, curvature), + BakedMap::Position => parameters(ui, "position", &mut settings.position.parameters, position), + BakedMap::Thickness => parameters(ui, "thickness", &mut settings.thickness.parameters, thickness), + BakedMap::Height => parameters(ui, "height", &mut settings.height.parameters, height), + BakedMap::BentNormal => parameters(ui, "bent_normal", &mut settings.bent_normal.parameters, bent_normal), } } -fn baker(ui: &mut Ui, map: BakedMap, settings: &mut MapSettings, controls: impl FnOnce(&mut Ui, &mut T)) { - if section(ui, tr(baked_map_label(map)), Some(&mut settings.is_enabled), |ui| controls(ui, &mut settings.parameters)) { - settings.parameters = T::default(); +/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters +fn parameters(ui: &mut Ui, map_key: &str, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) -> Option { + controls(ui, parameters); + ui.add_space(6.0); + + let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; + if restore.clicked() { + *parameters = T::default(); + return Some(json!({"maps": {map_key: {"parameters": parameters}}})); } + None } fn id(ui: &mut Ui, settings: &mut IdSettings) { diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs new file mode 100644 index 00000000..b9101e93 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -0,0 +1,75 @@ +use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as icon; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr}; +use crate::theme::Tokens; + +/// Height of one baker row, in points +const ROW_HEIGHT: f32 = 24.0; +/// Inset of a row's checkbox and name from its left edge, in points +const ROW_INSET: f32 = 6.0; + +/// The Common Settings button, Check All, and one row per map (checkbox enables, click selects) +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + if ui.button(format!("{} {}", icon::GEAR, tr("Common Settings"))).clicked() { + app.ui.dock.focus(Panel::CommonSettings); + } + + ui.add_space(4.0); + check_all(ui, settings); + ui.separator(); + + let selected = super::selected_map(app.ui.selected_baked_map, settings); + for map in BakedMap::ALL { + if ui.push_id(map, |ui| row(ui, map, settings, map == selected)).inner { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + } +} + +/// Enable every map, or disable them all when every map is already enabled +fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { + let enabled_count = BakedMap::ALL.into_iter().filter(|map| settings.maps.is_enabled(*map)).count(); + let mut all_enabled = enabled_count == BakedMap::ALL.len(); + let some_enabled = enabled_count > 0 && !all_enabled; + + if ui.add(egui::Checkbox::new(&mut all_enabled, tr("Check All")).indeterminate(some_enabled)).changed() { + for map in BakedMap::ALL { + settings.maps.set_enabled(map, all_enabled); + } + } +} + +/// One baker row; returns whether the row (not its checkbox) was clicked +fn row(ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); + + let painter = ui.painter(); + if is_selected { + painter.rect_filled(rect, tokens.cr(), tokens.row_selected); + painter.rect_stroke(rect, tokens.cr(), Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, tokens.cr(), tokens.row_hover); + } + painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + + // Added after the row's own response, so the checkbox takes the clicks over it + let content_rect = rect.shrink2(vec2(ROW_INSET, 0.0)); + let mut content = ui.new_child(UiBuilder::new().max_rect(content_rect).layout(Layout::left_to_right(Align::Center))); + let mut is_enabled = settings.maps.is_enabled(map); + let checkbox = content.checkbox(&mut is_enabled, ""); + let text = if is_selected { RichText::new(name).strong() } else { RichText::new(name) }; + let label = content.add(egui::Label::new(text).selectable(false).truncate()); + if checkbox.labelled_by(label.id).changed() { + settings.maps.set_enabled(map, is_enabled); + } + + response.clicked() +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs new file mode 100644 index 00000000..70dd4225 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -0,0 +1,220 @@ +//! Bake Mode presentation; persisted settings live in core and edits use engine commands + +mod bake_paint_brush; +mod bake_visualization_panel; +mod bake_visualization_toggles; +mod breadcrumb; +mod common_settings; +pub use bake_paint_brush::BakePaintBrush; +pub(crate) use bake_visualization_panel::bake_visualization_panel; +pub use bake_visualization_toggles::BakeVisualizationToggles; +mod controls; +mod map_settings; +mod mesh_map_bakers; + +use egui::{Ui, vec2}; +use egui_phosphor::regular as icon; +use serde_json::{Value, json}; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::widgets::{icon_button, primary_button}; + +pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { + egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { + for set_index in 0..app.session.set_count() { + let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; + + let name = texture_set.name.clone(); + let resolution = texture_set.resolution; + let mut is_enabled = texture_set.bake.common.is_enabled; + let visible = texture_set.visible; + let tiles: Vec<_> = texture_set + .uv_tiles + .iter() + .map(|tile| (*tile, texture_set.tile_resolutions.get(tile).copied(), !texture_set.bake_excluded_tiles.contains(tile))) + .collect(); + + ui.push_id(set_index, |ui| { + ui.horizontal(|ui| { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() { + app.run("textureSet.visible", json!({ "ts": set_index })); + } + if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None) + && selected != resolution + { + app.start_resize(set_index, selected); + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + }); + }); + }); + + if !tiles.is_empty() { + egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| { + for (tile, override_resolution, enabled) in &tiles { + let mut enabled = *enabled; + ui.push_id(tile, |ui| { + ui.horizontal(|ui| { + if ui.checkbox(&mut enabled, tile.to_string()).on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled})); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default(); + let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]); + if let Some(selected) = resolution_menu( + ui, + &label, + text, + override_resolution.unwrap_or(resolution), + override_resolution.map(|_| resolution), + ) { + app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": tile, "resolution": selected})); + } + }); + }) + }); + } + }); + } + }); + } + }); +} + +fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option) -> Option { + let effective_size = format!("{resolution} × {resolution}"); + let measured = if text.is_empty() { &effective_size } else { &text }; + let font = egui::TextStyle::Button.resolve(ui.style()); + let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x; + let width = text_width + ui.spacing().button_padding.x * 2.0; + let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false)); + let popup_id = response.id.with("resolution_menu"); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked(); + let shown = if text.is_empty() && (response.hovered() || open) { effective_size } else { text }; + ui.painter().text(response.rect.center(), egui::Align2::CENTER_CENTER, &shown, font, ui.style().interact(&response).text_color()); + + let mut selected = None; + egui::Popup::menu(&response).id(popup_id).show(|ui| { + if let Some(inherited) = inherited_resolution { + if ui.button(tr("Remove resolution override")).clicked() { + selected = Some(inherited); + ui.close(); + } + ui.separator(); + } + for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] { + if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() { + selected = Some(candidate); + } + } + }); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), label); + info.current_text_value = Some(shown.clone()); + info + }); + response.on_hover_text(label); + selected +} + +/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows +pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let texture_set = json!(app.session.ts()); + edit_settings(app, ui, "mesh_map_bakers", texture_set, |app, ui, settings| { + mesh_map_bakers::show(app, ui, settings); + None + }); +} + +/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters +pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; + + let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); + breadcrumb::show(app, ui, selected); + ui.separator(); + edit_settings(app, ui, "mesh_map_settings", json!("all"), |_, ui, settings| { + ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner + }); +} + +/// The Common Settings panel: output, high poly, cage and skew settings +pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "bake_common_settings", json!("all"), common_settings::show); +} + +/// The map whose settings show: the chosen one, else the first enabled map, else Normal +fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { + selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) +} + +/// Send changed fields and explicitly reset sections through the same undoable command +fn edit_settings( + app: &mut TextureCraftApp, + ui: &mut Ui, + scroll_id: &str, + texture_sets: Value, + contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option, +) { + let set_index = app.session.ts(); + let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; + + let mut settings = before.clone(); + let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; + if settings == before && reset.is_none() { + return; + } + + let mut patch = settings_patch(&before, &settings); + if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) { + fields.extend(reset); + } + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); +} + +pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( + ctx, + |ui| { + ui.horizontal(|ui| { + if let Some(progress) = app.bake_progress() { + ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); + if ui.button(tr("Cancel")).clicked() { + app.cancel_bake(); + } + } else { + let texture_sets: Vec = app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles()) + .map(|(index, _)| index) + .collect(); + let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); + if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { + app.start_bake(texture_sets); + } + } + + if ui.button(tr("Return to Painting Mode")).clicked() { + app.ui.mode = Mode::Painting; + } + }); + }, + ); +} diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs new file mode 100644 index 00000000..1a30780e --- /dev/null +++ b/crates/ui-egui/src/bake_scene.rs @@ -0,0 +1,11 @@ +//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session + +mod bake_scene_link; +mod cage_link; +mod cage_shell_key; +mod cage_upload; +mod reach_link; +mod shared_handle; + +pub use bake_scene_link::BakeSceneLink; +pub use cage_upload::CageUpload; diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs new file mode 100644 index 00000000..b9cecaa9 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -0,0 +1,239 @@ +use std::sync::Arc; + +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; +use texturecraft_render::BakeVisualization; + +use super::CageUpload; +use super::cage_link::CageLink; +use super::cage_shell_key::CageShellKey; +use super::reach_link::ReachLink; +use super::shared_handle::SharedHandle; +use crate::gpu::SceneSync; + +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +#[derive(Default)] +pub struct BakeSceneLink { + /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) + high: SharedHandle, + high_id: u64, + /// Whether the GPU has the high poly (a lost frame sends it again under the same id) + high_sent: bool, + cages: Vec>, + /// How many texture sets' cages the GPU was last told to keep + sent_cage_count: Option, + /// The low-poly mesh whose seams are uploaded + seams_mesh_id: Option, + next_topology: u64, + reach: ReachLink, +} + +impl BakeSceneLink { + /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay + pub fn resend(&mut self) { + self.high_sent = false; + self.sent_cage_count = None; + self.seams_mesh_id = None; + for link in self.cages.iter_mut().flatten() { + link.max_frontal = f32::NAN; + } + self.reach.resend(); + } + + /// Whether something is still being worked out off the UI thread + pub fn busy(&self) -> bool { + self.reach.busy() + } + + /// Add to `out` what the GPU needs to draw `visualization` this frame + pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + self.reach.poll(); + + let Some(visualization) = visualization else { return }; + + if visualization.high_poly { + let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let handle = SharedHandle::of(high.as_ref()); + if handle != self.high { + self.high = handle; + self.high_id += 1; + self.high_sent = false; + } + if !self.high_sent { + out.bake_high = Some((high, self.high_id)); + self.high_sent = true; + } + self.reach.sync(session, self.high_id, visualization.only_set, out); + } + + if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + self.seams_mesh_id = Some(session.mesh_id); + out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + } + + if visualization.cage { + self.sync_cages(session, out); + } + } + + /// Rebuild the cages whose inputs changed and move the corners of those whose distance changed + fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + if self.sent_cage_count != Some(set_count) { + out.bake_cage_count = Some(set_count); + self.sent_cage_count = Some(set_count); + } + self.cages.truncate(set_count); + self.cages.resize_with(set_count, || None); + + for (texture_set, link) in self.cages.iter_mut().enumerate() { + let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue }; + + let max_frontal = set.bake.cage.max_frontal; + match link { + Some(link) if link.key == key => { + if link.max_frontal == max_frontal { + continue; + } + link.max_frontal = max_frontal; + } + _ => { + self.next_topology += 1; + let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new); + *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal }); + } + } + + let Some(link) = link.as_ref() else { continue }; + + let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() }); + out.bake_cages.push((texture_set, upload, link.topology)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + + /// How long a test waits for the reach worker: frames, and the pause between them + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5); + + /// The sample project with a high poly a little outside its low poly + fn session() -> Session { + const HIGH_POLY_OFFSET: f32 = 0.02; + + let mut session = texturecraft_engine::sample_session(128, 128).unwrap(); + let low = session.mesh.clone(); + let mut obj = String::new(); + for (position, normal) in low.positions.iter().zip(&low.normals) { + let raised = *position + *normal * HIGH_POLY_OFFSET; + obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z); + } + for corners in low.indices.chunks(3) { + obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1); + } + session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap(); + session + } + + fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync { + let mut out = SceneSync::default(); + link.sync(session, Some(visualization), &mut out); + out + } + + /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red + fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { + for _ in 0..WAIT_FRAMES { + if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { + return missed.iter().sum::() / missed.len().max(1) as f32; + } + std::thread::sleep(WAIT_FRAME_PAUSE); + } + panic!("the reach never arrived"); + } + + fn set_distances(session: &mut Session, max_frontal: f32) { + texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap(); + } + + #[test] + fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + let first = sync(&mut link, &session, EVERYTHING); + assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + + let unchanged = sync(&mut link, &session, EVERYTHING); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + + set_distances(&mut session, 0.03); + let moved = sync(&mut link, &session, EVERYTHING); + let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + assert_eq!(moved_topology, topology, "a distance only moves the corners"); + assert_ne!(moved_cage.corners, cage.corners); + + texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); + let rebuilt = sync(&mut link, &session, EVERYTHING); + assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts + red_share(&mut link, &session, EVERYTHING); + + link.resend(); + let resent = sync(&mut link, &session, EVERYTHING); + assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); + assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); + assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); + assert!(!link.busy(), "a lost frame doesn't work out the reach again"); + } + + #[test] + fn a_reach_finishes_while_nothing_is_drawn() { + let session = session(); + let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + for hidden in [None, Some(no_high_poly)] { + let mut link = BakeSceneLink::default(); + sync(&mut link, &session, EVERYTHING); + assert!(link.busy(), "the first frame starts working out the reach"); + + let finished = (0..WAIT_FRAMES).any(|_| { + std::thread::sleep(WAIT_FRAME_PAUSE); + link.sync(&session, hidden, &mut SceneSync::default()); + !link.busy() + }); + assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}"); + } + } + + #[test] + fn the_red_follows_the_distances_and_the_selected_set() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + set_distances(&mut session, 0.0); + let at_zero = red_share(&mut link, &session, EVERYTHING); + assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); + + set_distances(&mut session, 0.05); + let covered = red_share(&mut link, &session, EVERYTHING); + assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); + + set_distances(&mut session, 0.0); + let by_name = |session: &mut Session, low_suffix: &str| { + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName; + set.bake.high_poly.low_suffix = low_suffix.into(); + } + }; + by_name(&mut session, "_no_such_suffix"); + let by_name_red = red_share(&mut link, &session, EVERYTHING); + assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); + + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; + assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_link.rs b/crates/ui-egui/src/bake_scene/cage_link.rs new file mode 100644 index 00000000..855d9619 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_link.rs @@ -0,0 +1,16 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; + +use super::cage_shell_key::CageShellKey; + +/// A texture set's cage as the GPU has it +pub(super) struct CageLink { + pub(super) key: CageShellKey, + /// `None`: the set bakes without a high poly or its cage can't be built + pub(super) shell: Option>, + /// The renderer's name for the shell's corner order and edges + pub(super) topology: u64, + /// The max frontal distance the GPU's corners are at + pub(super) max_frontal: f32, +} diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs new file mode 100644 index 00000000..44e17eca --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -0,0 +1,47 @@ +use std::collections::BTreeMap; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::BakePaintMap; +use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::geom::Mesh; + +use super::shared_handle::SharedHandle; + +/// Everything a texture set's cage shell is built from except the distances, which only move its corners +#[derive(Clone, Debug, PartialEq)] +pub(super) struct CageShellKey { + mesh_id: u64, + high: SharedHandle, + cage_file: SharedHandle, + material: usize, + uv_tiles: Vec, + tile_resolutions: BTreeMap, + cage_kind: CageType, + relative_to_bounding_box: bool, + average_normals: bool, + use_low_as_high: bool, + skew: SkewSettings, + /// The painted skew and cage maps + paint: [SharedHandle; 2], +} + +impl CageShellKey { + pub(super) fn of(session: &Session, texture_set: usize) -> Option { + let set = session.doc.project.texture_sets.get(texture_set)?; + let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); + Some(CageShellKey { + mesh_id: session.mesh_id, + high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + material: set.material, + uv_tiles: set.uv_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + cage_kind: set.bake.cage.kind, + relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, + average_normals: set.bake.cage.average_normals, + use_low_as_high: set.bake.high_poly.use_low_as_high, + skew: set.bake.skew, + paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], + }) + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_upload.rs b/crates/ui-egui/src/bake_scene/cage_upload.rs new file mode 100644 index 00000000..81951645 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_upload.rs @@ -0,0 +1,10 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; +use texturecraft_engine::geom::glam::Vec3; + +/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from +pub struct CageUpload { + pub corners: Vec, + pub shell: Arc, +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs new file mode 100644 index 00000000..c8a181f5 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -0,0 +1,140 @@ +use std::sync::mpsc::{Receiver, TryRecvError}; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::{HighPolyReach, high_poly_missed}; +use texturecraft_engine::core::HighPolySettings; + +use super::cage_shell_key::CageShellKey; +use crate::gpu::SceneSync; + +/// Each set's (max frontal, max rear) and the selected-set filter +type ShownDistances = (Vec<(f32, f32)>, Option); + +/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show +#[derive(Default)] +pub(super) struct ReachLink { + /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for + keys: Vec>, + high_id: u64, + job: Option>>>, + reach: Vec>, + /// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for + shown: Option, +} + +impl ReachLink { + /// Whether a reach is being worked out (the view must keep drawing to pick it up) + pub(super) fn busy(&self) -> bool { + self.job.is_some() + } + + /// Send the colors again (the GPU lost what it was sent); the reach itself stays + pub(super) fn resend(&mut self) { + self.shown = None; + } + + /// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears + pub(super) fn poll(&mut self) { + let Some(job) = &self.job else { return }; + + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed + pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { + // Coalesce paint edits while a worker runs; after polling it, the next job captures the latest inputs + if self.job.is_some() { + return; + } + + let set_count = session.doc.project.texture_sets.len(); + let keys: Vec> = session + .doc + .project + .texture_sets + .iter() + .enumerate() + .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) + .collect(); + if keys != self.keys || high_id != self.high_id { + let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect(); + self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || { + inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect() + })); + (self.keys, self.high_id) = (keys, high_id); + } + + // Colors wait for the reach being worked out: the old ones stay until it arrives + if self.job.is_some() { + return; + } + + let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect(); + let shown = (distances, only_set); + if self.shown.as_ref() == Some(&shown) { + return; + } + + let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + + out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count))); + self.shown = Some(shown); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + use texturecraft_engine::bake::BakePaintMap; + use texturecraft_engine::core::BakePaintTarget; + use texturecraft_engine::geom::primitives; + + #[test] + fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() { + let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); + session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap(); + let (sender, receiver) = mpsc::channel(); + let mut link = ReachLink { job: Some(receiver), ..Default::default() }; + + // Hold the original job open while paint and mesh inputs change + for amount in [0.25, 0.5, 0.75] { + session.doc.bake_paint.insert((0, BakePaintTarget::Cage), Arc::new(BakePaintMap::constant(amount))); + let mut out = SceneSync::default(); + link.sync(&session, 2, None, &mut out); + assert!(out.bake_high_missed.is_none()); + } + assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver"); + link.poll(); + + // The finished job is stale: a new job must capture the latest settings before sending colors + session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + let mut out = SceneSync::default(); + link.sync(&session, 2, None, &mut out); + assert!(link.busy()); + assert!(out.bake_high_missed.is_none()); + + for _ in 0..2000 { + link.poll(); + if !link.busy() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + assert!(!link.busy(), "the latest reach must finish"); + link.sync(&session, 2, None, &mut out); + let (high_id, missed) = out.bake_high_missed.unwrap(); + assert_eq!(high_id, 2); + assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]); + assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly"); + } +} diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs new file mode 100644 index 00000000..15ceb1d8 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/shared_handle.rs @@ -0,0 +1,32 @@ +use std::sync::{Arc, Weak}; + +/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it +#[derive(Debug)] +pub(super) struct SharedHandle(Option>); + +impl SharedHandle { + pub(super) fn of(value: Option<&Arc>) -> SharedHandle { + SharedHandle(value.map(Arc::downgrade)) + } +} + +impl Clone for SharedHandle { + fn clone(&self) -> Self { + SharedHandle(self.0.clone()) + } +} + +impl Default for SharedHandle { + fn default() -> Self { + SharedHandle(None) + } +} + +impl PartialEq for SharedHandle { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(this), Some(other)) => Weak::ptr_eq(this, other), + (this, other) => this.is_none() && other.is_none(), + } + } +} diff --git a/crates/ui-egui/src/color_selection_editor.rs b/crates/ui-egui/src/color_selection_editor.rs new file mode 100644 index 00000000..482bc227 --- /dev/null +++ b/crates/ui-egui/src/color_selection_editor.rs @@ -0,0 +1,104 @@ +//! Properties of a color selection effect: tolerance and the ID colors it selects + +use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::id_color_pick::IdColorPick; +use crate::theme::Tokens; +use crate::widgets::{icon_button, slider_edit}; + +/// Width of one R, G or B readout, so the columns line up from row to row (fits "G: 255") +const READOUT_WIDTH: f32 = 50.0; + +/// Height of a color row's swatch and readouts, as tall as the app's other swatches +const ROW_HEIGHT: f32 = 18.0; + +const SWATCH_WIDTH: f32 = 36.0; + +const ROW_BUTTON_SIZE: f32 = 20.0; + +/// Tolerance, a Colors list with a pick mode, and one row per ID color (swatch, re-pick, R/G/B, remove) +pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, colors: &[[f32; 3]], tolerance: f32) { + let tokens = Tokens::get(ui.ctx()); + let mut edited_tolerance = tolerance; + if let Some(merge) = slider_edit(ui, tr("Tolerance"), &mut edited_tolerance, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": effect.0, "tolerance": edited_tolerance, "merge": merge})); + } + + let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); + let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id)); + if !has_id_map { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (F8) to pick colors from the mesh."))).color(tokens.warning)); + } + + let picking = app.picking_id_color.filter(|pick| pick.effect == effect); + ui.group(|ui| { + ui.horizontal(|ui| { + ui.label(tr("Colors")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let adding = picking.is_some_and(|pick| pick.index.is_none()); + let button = egui::Button::new(format!("{} {}", ic::EYEDROPPER, tr("Pick color"))).selected(adding); + if ui.add_enabled(has_id_map, button).clicked() { + toggle_pick(app, effect, None, adding); + } + }); + }); + + for (index, color) in colors.iter().enumerate() { + ui.horizontal(|ui| { + id_swatch(ui, *color); + let repicking = picking.is_some_and(|pick| pick.index == Some(index)); + let repick = ui.add_enabled_ui(has_id_map, |ui| icon_button(ui, ic::EYEDROPPER, tr("Pick color"), repicking, ROW_BUTTON_SIZE)).inner; + if repick.clicked() { + toggle_pick(app, effect, Some(index), repicking); + } + + for (channel, value) in ["R", "G", "B"].iter().zip(display_bytes(*color)) { + ui.allocate_ui_with_layout(vec2(READOUT_WIDTH, ROW_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(READOUT_WIDTH); + ui.label(format!("{channel}: {value}")); + }); + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let remove = ui.add_enabled_ui(colors.len() > 1, |ui| icon_button(ui, ic::MINUS, tr("Remove"), false, ROW_BUTTON_SIZE)).inner; + if remove.clicked() { + // Removing a row changes the indices of pending replacements + IdColorPick::end(app); + let remaining: Vec<[f32; 3]> = colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect(); + app.run("effect.set", json!({"effect": effect.0, "colors": remaining})); + } + }); + }); + } + }); +} + +/// The layer whose mask holds `effect` +fn effect_owner(app: &TextureCraftApp, effect: LayerId) -> LayerId { + app.session.doc.project.effect(effect).map_or(effect, |(owner, _)| owner) +} + +fn toggle_pick(app: &mut TextureCraftApp, effect: LayerId, index: Option, running: bool) { + if running { + IdColorPick::end(app); + } else { + IdColorPick::start(app, effect, index); + } +} + +/// An ID color as the ID map view draws it: the stored value, unconverted, in 0–255 +fn display_bytes(color: [f32; 3]) -> [u8; 3] { + color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8) +} + +fn id_swatch(ui: &mut Ui, color: [f32; 3]) { + let tokens = Tokens::get(ui.ctx()); + let [red, green, blue] = display_bytes(color); + let (rect, _) = ui.allocate_exact_size(vec2(SWATCH_WIDTH, ROW_HEIGHT), Sense::hover()); + ui.painter().rect(rect, f32::from(tokens.radius), Color32::from_rgb(red, green, blue), Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3a74a80b..0bb90ccd 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,10 +5,10 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, - Source, + BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, + LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; -use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; +use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -19,6 +19,13 @@ use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it +const NEW_FILTER: &str = "hsl"; +const FILTER_SWATCH_WIDTH: f32 = 36.0; +const FILTER_HINT_SIZE: f32 = 10.5; +/// The most colors `effect.set {colors}` takes for a gradient map +const MAX_GRADIENT_STOPS: usize = 16; + const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), Color32::from_rgb(0xd0, 0x80, 0x30), @@ -208,48 +215,43 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "Add effect" items for `layer` (toolbar and context menu). Effects that fit both stacks go -/// to the content when it is the selected target; generators and compare always go to the -/// mask, anchor points to the content. +/// "Add effect" items for `layer`: content when it is the selected target, else the mask fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app); - let t = if content { "content" } else { "mask" }; + let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); + + // Generators and compare masks always go to the mask, anchor points to the content let items = [ (tr("Add generator"), "effect.add.generator", json!({})), - (tr("Add paint"), "effect.add.paint", json!({"target": t})), - (tr("Add fill"), "effect.add.fill", json!({"target": t})), - (tr("Add levels"), "effect.add.levels", json!({"target": t})), + (tr("Add paint"), "effect.add.paint", json!({"target": target})), + (tr("Add fill"), "effect.add.fill", json!({"target": target})), + (tr("Add levels"), "effect.add.levels", json!({"target": target})), (tr("Add compare mask"), "effect.add.compare", json!({})), + (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), (tr("Add anchor point"), "effect.add.anchor", json!({})), ]; - let run = |app: &mut TextureCraftApp, id: &str, p: &Value| { + for (label, command, params) in items { + let enabled = command != "effect.add.anchor" || !layer.is_group(); + if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + continue; + } + if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(id, with(p, json!({"layer": layer.id.0}))); - }; - for (label, id, p) in items { - let enabled = id != "effect.add.anchor" || !layer.is_group(); - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - run(app, id, &p); - ui.close(); + + let added = app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + // The neutral filter is a placeholder: its slot opens the picker to choose the real one + if command == "effect.add.filter" + && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) + { + app.ui.dock.focus(crate::docking::Panel::Properties); + crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); } + + ui.close(); } - // The filter library (material finishes only fill content). - ui.menu_button(tr("Add filter"), |ui| { - let mut group = ""; - for f in FILTERS.iter().filter(|f| content || f.mask) { - if f.group != group { - ui.label(caption(tr(f.group))); - group = f.group; - } - if ui.button(tr(f.label)).clicked() { - run(app, "effect.add.filter", &json!({"target": t, "filter": f.id})); - ui.close(); - } - } - }); } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { @@ -912,35 +914,44 @@ fn mesh_map_color(map: BakedMap) -> Color32 { /// The Properties tab title: what the panel edits. pub(crate) fn properties_title(app: &TextureCraftApp) -> String { - let p = &app.session.doc.project; - let what = match (app.session.selected_layer().and_then(|id| p.layers.get(&id)), app.session.target) { - (Some(_), StackTarget::Effect(e)) => p.effect(e).map(|(_, x)| x.name.clone()).unwrap_or_default(), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), - (Some(l), StackTarget::Content) if l.is_group() => tr("Folder").to_string(), - (Some(l), StackTarget::Content) if l.instance_source().is_some() => tr("Instance").to_string(), + let project = &app.session.doc.project; + let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { + // Polygon fill keeps its own properties whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(), + (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), + (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), _ => tr(app.session.tool.tool.label()).to_string(), }; format!("{} - {what}", tr("Properties")) } pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let sel = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); - let target = app.session.target; - egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| match (&sel, target) { - (Some(l), StackTarget::Effect(e)) => effect_properties(app, ui, l, e), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => fill_properties(app, ui, l), - (Some(l), StackTarget::Content) if l.is_group() => { - ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tk.text_dim)); + egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); +} + +/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool +pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); + + match (&selected, app.session.target) { + // Polygon fill shows its own settings and says what it fills into, whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui), + (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), + (Some(layer), StackTarget::Content) if layer.is_group() => { + ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); } - (Some(l), StackTarget::Content) if l.instance_source().is_some() => instance_properties(app, ui, l), - (Some(l), StackTarget::Mask) => { - height_mask_section(app, ui, l); + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), + (Some(layer), StackTarget::Mask) => { + height_mask_section(app, ui, layer); ui.separator(); tool_properties(app, ui); } _ => tool_properties(app, ui), - }); + } } /// An instance draws its source: point there for edits. @@ -990,38 +1001,43 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - // Brush preview: a stroke and a sphere with the tool's material. + let tokens = Tokens::get(ui.ctx()); + // Brush preview: a stroke and a sphere with the tool's material let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 88.0), Sense::hover()); - let p = ui.painter(); - p.rect_filled(rect, 2.0, tk.viewport); - let half = rect.width() * 0.5; - let b = &app.session.tool.brush; - let mut pts = Vec::new(); - for k in 0..=40 { - let t = k as f32 / 40.0; - pts.push(pos2(rect.left() + 14.0 + t * (half - 28.0), rect.center().y + (t * 9.0).sin() * 18.0)); + let painter = ui.painter(); + painter.rect_filled(rect, 2.0, tokens.viewport); + let half_width = rect.width() * 0.5; + let brush = &app.session.tool.brush; + let mut points = Vec::new(); + for step in 0..=40 { + let fraction = step as f32 / 40.0; + points.push(pos2(rect.left() + 14.0 + fraction * (half_width - 28.0), rect.center().y + (fraction * 9.0).sin() * 18.0)); } - let w = (b.size / 0.25 * 60.0).clamp(2.0, 30.0); - let a = (b.flow * b.opacity * 255.0) as u8; - p.add(egui::Shape::line(pts, Stroke::new(w, Color32::from_white_alpha(a.max(30))))); - let base = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); - crate::thumbs::paint_sphere(p, pos2(rect.left() + half * 1.5, rect.center().y), 36.0, base); + + let stroke_width = (brush.size / 0.25 * 60.0).clamp(2.0, 30.0); + let alpha = (brush.flow * brush.opacity * 255.0) as u8; + painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(30))))); + let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); + crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), 36.0, base_color); ui.add_space(4.0); + ui.horizontal(|ui| { + let button_size = ui.spacing().interact_size.y; for (tab, icon, tip) in [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, ic::SPHERE, tr("Material"))] { - if icon_button(ui, icon, tip, app.ui.props_tab == tab, 24.0).clicked() { + if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { app.ui.props_tab = tab; } } }); ui.separator(); + if app.session.quick_mask.editing { - ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } + let tool_section: Option = match app.session.tool.tool { Tool::Projection => Some(stencil_section), Tool::Clone => Some(clone_section), @@ -1034,6 +1050,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { section(app, ui); ui.separator(); } + match app.ui.props_tab { PropsTab::Brush => brush_section(app, ui), PropsTab::Alpha => alpha_section(app, ui), @@ -1133,6 +1150,104 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } +/// Width of the label column in polygon fill's properties +const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; + +/// Polygon fill's properties: how it selects and fills, its blending, then what it fills with (material, mask gray, or why it can't fill) +fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::FillHitTest; + + let button_size = ui.spacing().interact_size.y; + ui.label(caption(&tr("Polygon fill").to_uppercase())); + property_row(ui, tr("Selection mode"), tr("A click fills what is under it; a dragged rectangle fills what it selects as it grows"), |ui| { + icon_button(ui, ic::SELECTION, tr("Rectangle fill"), true, button_size); + }); + property_row( + ui, + tr("Fill mode"), + tr("Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands"), + |ui| crate::toolbar::fill_mode_buttons(app, ui), + ); + property_row(ui, tr("Hit-test"), tr("How a rectangle selects polygons"), |ui| { + for (hit_test, icon, tooltip) in [ + (FillHitTest::Intersection, ic::INTERSECT_SQUARE, tr("Intersection: fill polygons the rectangle touches")), + (FillHitTest::ContainedCenter, ic::SELECTION_FOREGROUND, tr("Contained center: fill polygons whose center is in the rectangle")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_hit_test == hit_test, button_size).clicked() { + app.session.tool.fill_hit_test = hit_test; + } + } + }); + ui.horizontal(|ui| { + ui.checkbox(&mut app.session.tool.fill_visible_only, tr("Visible polygons only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, tr("Fill only polygons the camera sees (3D view)"))); + }); + section(ui, "sec_polygon_fill_blending", tr("Blending"), false, |ui| { + let mut opacity = app.session.tool.brush.opacity * 100.0; + if slider(ui, tr("Opacity"), &mut opacity, 0.0..=100.0, 0).changed() { + app.session.tool.brush.opacity = (opacity / 100.0).clamp(0.0, 1.0); + } + }); + ui.separator(); + + match polygon_fill_paints_mask(app) { + Ok(false) => { + ui.label(caption(&tr("Material").to_uppercase())); + material_controls(app, ui); + } + Ok(true) => { + ui.label(caption(&tr("Grayscale").to_uppercase())); + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; + } + } + Err(note) => { + ui.label(RichText::new(note).color(Tokens::get(ui.ctx()).text_dim)); + } + } +} + +/// One polygon fill setting: its label in a fixed column, its `controls`, and an info icon with `info` at the right edge +fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let label_width = ui.label(label).rect.width(); + ui.add_space((POLYGON_FILL_LABEL_WIDTH - label_width - ui.spacing().item_spacing.x).max(0.0)); + controls(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, info)); + }); +} + +/// A dim info icon explaining a setting on hover +fn info_icon(ui: &mut Ui, text: &str) { + ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text); +} + +/// What a polygon fill paints into now: Ok(true) a mask (gray), Ok(false) layer content (material), or a note on why it can't fill +fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { + if app.session.quick_mask.editing { + return Err(tr("Editing the quick mask: fills paint where painting is allowed. Press U to finish.").to_string()); + } + + let project = &app.session.doc.project; + let Some(layer) = app.session.selected_layer().and_then(|id| project.layers.get(&id)) else { + return Err(tr("Select a paint layer or a layer's mask to fill").to_string()); + }; + + match app.session.target { + StackTarget::Mask => Ok(true), + StackTarget::Effect(_) => Ok(!targets_content(app)), + StackTarget::Content => { + let content = project.content_layer(layer.id).unwrap_or(layer); + if matches!(content.kind, LayerKind::Paint) { + Ok(false) + } else { + Err(trf("\"{layer}\" can't be filled: select a paint layer or a layer's mask", &[("layer", &layer.name)])) + } + } + } +} + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); @@ -1354,59 +1469,68 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; +/// The tool's material under a "Material" heading fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + material_controls(app, ui); +} + +/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask) +fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::core::ChannelKind; + + let tokens = Tokens::get(ui.ctx()); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let on = app.session.tool.enabled.contains(c); - if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo})); + for channel in &channels { + let on = app.session.tool.enabled.contains(channel); + if chip(ui, tr(channel.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("tool.material", json!({"channel": channel.id(), "enabled": solo || !on, "solo": solo})); } } }); ui.add_space(4.0); - let mask_mode = !targets_content(app); - if mask_mode { - let mut v = app.session.tool.mask_value; - if slider(ui, tr("Mask value (gray)"), &mut v, 0.0..=1.0, 2).changed() { - app.session.tool.mask_value = v; + + if !targets_content(app) { + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Mask value (gray)"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; } return; } - for c in chans { - if !app.session.tool.enabled.contains(&c) { + + for channel in channels { + if !app.session.tool.enabled.contains(&channel) { continue; } - let mut v = app.session.tool.values.get(&c).copied().unwrap_or(c.default_value()); - match c.kind() { - texturecraft_engine::core::ChannelKind::Color => { + let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()); + match channel.kind() { + ChannelKind::Color => { ui.horizontal(|ui| { - ui.label(tr(c.label())); - if color_swatch(ui, &format!("tool_{}", c.id()), &mut v, ui.available_width() - 4.0) { - app.session.tool.values.insert(c, v); + ui.label(tr(channel.label())); + if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { + app.session.tool.values.insert(channel, value); } }); } - texturecraft_engine::core::ChannelKind::NormalMap => { - ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tk.text_dim)); + ChannelKind::NormalMap => { + ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tokens.text_dim)); } - texturecraft_engine::core::ChannelKind::Signed => { - if slider(ui, tr(c.label()), &mut v[0], -1.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Signed => { + if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } - texturecraft_engine::core::ChannelKind::Scalar => { - if slider(ui, tr(c.label()), &mut v[0], 0.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Scalar => { + if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } } } if app.session.tool.tool == Tool::Eraser { - ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tk.text_dim)); + ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim)); } } @@ -1566,46 +1690,56 @@ fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> Str trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } -/// Projection and per-channel sources of a fill: a fill layer's (`base` = {"layer"}, `on` = -/// its enabled channels) or a content fill effect's (`base` = {"effect"}, `on` = the channels -/// it has a source for). `reader` is the layer owning the fill (for anchor sources). +/// Space above a fill's Material caption, setting it apart from the projection +const FILL_MATERIAL_GAP: f32 = 6.0; + +/// Space between a fill's channel chips and its channel sources +const FILL_CHANNELS_GAP: f32 = 4.0; + +/// Projection and sources of a fill layer or fill effect (`base`) for its channels `on`; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { - use texturecraft_engine::core::Projection; let salt = base.to_string(); - if let Projection::Decal(d) = &fill.projection { - decal_editor(app, ui, d, reader); + if let Projection::Decal(decal) = &fill.projection { + decal_editor(app, ui, decal, reader); } else { - projection_editor(app, ui, fill, base); + projection_editor(app, ui, fill, base, &salt); } - ui.add_space(6.0); + + ui.add_space(FILL_MATERIAL_GAP); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let enabled = on.contains(c); - if chip(ui, tr(c.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": solo || !enabled, "solo": solo}))); + for channel in &channels { + let enabled = on.contains(channel); + if chip(ui, tr(channel.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "enabled": solo || !enabled, "solo": solo}))); } } }); - ui.add_space(4.0); + + ui.add_space(FILL_CHANNELS_GAP); let anchors = anchors_below(app, reader); - for c in chans { - if !on.contains(&c) { - continue; + for channel in channels { + if on.contains(&channel) { + fill_channel(app, ui, fill, base, channel, &anchors, &salt); } - fill_channel(app, ui, fill, base, c, &anchors, &salt); } } -/// The projection of a fill (other than a decal): kind, scale, and what the kind adds (UV -/// rotation and offset, tri-planar sharpness, an axis, a world offset). Each edit sends only the -/// field it changed; the command keeps the others. -fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { - use texturecraft_engine::core::Projection; - let proj_label = fill.projection.label(); - combo(ui, tr("Projection"), tr(proj_label), |ui| { +/// Slider range of a fill's scale or tiling +const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; + +/// Slider range of a UV fill's rotation, a full turn +const FILL_ROTATION_DEGREES_RANGE: std::ops::RangeInclusive = 0.0..=360.0; + +/// Tri-planar hardness, the exponent weighting the three projections; `layer.fill.projection` clamps to the same range +const TRIPLANAR_HARDNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; + +/// A fill's projection kind, axis and hardness, then its collapsible UV transformations +fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, salt: &str) { + let projection_label = fill.projection.label(); + combo(ui, tr("Projection"), tr(projection_label), |ui| { for (id, label) in [ ("uv", n_("UV projection")), ("triplanar", n_("Tri-planar projection")), @@ -1613,55 +1747,63 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: ("spherical", n_("Spherical projection")), ("cylindrical", n_("Cylindrical projection")), ] { - if ui.selectable_label(proj_label == label, tr(label)).clicked() { + if ui.selectable_label(projection_label == label, tr(label)).clicked() { app.run("layer.fill.projection", with(base, json!({"projection": id}))); } } }); - let mut scale = match &fill.projection { + + // Each edit sends only the fields it changed; the command keeps the others + let mut edit = |fields: Value| { + app.run("layer.fill.projection", with(base, fields)); + }; + if let Projection::Planar { axis, .. } | Projection::Cylindrical { axis, .. } = &fill.projection + && let Some(picked_axis) = axis_combo(ui, *axis) + { + edit(json!({"axis": picked_axis})); + } + if let Projection::Triplanar { sharpness, .. } = &fill.projection { + let mut hardness = *sharpness; + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut hardness, TRIPLANAR_HARDNESS_RANGE, 1) { + edit(json!({"sharpness": hardness, "merge": merge})); + } + } + + // One id per fill so each keeps its own open or closed state + section(ui, &format!("sec_fill_transform{salt}"), tr("UV transformations"), true, |ui| { + projection_transform(ui, &fill.projection, &mut edit); + }); +} + +/// Scale plus what the projection kind adds: UV rotation and offset, or a world offset +fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl FnMut(Value)) { + let mut scale = match projection { Projection::Uv { scale, .. } => scale[0], Projection::Triplanar { scale, .. } | Projection::Planar { scale, .. } | Projection::Spherical { scale } | Projection::Cylindrical { scale, .. } => { *scale } Projection::Decal(_) => return, }; - let mut edit = |extra: Value| app.run("layer.fill.projection", with(base, extra)); - if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { + if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, FILL_SCALE_RANGE, 2) { edit(json!({"scale": scale, "merge": merge})); } - match &fill.projection { + + match projection { Projection::Uv { rotation, offset, .. } => { - let mut r = *rotation; - if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut r, 0.0..=360.0, 0) { - edit(json!({"rotation": r, "merge": merge})); + let mut rotation_degrees = *rotation; + if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { + edit(json!({"rotation": rotation_degrees, "merge": merge})); } - if let Some((o, merge)) = offset_sliders(ui, ["U", "V"], *offset) { - edit(json!({"offset": o, "merge": merge})); + if let Some((edited_offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { + edit(json!({"offset": edited_offset, "merge": merge})); } } - Projection::Triplanar { sharpness, offset, .. } => { - let mut s = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Blend sharpness"), &mut s, 1.0..=64.0, 1) { - edit(json!({"sharpness": s, "merge": merge})); - } - if let Some((o, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": o, "merge": merge})); + Projection::Triplanar { offset, .. } | Projection::Planar { offset, .. } => { + if let Some((edited_offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { + edit(json!({"offset": edited_offset, "merge": merge})); } } - Projection::Planar { axis, offset, .. } => { - if let Some(a) = axis_combo(ui, *axis) { - edit(json!({"axis": a})); - } - if let Some((o, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": o, "merge": merge})); - } - } - Projection::Cylindrical { axis, .. } => { - if let Some(a) = axis_combo(ui, *axis) { - edit(json!({"axis": a})); - } - } - Projection::Spherical { .. } | Projection::Decal(_) => {} + Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Decal(_) => {} } } @@ -1844,63 +1986,42 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { let tk = Tokens::get(ui.ctx()); - let Some((_, e)) = app.session.doc.project.effect(eid).map(|(l, e)| (l, e.clone())) else { return }; + let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; + let id = eid.0; ui.horizontal(|ui| { ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(e.blend.label())).show_ui(ui, |ui| { - for m in BlendMode::all() { - if ui.selectable_label(m == e.blend, tr(m.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{m:?}")})); + egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { + for mode in BlendMode::all() { + if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); } } }); }); - let mut op = e.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": op, "merge": merge})); + let mut opacity = effect.opacity; + if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); } ui.separator(); - match &e.kind { - EffectKind::Generator(g) => { - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(g.kind.label())).show_ui(ui, |ui| { - for k in GeneratorKind::ALL { - if ui.selectable_label(k == g.kind, tr(k.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple. - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{k:?}")})); - } - } - }); - let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); - let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); - let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); - let mut inv = g.invert; - let r5 = ui.checkbox(&mut inv, tr("Invert")); - if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r5.changed().then_some(false)) { - app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv, "merge": merge})); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label( - RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning), - ); - } - } - EffectKind::Levels(l) => { + + match &effect.kind { + EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), + EffectKind::Levels(levels) => { ui.label(caption(tr("Levels"))); - levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); - let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; + levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high)); + let mut values = [levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]; let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; let mut edit = None; - for (i, label) in labels.iter().enumerate() { - let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2)); + for (index, label) in labels.iter().enumerate() { + let range = if index == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; + edit = edit.or(slider_edit(ui, label, &mut values[index], range, 2)); } if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge})); + app.run( + "effect.set", + json!({"effect": id, "inLow": values[0], "inHigh": values[1], "gamma": values[2], "outLow": values[3], "outHigh": values[4], "merge": merge}), + ); } } EffectKind::Fill { source, .. } => { @@ -1916,25 +2037,25 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - for (a, label) in &anchors { - if ui.selectable_label(source.anchor() == Some(*a), trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("effect.set", json!({"effect": id, "anchor": a.0})); + for (anchor, label) in &anchors { + if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } } }); match source { - Source::Uniform(v) => { - let mut x = v[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "value": x, "merge": merge})); + Source::Uniform(color) => { + let mut value = color[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } Source::Anchor { channel, .. } => { - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == *channel, tr(c.label())).clicked() { - app.run("effect.set", json!({"effect": id, "anchorChannel": c.id()})); + for option in channels { + if ui.selectable_label(option == *channel, tr(option.label())).clicked() { + app.run("effect.set", json!({"effect": id, "anchorChannel": option.id()})); } } }); @@ -1946,10 +2067,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); } } - EffectKind::Material(f) => { + EffectKind::Material(fill) => { ui.label(caption(tr("Fill"))); - let on: Vec = f.sources.keys().copied().collect(); - fill_editor(app, ui, f, &json!({"effect": id}), &on, layer.id); + let enabled: Vec = fill.sources.keys().copied().collect(); + fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id); } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); @@ -1959,7 +2080,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|x| x.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == eid) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") @@ -1973,30 +2094,103 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: .color(tk.text_dim), ); let editing = app.session.tool.path.editing; - for i in 0..paths.len() { + for index in 0..paths.len() { ui.horizontal(|ui| { - let on = editing == Some((eid, i)); - if ui.selectable_label(on, format!("{} {}", tr("Path"), i + 1)).on_hover_text(tr("Edit")).clicked() { - if on { + let selected = editing == Some((eid, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { app.run("tool.path", json!({"clear": true})); } else { - app.run("path.edit", json!({"effect": id, "index": i})); + app.run("path.edit", json!({"effect": id, "index": index})); } } if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { - app.run("path.remove", json!({"effect": id, "index": i})); + app.run("path.remove", json!({"effect": id, "index": index})); } }); } tool_properties(app, ui); } - EffectKind::Filter(f) => filter_properties(app, ui, id, f), + EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); } } } +/// The settings of generator effect `id`. +fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let tk = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Replace the generator kind: remove and add keeps ordering simple + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + let (mut level, mut softness, mut noise, mut noise_scale, mut invert) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.invert); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(invert_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "invert": invert, "merge": merge}), + ); + } + + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); + } +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tk = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + /// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel /// picked here), with the input range marked. Recomputed after a document change once no /// pointer button is held, so dragging a slider keeps the last one. @@ -2029,82 +2223,85 @@ fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Laye } } -/// The parameters of filter effect `id`. -fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { +/// The filter slot and the parameters of filter effect `id` +fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); - let set = |app: &mut TextureCraftApp, key: &str, v: Value, merge: bool| { - let mut p = json!({ "effect": id, "merge": merge }); - p[key] = v; - app.run("effect.set", p); + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + let mut params = json!({ "effect": id, "merge": merge }); + params[key] = value; + app.run("effect.set", params); }; - ui.label(caption(tr(f.label()))); - if let Filter::Hsl { hue, .. } = f { - let mut h = hue * 360.0; - if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { - set(app, "hue", json!(h / 360.0), merge); + crate::filter_slot::show(app, ui, id, filter); + + if let Filter::Hsl { hue, .. } = filter { + let mut degrees = hue * 360.0; + if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) { + set(app, "hue", json!(degrees / 360.0), merge); } } - for (key, label, mut v, lo, hi) in scalar_params(f) { + + for (key, label, mut value, min, max) in scalar_params(filter) { let decimals = if matches!(key, "seed" | "levels") { 0 - } else if hi - lo > 10.0 { + } else if max - min > 10.0 { 1 } else { 2 }; - if let Some(merge) = slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { - set(app, key, json!(v), merge); + if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { + set(app, key, json!(value), merge); } } - match f { + + match filter { Filter::ColorBalance { shadows, midtones, highlights } => { for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)] { ui.label(RichText::new(label).strong()); - let mut v = *rgb; + let mut balance = *rgb; let mut edit = None; - for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - edit = edit.or(slider_edit(ui, name, x, -1.0..=1.0, 2)); + for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { + edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2)); } if let Some(merge) = edit { - set(app, key, json!(v), merge); + set(app, key, json!(balance), merge); } } } Filter::ReplaceColor { from, to, .. } => { for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut v = *rgb; + let mut color = *rgb; ui.horizontal(|ui| { - if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) { - set(app, key, json!(v), false); + if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) { + set(app, key, json!(color), false); } ui.label(label); }); } - ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::GradientMap { colors } => { - let mut c = colors.clone(); + let mut stops = colors.clone(); let mut changed = false; ui.horizontal_wrapped(|ui| { - for (i, col) in c.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0); + for (i, stop) in stops.iter_mut().enumerate() { + changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH); } }); ui.horizontal(|ui| { - if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - c.push(c.last().copied().unwrap_or([1.0; 3])); + if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { + stops.push(stops.last().copied().unwrap_or([1.0; 3])); changed = true; } - if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - c.pop(); + if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { + stops.pop(); changed = true; } }); if changed { - set(app, "colors", json!(c), false); + set(app, "colors", json!(stops), false); } - ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::Warp { .. } | Filter::DirectionalBlur { .. } @@ -2115,7 +2312,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter | Filter::Bevel { .. } | Filter::Mosaic { .. } | Filter::Glow { .. } => { - ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } _ => {} } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 11de63af..0dcbdaa2 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -24,8 +24,12 @@ use crate::theme::Tokens; pub enum Panel { Viewport, Assets, - BakeMaps, - BakeSettings, + // Saved layouts name the bake panels by their earlier names + #[serde(rename = "BakeMaps")] + MeshMapSettings, + #[serde(rename = "BakeSettings")] + CommonSettings, + MeshMapBakers, TextureSetList, Layers, TextureSetSettings, @@ -37,14 +41,15 @@ pub enum Panel { } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 11] = [ +pub const VIEWS: [(&str, Panel); 12] = [ ("ui.view.assets", Panel::Assets), - ("ui.view.bakeMaps", Panel::BakeMaps), - ("ui.view.bakeSettings", Panel::BakeSettings), + ("ui.view.bakeMaps", Panel::MeshMapSettings), + ("ui.view.bakeSettings", Panel::CommonSettings), ("ui.view.display", Panel::Display), ("ui.view.history", Panel::History), ("ui.view.layers", Panel::Layers), ("ui.view.log", Panel::Log), + ("ui.view.meshMapBakers", Panel::MeshMapBakers), ("ui.view.properties", Panel::Properties), ("ui.view.shader", Panel::Shader), ("ui.view.textureSetList", Panel::TextureSetList), @@ -59,17 +64,18 @@ pub fn view_panel(id: &str) -> Option { impl Panel { pub(crate) fn available_in(self, mode: crate::state::Mode) -> bool { match self { - Self::BakeMaps | Self::BakeSettings => mode == crate::state::Mode::Baking, + Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers => mode == crate::state::Mode::Baking, Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings => mode != crate::state::Mode::Baking, _ => true, } } - pub const ALL: [Panel; 12] = [ + pub const ALL: [Panel; 13] = [ Panel::Viewport, Panel::Assets, - Panel::BakeMaps, - Panel::BakeSettings, + Panel::MeshMapSettings, + Panel::CommonSettings, + Panel::MeshMapBakers, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, @@ -84,8 +90,9 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", - Panel::BakeMaps => "Bake Maps", - Panel::BakeSettings => "Settings", + Panel::MeshMapSettings => "Mesh Map Settings", + Panel::CommonSettings => "Common Settings", + Panel::MeshMapBakers => "Mesh Map Bakers", Panel::TextureSetList => "Texture Sets", Panel::Layers => "Layers", Panel::TextureSetSettings => "Texture Set Settings", @@ -122,8 +129,8 @@ fn tabs(panels: &[Panel]) -> Node { Node::Tabs { panels: panels.to_vec(), active: 0 } } -fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) -> Node { - Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) } +fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node { + Node::Split { axis, size, first: Box::new(first), second: Box::new(second) } } /// The default: assets left of the viewport; texture set list, layers (tabbed with the texture @@ -131,9 +138,14 @@ fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) - /// shader, history and log are closed and open as floating windows. pub fn default_workspace() -> Workspace { use Panel::*; - let column = - split(SplitAxis::Vertical, 0.125, tabs(&[TextureSetList]), split(SplitAxis::Vertical, 0.57, tabs(&[Layers, TextureSetSettings]), tabs(&[Properties]))); - let root = split(SplitAxis::Horizontal, 0.115, tabs(&[Assets]), split(SplitAxis::Horizontal, 0.78, tabs(&[Viewport]), column)); + let column = split( + SplitAxis::Vertical, + SplitSize::Ratio(0.125), + tabs(&[TextureSetList]), + split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = + split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { if let Some(rect) = panel.float_rect() { @@ -149,7 +161,7 @@ pub fn default_workspace() -> Workspace { workspace.hidden.push((panel, location)); } } - for panel in [BakeMaps, BakeSettings] { + for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { workspace.hidden.push(( panel, Location { @@ -206,17 +218,28 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock +/// Width of the bake layout's texture set and mesh map bakers column, in points +const BAKERS_COLUMN_WIDTH: f32 = 200.0; +/// Width of the bake layout's common and mesh map settings column, in points +const SETTINGS_COLUMN_WIDTH: f32 = 330.0; +/// Height of the log under the bake layout's columns, in points +const BAKING_LOG_HEIGHT: f32 = 160.0; +/// Share of the first bake column the texture set list takes above the mesh map bakers +const TEXTURE_SET_LIST_SHARE: f32 = 0.4; + /// 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, + /// A saved layout could not be read, so this is the painting default in its place + replaced_unreadable: bool, } impl Default for Dock { fn default() -> Self { - Dock { workspace: default_workspace(), raise: None } + Dock { workspace: default_workspace(), raise: None, replaced_unreadable: false } } } @@ -240,18 +263,27 @@ impl<'de> Deserialize<'de> for Dock { } impl Dock { - /// The dock for a saved layout; the default when it is not a valid workspace. + /// The dock for a saved layout; the default, marked as a replacement, when it is not a valid workspace pub fn from_value(value: Value) -> Dock { + let unreadable = Dock { replaced_unreadable: true, ..Dock::default() }; let default = default_workspace(); let loaded = serde_json::from_value::(value).ok(); - let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return Dock::default() }; + let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return unreadable }; + workspace.reconcile(|_| true, permissions, &default); if validate(&workspace).is_err() { - return Dock::default(); + return unreadable; } - Dock { workspace, raise: None } + + Dock { workspace, raise: None, replaced_unreadable: false } } + /// Whether a saved layout could not be read and this dock is the painting default instead + pub(crate) fn replaced_unreadable(&self) -> bool { + self.replaced_unreadable + } + + /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport pub(crate) fn for_baking() -> Self { let mut workspace = default_workspace(); for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { @@ -259,17 +291,19 @@ impl Dock { workspace.hidden.push((panel, location)); } } - workspace.hidden.retain(|(panel, _)| !matches!(panel, Panel::BakeMaps | Panel::BakeSettings)); - workspace.layout = Layout { - root: Some(Node::Split { - axis: SplitAxis::Horizontal, - size: SplitSize::FixedFirst(320.0), - first: Box::new(tabs(&[Panel::TextureSetList, Panel::BakeSettings, Panel::BakeMaps])), - second: Box::new(tabs(&[Panel::Viewport])), - }), - floating: Vec::new(), - }; - Dock { workspace, raise: None } + + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + workspace.hidden.retain(|(panel, _)| !bake_panels.contains(panel)); + + let gutter_width = f32::from(crate::theme::GUTTER); + let list_column = split(SplitAxis::Vertical, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); + let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); + let columns = split(SplitAxis::Horizontal, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); + let columns_over_log = split(SplitAxis::Vertical, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; + let root = split(SplitAxis::Horizontal, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); + workspace.layout = Layout { root: Some(root), floating: Vec::new() }; + Dock { workspace, raise: None, replaced_unreadable: false } } pub fn workspace(&self) -> &Workspace { @@ -354,6 +388,17 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle { s } +/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included, +/// do not take it. +pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> bool { + let modal = context.memory(|memory| memory.top_modal_layer()).is_some(); + #[cfg(not(target_arch = "wasm32"))] + let modal = modal || crate::updates_ui::blocks_input(app); + #[cfg(target_arch = "wasm32")] + let _ = app; + modal +} + /// Draw the dock (viewport and panels) into `ui`. pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { for panel in Panel::ALL { @@ -366,7 +411,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { 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(context.memory(|memory| memory.top_modal_layer()).is_some()); + let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context)); if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } @@ -401,9 +446,10 @@ impl DockContent for Panels<'_> { return; } egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::BakeMaps => crate::bake_mode::bake_body(app, ui), + Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), - Panel::BakeSettings => crate::bake_mode::settings_body(app, ui), + Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), + Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), Panel::TextureSetList => crate::dock::texture_set_list(app, ui), Panel::Layers => crate::dock::layers(app, ui), @@ -425,8 +471,6 @@ impl DockContent for Panels<'_> { fn logical_label(&self, panel: &Panel) -> String { match panel { Panel::Properties => crate::dock::properties_title(self.app), - Panel::BakeMaps => tr("Bake Maps").to_string(), - Panel::BakeSettings => tr("Settings").to_string(), p => tr(p.name()).to_string(), } } @@ -475,6 +519,20 @@ mod tests { assert_eq!(back, dock); } + #[test] + fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + let dock = Dock::for_baking(); + assert!(validate(dock.workspace()).is_ok()); + assert_eq!( + panels_of(dock.workspace()), + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport] + ); + assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings)); + + let back: Dock = serde_json::from_str(&serde_json::to_string(&dock).unwrap()).unwrap(); + assert_eq!(back, dock); + } + #[test] fn unreadable_layouts_become_the_default() { for text in [ diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index fe2fc5e4..5d5ddafc 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -341,11 +341,14 @@ pub fn import(app: &mut TextureCraftApp, preset: &ExportPreset) { #[cfg(not(target_arch = "wasm32"))] fn import_file(app: &mut TextureCraftApp, _ctx: &egui::Context) { - let Some(path) = rfd::FileDialog::new().add_filter(tr("Export template"), &["json"]).pick_file() else { return }; - match texturecraft_engine::formats::load_preset(&path) { - Ok(p) => import(app, &p), - Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &path.display()), ("error", &e)]), true), - } + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::open().filter(tr("Export template"), &["json"]), Bound::App, |app, paths| { + let Some(path) = paths.first() else { return }; + match texturecraft_engine::formats::load_preset(path) { + Ok(p) => import(app, &p), + Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &path.display()), ("error", &e)]), true), + } + }); } #[cfg(target_arch = "wasm32")] @@ -356,26 +359,43 @@ fn import_file(_app: &mut TextureCraftApp, ctx: &egui::Context) { fn export_file(app: &mut TextureCraftApp) { let Some(p) = selected(app) else { return }; let name = format!("{}.json", sanitize_file_stem(&p.name)); - let saved = texturecraft_engine::formats::preset_to_json(&p).map_err(|e| e.to_string()).and_then(|json| write_json(&name, &json)); - match saved { - Ok(Some(to)) => app.toast(trf("Exported template \"{name}\" to {path}", &[("name", &p.name), ("path", &to)]), false), - Ok(None) => {} - Err(e) => app.toast(trf("Couldn't export the template: {error}", &[("error", &e)]), true), - } + let json = match texturecraft_engine::formats::preset_to_json(&p) { + Ok(json) => json, + Err(e) => { + export_failed(app, &e); + return; + } + }; + write_json(app, p.name, name, json); } -/// Save `json` with the native dialog (Ok(None): cancelled). +fn export_failed(app: &mut TextureCraftApp, error: &dyn std::fmt::Display) { + app.toast(trf("Couldn't export the template: {error}", &[("error", error)]), true); +} + +fn exported(app: &mut TextureCraftApp, name: &str, to: &str) { + app.toast(trf("Exported template \"{name}\" to {path}", &[("name", &name), ("path", &to)]), false); +} + +/// Asks where to save `json` with the native dialog. #[cfg(not(target_arch = "wasm32"))] -fn write_json(name: &str, json: &str) -> Result, String> { - let Some(path) = rfd::FileDialog::new().add_filter(tr("Export template"), &["json"]).set_file_name(name).save_file() else { return Ok(None) }; - std::fs::write(&path, json).map_err(|e| e.to_string())?; - Ok(Some(path.display().to_string())) +fn write_json(app: &mut TextureCraftApp, preset: String, name: String, json: String) { + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::save().filter(tr("Export template"), &["json"]).file_name(name), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + match std::fs::write(path, &json) { + Ok(()) => exported(app, &preset, &path.display().to_string()), + Err(e) => export_failed(app, &e), + } + }); } #[cfg(target_arch = "wasm32")] -fn write_json(name: &str, json: &str) -> Result, String> { - crate::web_files::download(name, json.as_bytes())?; - Ok(Some(name.to_string())) +fn write_json(app: &mut TextureCraftApp, preset: String, name: String, json: String) { + match crate::web_files::download(&name, json.as_bytes()) { + Ok(()) => exported(app, &preset, &name), + Err(e) => export_failed(app, &e), + } } /// Read the user's templates: the library folder on the desktop, the app storage on the web. diff --git a/crates/ui-egui/src/file_dialogs.rs b/crates/ui-egui/src/file_dialogs.rs new file mode 100644 index 00000000..3c9df8c0 --- /dev/null +++ b/crates/ui-egui/src/file_dialogs.rs @@ -0,0 +1,111 @@ +//! Native file dialogs that never block the frame (craft-dialogs). +//! +//! An action that needs a path calls [`TextureCraftApp::ask_file`] and returns. The dialog shows at +//! the end of the frame, and the continuation runs with the answer on a later frame. The browser +//! build has no native dialogs (`web_files.rs`). + +use std::panic::Location; +use std::path::PathBuf; +use std::sync::Arc; + +pub use craft_dialogs::{Answer, FileDialog, Override, Request}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; + +/// Whether an answer still needs the project that was open when the dialog was asked for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Bound { + /// The continuation reads or changes the open project, and does not run on another one. + Project, + /// The continuation does not depend on the open project. + App, +} + +/// What runs with the answer. The list is empty when nothing was chosen. +type Then = Box)>; + +/// Which dialog was asked for, for which project and by which code. Asking again with all three +/// the same brings the open panel to the front instead of queuing a second one. +#[derive(Clone, Debug, PartialEq)] +struct AskKey { + request: Request, + project: Option, + origin: &'static Location<'static>, +} + +/// A dialog's continuation. +pub struct Asked { + key: AskKey, + then: Then, +} + +/// The app's dialogs and the requests not yet answered. +pub struct FileDialogs { + dialogs: craft_dialogs::Dialogs, + asked: Vec, +} + +impl FileDialogs { + /// The dialogs of the app whose context is `ctx`: an answer wakes its event loop. + pub fn new(ctx: egui::Context) -> FileDialogs { + FileDialogs { dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), asked: Vec::new() } + } + + /// Answers every request with `answer_with` instead of a native dialog (tests). + pub fn set_override(&mut self, answer_with: Option) { + self.dialogs.set_override(answer_with); + } + + /// Requests that have not been answered yet. + pub fn pending(&self) -> usize { + self.asked.len() + } + + /// Shows the next dialog asked for. Call at the end of every frame with the window. + pub fn show_pending(&mut self, frame: &eframe::Frame) { + self.dialogs.show_pending(Some(frame)); + } +} + +impl TextureCraftApp { + /// Queues `dialog`. `then` runs on a later frame with the chosen paths, or with none after + /// Cancel, after a dialog that could not be shown, and when `bound` is [`Bound::Project`] and + /// another project has been opened since. Returns false, and drops `then`, when the same dialog + /// is already showing or waiting. + #[track_caller] + pub(crate) fn ask_file(&mut self, dialog: FileDialog, bound: Bound, then: impl FnOnce(&mut TextureCraftApp, Vec) + 'static) -> bool { + let project = (bound == Bound::Project).then_some(self.session.project_id); + let key = AskKey { request: Request::File(dialog.clone()), project, origin: Location::caller() }; + if self.file_dialogs.asked.contains(&key) { + self.file_dialogs.dialogs.raise(); + return false; + } + self.file_dialogs.asked.push(key.clone()); + self.file_dialogs.dialogs.ask(dialog, Asked { key, then: Box::new(then) }); + true + } + + /// Runs the continuations of the dialogs that have answered. + pub(crate) fn run_file_dialog_answers(&mut self) { + for (asked, answer) in self.file_dialogs.dialogs.take_answers() { + let Asked { key, then } = asked; + if let Some(i) = self.file_dialogs.asked.iter().position(|k| *k == key) { + self.file_dialogs.asked.remove(i); + } + let paths = match answer { + Answer::Paths(paths) => paths, + Answer::Unavailable(why) => { + self.toast(trf("The file dialog couldn't be shown: {error}", &[("error", &why)]), true); + Vec::new() + } + Answer::Cancelled | Answer::Message(_) => Vec::new(), + }; + let moved_on = key.project.is_some_and(|project| project != self.session.project_id); + if moved_on && !paths.is_empty() { + self.toast(tr("The project changed while the dialog was open, so nothing was done"), true); + } + then(self, if moved_on { Vec::new() } else { paths }); + } + } +} diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs new file mode 100644 index 00000000..172017d9 --- /dev/null +++ b/crates/ui-egui/src/filter_slot.rs @@ -0,0 +1,120 @@ +//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it + +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Filter, LayerId}; +use texturecraft_engine::filter_lib::{filter_effects, find}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; +use crate::widgets::elided; + +const SLOT_HEIGHT: f32 = 52.0; +const SLOT_ROUNDING: f32 = 3.0; +const BORDER_WIDTH: f32 = 1.0; +const THUMBNAIL_SIZE: f32 = 40.0; +const THUMBNAIL_INSET: f32 = 6.0; +const CAPTION_FONT_SIZE: f32 = 11.0; +const NAME_FONT_SIZE: f32 = 13.0; +/// Gap between the caption's and the name's centers +const LINE_GAP: f32 = 15.0; +const CARET_INSET: f32 = 14.0; +const CARET_FONT_SIZE: f32 = 14.0; +/// Gap between the slot and its keyboard focus outline +const FOCUS_MARGIN: f32 = 2.0; + +/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { + let ctx = ui.ctx().clone(); + let on_mask = is_on_mask(app, effect); + let current = find(filter.label()).map(|def| def.id); + let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id)); + let name = tr(filter.label()); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); + + let popup = ui.make_persistent_id(("filter_picker", effect)); + let open_requested = take_open_request(&ctx, effect); + + if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { + resource_picker::toggle(&ctx, popup); + } + + let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); + paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name); + + let items = |thumbs: &mut Thumbs| { + filter_effects() + .iter() + .filter(|def| def.mask || !on_mask) + .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) + .collect() + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); + if let Some(id) = picked.filter(|id| Some(*id) != current) { + app.run("effect.set", json!({"effect": effect, "filter": id})); + } +} + +/// Has the slot of filter effect `effect` open its picker if it shows this frame or the next, as Add filter does for the filter it adds +pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|data| data.insert_temp(open_request_id(), (effect, frame))); +} + +/// Whether an open request for `effect`'s slot is waiting, removing it; a request older than a frame lapses +fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { + let frame = ctx.cumulative_frame_nr(); + let request = ctx.data_mut(|data| data.remove_temp::<(u64, u64)>(open_request_id())); + + // Properties can draw before or after the menu that asked, so a request lives for this frame and the next + request.is_some_and(|(requested_effect, requested_frame)| requested_effect == effect && frame <= requested_frame + 1) +} + +/// Where the effect whose slot should open its picker waits +fn open_request_id() -> egui::Id { + egui::Id::unique("filter_slot_open_request") +} + +/// Whether filter effect `effect` sits in a mask rather than the layer content +fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { + let project = &app.session.doc.project; + let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner)); + owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) +} + +/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); + if focused { + painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + + if let Some(texture) = thumbnail { + let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + // Long names are cut short rather than run under the thumbnail or the caret + let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; + let text_right = rect.right() - CARET_INSET * 2.0; + let text_center_x = (text_left + text_right) * 0.5; + let lines = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + for (text, size, color, offset) in lines { + let galley = elided(painter, text, size, color, text_right - text_left); + painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); + } + + let caret_color = if highlighted { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 77db5727..acdac551 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,9 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; + +use crate::bake_scene::{BakeSceneLink, CageUpload}; /// Content shown through the aux texture. #[derive(Clone, Copy, Debug, PartialEq)] @@ -25,6 +27,9 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); +/// The low poly's UV seam edges (vertex pairs) per material +pub type UvSeamEdges = Vec>; + /// What the renderer must catch up with before drawing. #[derive(Default)] pub struct SceneSync { @@ -36,6 +41,16 @@ pub struct SceneSync { pub env: Option<(String, Option>)>, pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec)>, pub aux: Vec<(usize, u32, Vec)>, + /// Bake mode's high poly (`None` removes it) and the id it is sent under + pub bake_high: Option<(Option>, u64)>, + /// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0) + pub bake_high_missed: Option<(u64, Vec)>, + /// Changed cages: texture set, the cage or `None` to remove it, its topology + pub bake_cages: Vec<(usize, Option, u64)>, + /// Texture sets left after some were removed: their cages go too + pub bake_cage_count: Option, + /// The low poly's UV seams per material, for mesh id + pub uv_seams: Option<(u64, UvSeamEdges)>, } /// Lives in egui's callback resources. @@ -78,6 +93,7 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + bake_scene: BakeSceneLink, } /// Compositing time per frame: a full recomposite of a large texture set spreads over frames. @@ -124,6 +140,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + bake_scene: BakeSceneLink::default(), } } @@ -133,126 +150,158 @@ impl GpuLink { std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner)) } - /// Collect everything the GPU needs this frame (runs the compositor first). + /// Whether bake mode's visualization is still being worked out off the UI thread + pub fn bake_busy(&self) -> bool { + self.bake_scene.busy() + } + /// Compositing progress (0..1) while tiles wait to be composited. pub fn composite_progress(&self, s: &Session) -> Option { let pending = s.pending_tiles(); (pending > 0 && self.composite_total > 0).then(|| 1.0 - pending as f32 / self.composite_total as f32) } - /// `spent_ms`: time this frame already took before the sync. - pub fn sync(&mut self, s: &mut Session, aux_map: Option, shift: u32, spent_ms: f64) -> SceneSync { - let start = crate::now_ms(); + /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took + pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { + let start_ms = crate::now_ms(); let mut queued = 0usize; - let left = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start) - queued as f64 * UPLOAD_MS_PER_TILE; - let pending = s.pending_tiles(); + let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - s.update_for(COMPOSITE_BUDGET_MS.min(left(0)).max(MIN_SLICE_MS), crate::now_ms); + session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); + let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { self.mesh_id = 0; self.sets.clear(); self.env = Default::default(); + self.bake_scene.resend(); self.reset.store(true, Ordering::Release); } - if self.mesh_id != s.mesh_id { - out.mesh = Some((s.mesh.clone(), s.mesh_id)); - self.mesh_id = s.mesh_id; + + if self.mesh_id != session.mesh_id { + out.mesh = Some((session.mesh.clone(), session.mesh_id)); + self.mesh_id = session.mesh_id; self.aux.clear(); } - let sets: Vec = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect(); + + let sets: Vec = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect(); if sets != self.sets || shift != self.shift || out.mesh.is_some() { - out.sets = Some((sets.clone(), s.mesh.materials.len().max(1), shift)); + out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift)); self.sets = sets; self.shift = shift; } - let d = &s.doc.project.display; - let image = d.environment_resource().and_then(|n| s.images.get(n)); - let ptr = image.map_or(0, |i| Arc::as_ptr(i) as usize); - if self.env.0 != d.environment || self.env.1 != ptr { - self.env = (d.environment.clone(), ptr); - out.env = Some((d.environment.clone(), image.cloned())); + + let display = &session.doc.project.display; + let image = display.environment_resource().and_then(|name| session.images.get(name)); + let image_identity = image.map_or(0, |image| Arc::as_ptr(image) as usize); + if self.env.0 != display.environment || self.env.1 != image_identity { + self.env = (display.environment.clone(), image_identity); + out.env = Some((display.environment.clone(), image.cloned())); } + if self.reset.swap(false, Ordering::AcqRel) { - for c in &mut s.caches { - c.upload.extend(texturecraft_engine::compose::all_tiles(c.size.0, c.size.1)); + for cache in &mut session.caches { + cache.upload.extend(texturecraft_engine::compose::all_tiles(cache.size.0, cache.size.1)); } self.aux.clear(); } - for ts in 0..s.caches.len() { - let tiles = s.take_uploads(ts); + + for texture_set in 0..session.caches.len() { + let tiles = session.take_uploads(texture_set); if tiles.is_empty() { continue; } + let mut done = 0; - if let Some(cache) = s.caches.get(ts) { + if let Some(cache) = session.caches.get(texture_set) { let empty = Default::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&empty); - let comp = &cache.composite; - // In chunks while the frame has time (at least one chunk); the rest waits. + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + let composite = &cache.composite; + // In chunks while the frame has time (at least one chunk); the rest waits for chunk in tiles.chunks(UPLOAD_CHUNK) { let bytes: Vec<_> = chunk .par_iter() - .flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty))) - .map(|(k, tx, ty)| (ts, k, tx, ty, tile_bytes(comp, baked, k, tx, ty))) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); done += chunk.len(); - if left(queued) < MIN_SLICE_MS { + if time_left_ms(queued) < MIN_SLICE_MS { break; } } } - if let (Some(rest), Some(cache)) = (tiles.get(done..), s.caches.get_mut(ts)) { + if let (Some(rest), Some(cache)) = (tiles.get(done..), session.caches.get_mut(texture_set)) { cache.upload.extend(rest.iter().copied()); } } + match aux_map { - Some(AuxView::MeshMap(m)) => { - for ts in 0..s.caches.len() { - let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); - let key = (format!("{m:?}"), rev); - if self.aux.get(&ts) == Some(&key) { + Some(AuxView::MeshMap(map)) => { + for texture_set in 0..session.caches.len() { + let revision = session.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)).map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}"), revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - out.aux.push((ts, res, texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res))); - self.aux.insert(ts, key); + let Some(cache) = session.caches.get(texture_set) else { continue }; + + let resolution = texturecraft_render::aux_size(cache.size); + out.aux.push(( + texture_set, + resolution, + texturecraft_render::mesh_maps::mesh_map_rgba( + session.doc.baked.get(&texture_set), + map, + resolution, + cache.size, + &cache.composite.block_scales, + ), + )); + self.aux.insert(texture_set, key); } } Some(AuxView::Mask(id)) => { - if let Some((ts, _, _)) = s.doc.project.locate(id) { - let key = (format!("mask{}", id.0), s.revision); - if self.aux.get(&ts) != Some(&key) && !s.stroke_active() { - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - if let Some(rgba) = s.mask_view_rgba(id, res) { - out.aux.push((ts, res, rgba)); + if let Some((texture_set, _, _)) = session.doc.project.locate(id) { + let key = (format!("mask{}", id.0), session.revision); + if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { + let resolution = + session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size)); + if let Some(rgba) = session.mask_view_rgba(id, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } } Some(AuxView::QuickMask) => { - for ts in 0..s.caches.len() { - let Some(cache) = s.caches.get(ts) else { continue }; - let key = (format!("quickmask{}", s.quick_mask.revision), cache.revision); - if self.aux.get(&ts) == Some(&key) { + for texture_set in 0..session.caches.len() { + let Some(cache) = session.caches.get(texture_set) else { continue }; + + let key = (format!("quickmask{}", session.quick_mask.revision), cache.revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let res = texturecraft_render::aux_size(cache.size); - if let Some(rgba) = s.quick_mask_rgba(ts, res) { - out.aux.push((ts, res, rgba)); + let resolution = texturecraft_render::aux_size(cache.size); + if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } None => {} } + + self.bake_scene.sync(session, bake, &mut out); out } } +/// Mask view resolution for a texture set without a composite cache +const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024; + /// Paint callback for one view. pub struct ViewCallback { pub frame: Frame, @@ -289,39 +338,64 @@ impl CallbackTrait for ViewCallback { if let Some((mesh, id)) = &sync.mesh { gpu.renderer.set_mesh(device, queue, mesh, *id); } - if let Some((sets, mats, shift)) = &sync.sets { + if let Some((sets, material_count, shift)) = &sync.sets { gpu.renderer.set_display_shift(*shift); - let reset = gpu.renderer.set_texture_sets(device, queue, sets, *mats); + let reset = gpu.renderer.set_texture_sets(device, queue, sets, *material_count); if !reset.is_empty() { gpu.reset.store(true, Ordering::Release); } } - for (ts, k, tx, ty, bytes) in &sync.tiles { - gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes); + for (texture_set, kind, tile_x, tile_y, bytes) in &sync.tiles { + gpu.renderer.upload_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes); } - for (ts, size, bytes) in &sync.aux { - gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); + for (texture_set, size, bytes) in &sync.aux { + gpu.renderer.upload_aux(device, queue, *texture_set, *size, bytes); + } + if let Some((high, id)) = &sync.bake_high + && let Err(error) = gpu.renderer.set_bake_high(device, queue, high.as_deref(), *id) + { + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + if reports.errors.len() < MAX_GPU_ERRORS && !reports.errors.contains(&error) { + reports.errors.push(error); + } + gpu.ctx.request_repaint(); + } + if let Some((id, missed)) = &sync.bake_high_missed { + gpu.renderer.set_bake_high_missed(queue, *id, missed); + } + if let Some(count) = sync.bake_cage_count { + gpu.renderer.truncate_bake_cages(count); + } + for (texture_set, cage, topology) in &sync.bake_cages { + let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); + } + if let Some((mesh_id, seams)) = &sync.uv_seams { + gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); } } - // Also installs (or rejects) full-size textures WebGPU answered for since last frame. + + // Also installs (or rejects) full-size textures WebGPU answered for since last frame gpu.renderer.prepare(device, queue, encoder, &self.frame); let failed = gpu.renderer.take_memory_failures(); if !failed.is_empty() { - let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); - for ts in failed { - if !r.memory.contains(&ts) { - r.memory.push(ts); + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for texture_set in failed { + if !reports.memory.contains(&texture_set) { + reports.memory.push(texture_set); } } - // This frame's report drain already ran: the next frame shows the toast. + // This frame's report drain already ran: the next frame shows the toast gpu.ctx.request_repaint(); } if gpu.renderer.awaiting_gpu() { gpu.ctx.request_repaint(); } - let ppp = screen.pixels_per_point; - let r = self.rect; - gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels); + + let pixels_per_point = screen.pixels_per_point; + let rect = self.rect; + let blit_rect = [rect.min.x * pixels_per_point, rect.min.y * pixels_per_point, rect.width() * pixels_per_point, rect.height() * pixels_per_point]; + gpu.renderer.set_blit_rect(queue, self.frame.view_id, blit_rect, screen.size_in_pixels); Vec::new() } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 80105c00..7ccc1d84 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -134,13 +134,15 @@ pub fn os_language() -> &'static str { locale.map_or("en", |l| language_for_locale(&l)) } +/// Tests that switch the global UI language, or draw the UI under it, run one at a time. +#[cfg(test)] +pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + #[cfg(test)] mod tests { + use super::TEST_LANGUAGE as LANGUAGE; use super::*; - /// Tests that switch the global UI language run one at a time. - static LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); - /// Every key the UI looks up: `tr("…")` / `trf("…"` literals in the sources, plus the /// static catalogs whose labels are translated where they are shown. fn keys() -> Vec { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index ff6d2d92..afdfaeb0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "شدة الانسداد المحيطي (AO)"), ("About TextureCraft", "حول TextureCraft"), ("About TextureCraft...", "حول TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "إضافة طبقة تعبئة بهذه الصورة (أو اسحبها إلى العرض ثلاثي الأبعاد لوضعها كملصق)", - ), - ("Add a fill layer using this pattern", "إضافة طبقة تعبئة بهذا النمط"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "إضافة طبقة تعبئة بهذه المادة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "أضف نقطة ارتكاز إلى طبقة سفلية لاستخدام مكدسها كقناع."), ("Add anchor point", "إضافة نقطة ارتكاز"), ("Add as decal (view center)", "إضافة كملصق (مركز العرض)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "إضافة رسم"), ("Add paint layer", "إضافة طبقة رسم"), ("Add smart material from the shelf", "إضافة مادة ذكية من الرف"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "إضافة مجلد المادة الذكية فوق الطبقة المحددة (أو اسحبه إلى مكدس الطبقات)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "إضافة هذه اللمسة النهائية إلى خشونة وارتفاع الطبقة المحددة (أو اسحبها إلى طبقة)", - ), ("Add to the layer content", "إضافة إلى محتوى الطبقة"), ("Add to the mask", "إضافة إلى القناع"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "إضافة إلى محتوى الطبقة المحددة، أو إلى قناعها عند تحديد القناع (أو اسحبها إلى طبقة)", - ), ("Add white mask", "إضافة قناع أبيض"), ("Adjustments", "تعديلات"), ( @@ -107,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "المحور"), ("Back to painting", "العودة إلى الرسم"), ("Backface culling", "استبعاد الوجوه الخلفية"), + ("Bake an ID map (F8) to pick colors from the mesh.", "اخبز خريطة المعرّفات ID (F8) لالتقاط الألوان من الشبكة."), ("Bake Mesh Maps", "خبز خرائط المجسم"), ("Bake mesh maps", "خبز خرائط المجسم"), ( @@ -126,7 +106,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "النواظم المنحنية"), ("Bevel", "شطف الحواف"), ("Black", "أسود"), - ("Blend sharpness", "حدة المزج"), ("Blending", "الدمج"), ("Blending mode of the displayed channel", "نمط الدمج للقناة المعروضة"), ("Blur", "تمويه"), @@ -143,6 +122,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "مدمج: {mesh}"), ("Cage: {name}", "القفص (Cage): {name}"), ("Camera", "الكاميرا"), + ("Colors", "الألوان"), + ("Go to camera 1", "الانتقال إلى الكاميرا 1"), + ("Go to camera 2", "الانتقال إلى الكاميرا 2"), + ("Go to camera 3", "الانتقال إلى الكاميرا 3"), + ("Go to camera 4", "الانتقال إلى الكاميرا 4"), + ("Go to camera 5", "الانتقال إلى الكاميرا 5"), + ("Go to camera 6", "الانتقال إلى الكاميرا 6"), + ("Go to camera 7", "الانتقال إلى الكاميرا 7"), + ("Go to camera 8", "الانتقال إلى الكاميرا 8"), + ("Go to camera 9", "الانتقال إلى الكاميرا 9"), ("Camera settings", "إعدادات الكاميرا"), ("Cancel", "إلغاء"), ("Cancel the stroke", "إلغاء ضربة الفرشاة"), @@ -151,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "القناة"), ("Channel source: uniform value, procedural, image or anchor", "مصدر القناة: قيمة موحدة، إجرائي، صورة أو نقطة ارتكاز"), ("Channels", "القنوات"), + ("Check for Updates...", "التحقق من وجود تحديثات..."), ("Checker", "رقعة شطرنج"), ("Clamp", "تقييد القيم"), ("Clear", "مسح"), @@ -317,6 +307,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "تعبئة"), ("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"), ("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"), + ("Filter", "مرشح"), ("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"), ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), @@ -556,6 +547,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "مدار"), ("Orthographic", "متوازي (إملائي)"), + ("Perspective", "منظوري"), ("Output directory", "دليل الإخراج"), ("Output high", "المخرج العالي"), ("Output low", "المخرج المنخفض"), @@ -564,6 +556,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "تراكب (Overlay)"), ("Overlay opacity", "عتامة التراكب"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - خشونة ومعدنية (TextureCraft)"), + ("Pick color", "التقاط لون"), ("PNG image", "صورة PNG"), ("Padding", "الحشو (Padding)"), ("Paint", "رسم"), @@ -653,7 +646,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "التصيير، بتتبع المسار"), ("Replace", "استبدال"), ("Replace Color", "استبدال اللون"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "استبدال قناع الطبقة المحددة بهذا القناع الذكي (أو اسحبه إلى طبقة)"), ("Replacement color", "لون الاستبدال"), ("Report a bug...", "الإبلاغ عن خطأ..."), ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), @@ -690,6 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "خدوش"), ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), + ("Search", "بحث"), ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), @@ -808,13 +801,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ مع الخامات"), ("UV checker", "رقعة فحص UV"), ("UV island fill", "تعبئة جزيرة UV"), + ("UV transformations", "تحويلات UV"), ("UV projection", "إسقاط UV"), ("UV tiles", "بلاطات UV"), ("UV tiles (UDIM)", "بلاطات UV (UDIM)"), ("Undo", "تراجع"), ("Uniform value", "قيمة موحدة"), ("Use an equirectangular .hdr or .exr image as the environment", "استخدم صورة .hdr أو .exr متساوية المستطيلات كبيئة"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "استخدم كألفا للفرشاة (أو اسحبها إلى منفذ العرض أو خصائص الفرشاة)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), ("Value", "القيمة"), ("Version {version}", "الإصدار {version}"), @@ -963,7 +956,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "توسيط النواظم"), ("BBox", "صندوق الإحاطة"), ("BSphere", "كرة الإحاطة"), - ("Bake Maps", "خبز الخرائط"), + ("Mesh Map Bakers", "مُخبِزات خرائط المجسم"), + ("Common Settings", "الإعدادات المشتركة"), + ("Mesh Map Settings", "إعدادات خرائط المجسم"), + ("Check All", "تحديد الكل"), + ("No Parameters", "لا توجد معلمات"), ("Bake Selected Textures ({n})", "خبز الخامات المحددة ({n})"), ("By Mesh Name", "حسب اسم المجسم"), ("Cage", "القفص"), @@ -1041,6 +1038,51 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Remove resolution override", "إزالة تجاوز الدقة"), + ("Texture set resolution", "دقة مجموعة الخامات"), + ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), + ("Baking Visualization", "تصور الخبز"), + ("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"), + ("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"), + ("UV Seams", "فواصل UV"), + ("Project Mesh (LP)", "مجسم الإسقاط (LP)"), + ("Edges", "الحواف"), + ("Cavities", "التجاويف"), + ("Edges and cavities", "الحواف والتجاويف"), + ("Raw curvature", "الانحناء الخام"), + ("Detail sizes", "أحجام التفاصيل"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "يقرأ خريطة الانحناء كما خُبزت: تغيير الوضع أو أحد الأحجام يفعّل أحجام التفاصيل.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه", + ), + ("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."), + ("Fill mode", "وضع التعبئة"), + ("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"), + ("Hit-test", "اختبار الإصابة"), + ("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"), + ("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"), + ("Rectangle fill", "تعبئة مستطيلة"), + ("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"), + ("Selection mode", "وضع التحديد"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV", + ), + ("Visible polygons only", "المضلعات المرئية فقط"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), + ("The file dialog couldn't be shown: {error}", "تعذر عرض نافذة الملفات: {error}"), + ("The project changed while the dialog was open, so nothing was done", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"), ("Cores kept for the UI", "أنوية محجوزة للواجهة"), ("Max RAM while saving", "أقصى ذاكرة عند الحفظ"), ( diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0ae53a8e..13de434e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO-Intensität"), ("About TextureCraft", "Über TextureCraft"), ("About TextureCraft...", "Über TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Füllebene mit diesem Bild hinzufügen (oder in die 3D-Ansicht ziehen, um es als Decal zu platzieren)", - ), - ("Add a fill layer using this pattern", "Füllebene mit diesem Muster hinzufügen"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Füllebene mit diesem Material über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Einer darunterliegenden Ebene einen Ankerpunkt hinzufügen, um ihren Stapel als Maske zu verwenden.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Malen hinzufügen"), ("Add paint layer", "Malebene hinzufügen"), ("Add smart material from the shelf", "Smart-Material aus der Ablage hinzufügen"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Smart-Material-Ordner über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Diese Oberfläche zu Rauheit und Höhe der ausgewählten Ebene hinzufügen (oder auf eine Ebene ziehen)", - ), ("Add to the layer content", "Zum Ebeneninhalt hinzufügen"), ("Add to the mask", "Zur Maske hinzufügen"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Zum Inhalt der ausgewählten Ebene hinzufügen oder zu ihrer Maske, wenn die Maske ausgewählt ist (oder auf eine Ebene ziehen)", - ), ("Add white mask", "Weiße Maske hinzufügen"), ("Adjustments", "Korrekturen"), ( @@ -110,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Achse"), ("Back to painting", "Zurück zum Malen"), ("Backface culling", "Rückseiten-Culling"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Backe eine ID-Map (F8), um Farben vom Mesh aufzunehmen."), ("Bake Mesh Maps", "Mesh-Maps backen"), ("Bake mesh maps", "Mesh-Maps backen"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Mesh-Maps backen (F8) für Generatoren auf Basis von Krümmung, AO und Dicke."), @@ -126,7 +106,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Gebogene Normalen"), ("Bevel", "Abschrägung"), ("Black", "Schwarz"), - ("Blend sharpness", "Übergangsschärfe"), ("Blending", "Überblendung"), ("Blending mode of the displayed channel", "Füllmethode des angezeigten Kanals"), ("Blur", "Weichzeichnen"), @@ -143,6 +122,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integriert: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Kamera"), + ("Colors", "Farben"), + ("Go to camera 1", "Zu Kamera 1 wechseln"), + ("Go to camera 2", "Zu Kamera 2 wechseln"), + ("Go to camera 3", "Zu Kamera 3 wechseln"), + ("Go to camera 4", "Zu Kamera 4 wechseln"), + ("Go to camera 5", "Zu Kamera 5 wechseln"), + ("Go to camera 6", "Zu Kamera 6 wechseln"), + ("Go to camera 7", "Zu Kamera 7 wechseln"), + ("Go to camera 8", "Zu Kamera 8 wechseln"), + ("Go to camera 9", "Zu Kamera 9 wechseln"), ("Camera settings", "Kameraeinstellungen"), ("Cancel", "Abbrechen"), ("Cancel the stroke", "Strich abbrechen"), @@ -151,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Kanal"), ("Channel source: uniform value, procedural, image or anchor", "Kanalquelle: einheitlicher Wert, prozedural, Bild oder Anker"), ("Channels", "Kanäle"), + ("Check for Updates...", "Nach Updates suchen..."), ("Checker", "Schachbrett"), ("Clamp", "Begrenzen"), ("Clear", "Leeren"), @@ -341,6 +331,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Füllung"), ("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"), ("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"), + ("Filter", "Filter"), ("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"), ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), @@ -589,6 +580,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbit"), ("Orthographic", "Orthografisch"), + ("Perspective", "Perspektivisch"), ("Output directory", "Ausgabeverzeichnis"), ("Output high", "Ausgabe hoch"), ("Output low", "Ausgabe tief"), @@ -597,6 +589,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Ineinanderkopieren"), ("Overlay opacity", "Überlagerungsdeckkraft"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallisch/Rauheit (TextureCraft)"), + ("Pick color", "Farbe aufnehmen"), ("PNG image", "PNG-Bild"), ("Padding", "Padding"), ("Paint", "Malen"), @@ -692,10 +685,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, Path Tracing"), ("Replace", "Ersetzen"), ("Replace Color", "Farbe ersetzen"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Maske der ausgewählten Ebene durch diese Smart-Maske ersetzen (oder auf eine Ebene ziehen)", - ), ("Replacement color", "Ersatzfarbe"), ("Report a bug...", "Fehler melden..."), ("Rescan the library folder", "Bibliotheksordner neu einlesen"), @@ -732,6 +721,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Kratzer"), ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), + ("Search", "Suchen"), ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), @@ -850,16 +840,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ mit Texturen"), ("UV checker", "UV-Schachbrett"), ("UV island fill", "UV-Insel-Füllung"), + ("UV transformations", "UV-Transformationen"), ("UV projection", "UV-Projektion"), ("UV tiles", "UV-Kacheln"), ("UV tiles (UDIM)", "UV-Kacheln (UDIM)"), ("Undo", "Rückgängig"), ("Uniform value", "Einheitlicher Wert"), ("Use an equirectangular .hdr or .exr image as the environment", "Ein equirektangulares .hdr- oder .exr-Bild als Umgebung verwenden"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Als Pinsel-Alpha verwenden (oder in das Ansichtsfenster oder die Pinseleigenschaften ziehen)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Für Screenshots den Steuerkanal oder `texturecraft-cli render` verwenden"), ("Value", "Wert"), ("Version {version}", "Version {version}"), @@ -1012,7 +999,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normalen mitteln"), ("BBox", "Begrenzungsrahmen"), ("BSphere", "Begrenzungskugel"), - ("Bake Maps", "Maps backen"), + ("Mesh Map Bakers", "Mesh-Map-Baker"), + ("Common Settings", "Allgemeine Einstellungen"), + ("Mesh Map Settings", "Mesh-Map-Einstellungen"), + ("Check All", "Alle auswählen"), + ("No Parameters", "Keine Parameter"), ("Bake Selected Textures ({n})", "Ausgewählte Texturen backen ({n})"), ("By Mesh Name", "Nach Mesh-Name"), ("Cage", "Käfig"), @@ -1090,6 +1081,57 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Remove resolution override", "Auflösungsüberschreibung entfernen"), + ("Texture set resolution", "Auflösung des Textursets"), + ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"), + ("Not imported: {files}", "Nicht importiert: {files}"), + ("Baking Visualization", "Bake-Visualisierung"), + ("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"), + ("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"), + ("UV Seams", "UV-Nähte"), + ("Project Mesh (LP)", "Projektions-Mesh (LP)"), + ("Edges", "Kanten"), + ("Cavities", "Vertiefungen"), + ("Edges and cavities", "Kanten und Vertiefungen"), + ("Raw curvature", "Rohe Krümmung"), + ("Detail sizes", "Detailgrößen"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Liest die Krümmungskarte wie gebacken: Eine Änderung des Modus oder einer Größe schaltet die Detailgrößen ein.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.", + ), + ("Fill mode", "Füllmodus"), + ("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"), + ("Hit-test", "Treffertest"), + ("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"), + ("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"), + ("Rectangle fill", "Rechteckfüllung"), + ("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"), + ("Selection mode", "Auswahlmodus"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln", + ), + ("Visible polygons only", "Nur sichtbare Polygone"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"), + ("The file dialog couldn't be shown: {error}", "Der Dateidialog konnte nicht angezeigt werden: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Das Projekt hat sich geändert, während der Dialog geöffnet war, daher wurde nichts ausgeführt", + ), ("Cores kept for the UI", "Für die Oberfläche reservierte Kerne"), ("Max RAM while saving", "Max. RAM beim Speichern"), ( diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 23cb6675..dbeefd44 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidad de AO"), ("About TextureCraft", "Acerca de TextureCraft"), ("About TextureCraft...", "Acerca de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Añadir una capa de relleno con esta imagen (o arrastrarla a la vista 3D para colocarla como calcomanía)", - ), - ("Add a fill layer using this pattern", "Añadir una capa de relleno con este patrón"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Añadir una capa de relleno con este material sobre la capa seleccionada (o arrastrarlo a la pila de capas)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "Añade un punto de anclaje a una capa inferior para usar su pila como máscara."), ("Add anchor point", "Añadir punto de anclaje"), ("Add as decal (view center)", "Añadir como calcomanía (centro de la vista)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Añadir pintura"), ("Add paint layer", "Añadir capa de pintura"), ("Add smart material from the shelf", "Añadir material inteligente desde la biblioteca"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Añadir la carpeta del material inteligente sobre la capa seleccionada (o arrastrarla a la pila de capas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Añadir este acabado a la rugosidad y la altura de la capa seleccionada (o arrastrarlo a una capa)", - ), ("Add to the layer content", "Añadir al contenido de la capa"), ("Add to the mask", "Añadir a la máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Añadir al contenido de la capa seleccionada, o a su máscara si está seleccionada (o arrastrarlo a una capa)", - ), ("Add white mask", "Añadir máscara blanca"), ("Adjustments", "Ajustes de imagen"), ( @@ -107,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Eje"), ("Back to painting", "Volver a pintar"), ("Backface culling", "Descarte de caras traseras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Hornea un mapa de ID (F8) para tomar colores de la malla."), ("Bake Mesh Maps", "Hornear mapas de malla"), ("Bake mesh maps", "Hornear mapas de malla"), ( @@ -126,7 +106,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normales curvadas"), ("Bevel", "Bisel"), ("Black", "Negro"), - ("Blend sharpness", "Nitidez de la mezcla"), ("Blending", "Fusión"), ("Blending mode of the displayed channel", "Modo de fusión del canal mostrado"), ("Blur", "Desenfoque"), @@ -143,6 +122,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrada: {mesh}"), ("Cage: {name}", "Jaula: {name}"), ("Camera", "Cámara"), + ("Colors", "Colores"), + ("Go to camera 1", "Ir a la cámara 1"), + ("Go to camera 2", "Ir a la cámara 2"), + ("Go to camera 3", "Ir a la cámara 3"), + ("Go to camera 4", "Ir a la cámara 4"), + ("Go to camera 5", "Ir a la cámara 5"), + ("Go to camera 6", "Ir a la cámara 6"), + ("Go to camera 7", "Ir a la cámara 7"), + ("Go to camera 8", "Ir a la cámara 8"), + ("Go to camera 9", "Ir a la cámara 9"), ("Camera settings", "Ajustes de cámara"), ("Cancel", "Cancelar"), ("Cancel the stroke", "Cancelar el trazo"), @@ -151,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canal"), ("Channel source: uniform value, procedural, image or anchor", "Origen del canal: valor uniforme, procedural, imagen o anclaje"), ("Channels", "Canales"), + ("Check for Updates...", "Buscar actualizaciones..."), ("Checker", "Damero"), ("Clamp", "Limitar"), ("Clear", "Borrar"), @@ -332,6 +322,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Relleno"), ("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"), ("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"), ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), @@ -580,6 +571,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbitar"), ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), ("Output directory", "Directorio de salida"), ("Output high", "Salida alta"), ("Output low", "Salida baja"), @@ -588,6 +580,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Superponer"), ("Overlay opacity", "Opacidad de superposición"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidad (TextureCraft)"), + ("Pick color", "Tomar color"), ("PNG image", "Imagen PNG"), ("Padding", "Margen"), ("Paint", "Pintar"), @@ -680,10 +673,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderizado con trazado de trayectorias"), ("Replace", "Reemplazar"), ("Replace Color", "Reemplazar color"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Reemplazar la máscara de la capa seleccionada por esta máscara inteligente (o arrastrarla a una capa)", - ), ("Replacement color", "Color de reemplazo"), ("Report a bug...", "Informar de un error..."), ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), @@ -720,6 +709,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arañazos"), ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), + ("Search", "Buscar"), ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), @@ -838,16 +828,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ con texturas"), ("UV checker", "Damero UV"), ("UV island fill", "Relleno de islas UV"), + ("UV transformations", "Transformaciones UV"), ("UV projection", "Proyección UV"), ("UV tiles", "Mosaicos UV"), ("UV tiles (UDIM)", "Mosaicos UV (UDIM)"), ("Undo", "Deshacer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar una imagen equirrectangular .hdr o .exr como entorno"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alfa del pincel (o arrastrarlo a la ventana gráfica o a las propiedades del pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa el canal de control o `texturecraft-cli render` para las capturas"), ("Value", "Valor"), ("Version {version}", "Versión {version}"), @@ -997,7 +984,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Promediar normales"), ("BBox", "Caja delimitadora"), ("BSphere", "Esfera delimitadora"), - ("Bake Maps", "Hornear mapas"), + ("Mesh Map Bakers", "Horneadores de mapas de malla"), + ("Common Settings", "Ajustes comunes"), + ("Mesh Map Settings", "Ajustes de mapas de malla"), + ("Check All", "Marcar todo"), + ("No Parameters", "Sin parámetros"), ("Bake Selected Textures ({n})", "Hornear texturas seleccionadas ({n})"), ("By Mesh Name", "Por nombre de malla"), ("Cage", "Jaula"), @@ -1075,6 +1066,60 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Remove resolution override", "Quitar resolución personalizada"), + ("Texture set resolution", "Resolución del conjunto de texturas"), + ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Baked maps imported: {count}", "Mapas horneados importados: {count}"), + ("Not imported: {files}", "Sin importar: {files}"), + ("Baking Visualization", "Visualización del horneado"), + ("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"), + ("High Definition Mesh (HP)", "Malla de alta resolución (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malla de proyección (LP)"), + ("Edges", "Bordes"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordes y cavidades"), + ("Raw curvature", "Curvatura sin procesar"), + ("Detail sizes", "Tamaños de detalle"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lee el mapa de curvatura tal como se horneó: cambiar el modo o un tamaño activa los tamaños de detalle.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.", + ), + ("Fill mode", "Modo de relleno"), + ("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"), + ("Hit-test", "Prueba de selección"), + ("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"), + ("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"), + ("Rectangle fill", "Relleno rectangular"), + ("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"), + ("Selection mode", "Modo de selección"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV", + ), + ("Visible polygons only", "Solo polígonos visibles"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa", + ), + ("The file dialog couldn't be shown: {error}", "No se pudo mostrar el cuadro de diálogo de archivos: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "El proyecto cambió mientras el cuadro de diálogo estaba abierto, así que no se hizo nada", + ), ("Cores kept for the UI", "Núcleos reservados para la interfaz"), ("Max RAM while saving", "RAM máx. al guardar"), ( diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index bd822836..a84c5e69 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensité de l'AO"), ("About TextureCraft", "À propos de TextureCraft"), ("About TextureCraft...", "À propos de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Ajouter un calque de remplissage avec cette image (ou la glisser sur la vue 3D pour la placer comme décalque)", - ), - ("Add a fill layer using this pattern", "Ajouter un calque de remplissage avec ce motif"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Ajouter un calque de remplissage avec ce matériau au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa pile comme masque.", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Ajouter de la peinture"), ("Add paint layer", "Ajouter un calque de peinture"), ("Add smart material from the shelf", "Ajouter un matériau intelligent depuis la bibliothèque"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Ajouter le dossier du matériau intelligent au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Ajouter cette finition à la rugosité et à la hauteur du calque sélectionné (ou la glisser sur un calque)", - ), ("Add to the layer content", "Ajouter au contenu du calque"), ("Add to the mask", "Ajouter au masque"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Ajouter au contenu du calque sélectionné, ou à son masque si le masque est sélectionné (ou le glisser sur un calque)", - ), ("Add white mask", "Ajouter un masque blanc"), ("Adjustments", "Réglages"), ( @@ -113,6 +92,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Axe"), ("Back to painting", "Retour à la peinture"), ("Backface culling", "Élimination des faces arrière"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Précalculez une carte d'ID (F8) pour prélever des couleurs sur le maillage."), ("Bake Mesh Maps", "Précalculer les cartes de maillage"), ("Bake mesh maps", "Précalculer les cartes de maillage"), ( @@ -132,7 +112,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normales déviées"), ("Bevel", "Biseau"), ("Black", "Noir"), - ("Blend sharpness", "Netteté du fondu"), ("Blending", "Fusion"), ("Blending mode of the displayed channel", "Mode de fusion du canal affiché"), ("Blur", "Flou"), @@ -149,6 +128,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Intégré : {mesh}"), ("Cage: {name}", "Cage : {name}"), ("Camera", "Caméra"), + ("Colors", "Couleurs"), + ("Go to camera 1", "Aller à la caméra 1"), + ("Go to camera 2", "Aller à la caméra 2"), + ("Go to camera 3", "Aller à la caméra 3"), + ("Go to camera 4", "Aller à la caméra 4"), + ("Go to camera 5", "Aller à la caméra 5"), + ("Go to camera 6", "Aller à la caméra 6"), + ("Go to camera 7", "Aller à la caméra 7"), + ("Go to camera 8", "Aller à la caméra 8"), + ("Go to camera 9", "Aller à la caméra 9"), ("Camera settings", "Paramètres de la caméra"), ("Cancel", "Annuler"), ("Cancel the stroke", "Annuler le trait"), @@ -157,6 +146,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canal"), ("Channel source: uniform value, procedural, image or anchor", "Source du canal : valeur uniforme, procédural, image ou ancrage"), ("Channels", "Canaux"), + ("Check for Updates...", "Rechercher des mises à jour..."), ("Checker", "Damier"), ("Clamp", "Limiter"), ("Clear", "Effacer"), @@ -344,6 +334,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Remplissage"), ("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"), ("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"), + ("Filter", "Filtre"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"), ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), @@ -595,6 +586,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbite"), ("Orthographic", "Orthographique"), + ("Perspective", "Perspective"), ("Output directory", "Dossier de sortie"), ("Output high", "Sortie haute"), ("Output low", "Sortie basse"), @@ -603,6 +595,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Incrustation"), ("Overlay opacity", "Opacité de superposition"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Métallique Rugosité (TextureCraft)"), + ("Pick color", "Prélever une couleur"), ("PNG image", "Image PNG"), ("Padding", "Marge"), ("Paint", "Peinture"), @@ -695,10 +688,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendu, tracé de chemins"), ("Replace", "Remplacer"), ("Replace Color", "Remplacer la couleur"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Remplacer le masque du calque sélectionné par ce masque intelligent (ou le glisser sur un calque)", - ), ("Replacement color", "Couleur de remplacement"), ("Report a bug...", "Signaler un bug..."), ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), @@ -738,6 +727,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Rayures"), ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), + ("Search", "Rechercher"), ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), @@ -856,16 +846,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ avec textures"), ("UV checker", "Damier UV"), ("UV island fill", "Remplissage d'îlots UV"), + ("UV transformations", "Transformations UV"), ("UV projection", "Projection UV"), ("UV tiles", "Tuiles UV"), ("UV tiles (UDIM)", "Tuiles UV (UDIM)"), ("Undo", "Annuler"), ("Uniform value", "Valeur uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Utiliser une image équirectangulaire .hdr ou .exr comme environnement"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Utiliser comme alpha du pinceau (ou le glisser sur la fenêtre d'affichage ou les propriétés du pinceau)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "Utilisez le canal de contrôle ou `texturecraft-cli render` pour les captures d'écran", @@ -1021,7 +1008,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Moyenne des normales"), ("BBox", "Boîte englobante"), ("BSphere", "Sphère englobante"), - ("Bake Maps", "Précalculer les cartes"), + ("Mesh Map Bakers", "Précalculateurs de cartes de maillage"), + ("Common Settings", "Paramètres communs"), + ("Mesh Map Settings", "Paramètres des cartes de maillage"), + ("Check All", "Tout cocher"), + ("No Parameters", "Aucun paramètre"), ("Bake Selected Textures ({n})", "Précalculer les textures sélectionnées ({n})"), ("By Mesh Name", "Par nom de maillage"), ("Cage", "Cage"), @@ -1099,6 +1090,60 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Remove resolution override", "Supprimer la résolution personnalisée"), + ("Texture set resolution", "Résolution de l'ensemble de textures"), + ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Baked maps imported: {count}", "Cartes précalculées importées : {count}"), + ("Not imported: {files}", "Non importés : {files}"), + ("Baking Visualization", "Visualisation du baking"), + ("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"), + ("High Definition Mesh (HP)", "Maillage haute définition (HP)"), + ("UV Seams", "Coutures UV"), + ("Project Mesh (LP)", "Maillage de projection (LP)"), + ("Edges", "Arêtes"), + ("Cavities", "Cavités"), + ("Edges and cavities", "Arêtes et cavités"), + ("Raw curvature", "Courbure brute"), + ("Detail sizes", "Tailles de détail"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lit la carte de courbure telle que calculée : changer le mode ou une taille active les tailles de détail.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.", + ), + ("Fill mode", "Mode de remplissage"), + ("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"), + ("Hit-test", "Test de sélection"), + ("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"), + ("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"), + ("Rectangle fill", "Remplissage rectangulaire"), + ("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"), + ("Selection mode", "Mode de sélection"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV", + ), + ("Visible polygons only", "Polygones visibles uniquement"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque", + ), + ("The file dialog couldn't be shown: {error}", "Impossible d'afficher la boîte de dialogue de fichiers : {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Le projet a changé pendant que la boîte de dialogue était ouverte ; rien n'a été fait", + ), ("Cores kept for the UI", "Cœurs réservés à l'interface"), ("Max RAM while saving", "RAM max. à l'enregistrement"), ( diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 319c78cd..93805080 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensità AO"), ("About TextureCraft", "Informazioni su TextureCraft"), ("About TextureCraft...", "Informazioni su TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Aggiungi un livello di riempimento con questa immagine (o trascinala nella vista 3D per posizionarla come decal)", - ), - ("Add a fill layer using this pattern", "Aggiungi un livello di riempimento con questo motivo"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Aggiungi un livello di riempimento con questo materiale sopra il livello selezionato (o trascinalo nella pila dei livelli)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Aggiungi un punto di ancoraggio a un livello sottostante per usarne la pila come maschera.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Aggiungi pittura"), ("Add paint layer", "Aggiungi livello di pittura"), ("Add smart material from the shelf", "Aggiungi un materiale intelligente dalla libreria"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Aggiungi la cartella del materiale intelligente sopra il livello selezionato (o trascinala nella pila dei livelli)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Aggiungi questa finitura alla rugosità e all'altezza del livello selezionato (o trascinala su un livello)", - ), ("Add to the layer content", "Aggiungi al contenuto del livello"), ("Add to the mask", "Aggiungi alla maschera"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Aggiungi al contenuto del livello selezionato, o alla sua maschera se è selezionata (o trascinalo su un livello)", - ), ("Add white mask", "Aggiungi maschera bianca"), ("Adjustments", "Regolazioni"), ( @@ -110,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Asse"), ("Back to painting", "Torna alla pittura"), ("Backface culling", "Culling facce posteriori"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Esegui il bake di una mappa ID (F8) per prelevare i colori dalla mesh."), ("Bake Mesh Maps", "Bake mappe mesh"), ("Bake mesh maps", "Bake mappe mesh"), ( @@ -129,7 +109,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Bent normal"), ("Bevel", "Smusso"), ("Black", "Nero"), - ("Blend sharpness", "Nitidezza della fusione"), ("Blending", "Fusione"), ("Blending mode of the displayed channel", "Metodo di fusione del canale visualizzato"), ("Blur", "Sfocatura"), @@ -146,6 +125,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrata: {mesh}"), ("Cage: {name}", "Gabbia: {name}"), ("Camera", "Camera"), + ("Colors", "Colori"), + ("Go to camera 1", "Vai alla camera 1"), + ("Go to camera 2", "Vai alla camera 2"), + ("Go to camera 3", "Vai alla camera 3"), + ("Go to camera 4", "Vai alla camera 4"), + ("Go to camera 5", "Vai alla camera 5"), + ("Go to camera 6", "Vai alla camera 6"), + ("Go to camera 7", "Vai alla camera 7"), + ("Go to camera 8", "Vai alla camera 8"), + ("Go to camera 9", "Vai alla camera 9"), ("Camera settings", "Impostazioni camera"), ("Cancel", "Annulla"), ("Cancel the stroke", "Annulla il tratto"), @@ -154,6 +143,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canale"), ("Channel source: uniform value, procedural, image or anchor", "Sorgente del canale: valore uniforme, procedurale, immagine o ancoraggio"), ("Channels", "Canali"), + ("Check for Updates...", "Controlla aggiornamenti..."), ("Checker", "Scacchiera"), ("Clamp", "Limita"), ("Clear", "Cancella"), @@ -338,6 +328,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Riempimento"), ("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"), ("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"), ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), @@ -586,6 +577,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbita"), ("Orthographic", "Ortografica"), + ("Perspective", "Prospettica"), ("Output directory", "Cartella di output"), ("Output high", "Output alto"), ("Output low", "Output basso"), @@ -594,6 +586,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Sovrapponi"), ("Overlay opacity", "Opacità sovrapposizione"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallico Rugosità (TextureCraft)"), + ("Pick color", "Preleva colore"), ("PNG image", "Immagine PNG"), ("Padding", "Padding"), ("Paint", "Pittura"), @@ -689,10 +682,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, path tracing"), ("Replace", "Sostituisci"), ("Replace Color", "Sostituisci colore"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Sostituisci la maschera del livello selezionato con questa maschera intelligente (o trascinala su un livello)", - ), ("Replacement color", "Colore sostitutivo"), ("Report a bug...", "Segnala un bug..."), ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), @@ -729,6 +718,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Graffi"), ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), + ("Search", "Cerca"), ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), @@ -847,16 +837,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ con texture"), ("UV checker", "Scacchiera UV"), ("UV island fill", "Riempimento isola UV"), + ("UV transformations", "Trasformazioni UV"), ("UV projection", "Proiezione UV"), ("UV tiles", "Tile UV"), ("UV tiles (UDIM)", "Tile UV (UDIM)"), ("Undo", "Annulla"), ("Uniform value", "Valore uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usa un'immagine equirettangolare .hdr o .exr come ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usa come alpha del pennello (o trascinala nella viewport o nelle proprietà del pennello)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa il canale di controllo o `texturecraft-cli render` per gli screenshot"), ("Value", "Valore"), ("Version {version}", "Versione {version}"), @@ -1006,7 +993,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normali medie"), ("BBox", "Riquadro di delimitazione"), ("BSphere", "Sfera di delimitazione"), - ("Bake Maps", "Bake delle mappe"), + ("Mesh Map Bakers", "Baker delle mappe mesh"), + ("Common Settings", "Impostazioni comuni"), + ("Mesh Map Settings", "Impostazioni mappe mesh"), + ("Check All", "Seleziona tutto"), + ("No Parameters", "Nessun parametro"), ("Bake Selected Textures ({n})", "Bake texture selezionate ({n})"), ("By Mesh Name", "Per nome della mesh"), ("Cage", "Gabbia"), @@ -1084,6 +1075,60 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Remove resolution override", "Rimuovi risoluzione personalizzata"), + ("Texture set resolution", "Risoluzione del set di texture"), + ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Baked maps imported: {count}", "Mappe bake importate: {count}"), + ("Not imported: {files}", "Non importati: {files}"), + ("Baking Visualization", "Visualizzazione del baking"), + ("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"), + ("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"), + ("UV Seams", "Cuciture UV"), + ("Project Mesh (LP)", "Mesh di proiezione (LP)"), + ("Edges", "Bordi"), + ("Cavities", "Cavità"), + ("Edges and cavities", "Bordi e cavità"), + ("Raw curvature", "Curvatura grezza"), + ("Detail sizes", "Dimensioni del dettaglio"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Legge la mappa di curvatura così come è stata calcolata: cambiare la modalità o una dimensione attiva le dimensioni del dettaglio.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.", + ), + ("Fill mode", "Modalità di riempimento"), + ("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"), + ("Hit-test", "Test di selezione"), + ("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"), + ("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"), + ("Rectangle fill", "Riempimento rettangolare"), + ("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"), + ("Selection mode", "Modalità di selezione"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV", + ), + ("Visible polygons only", "Solo poligoni visibili"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello", + ), + ("The file dialog couldn't be shown: {error}", "Impossibile mostrare la finestra di dialogo dei file: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Il progetto è cambiato mentre la finestra di dialogo era aperta, quindi non è stato fatto nulla", + ), ("Cores kept for the UI", "Core riservati all'interfaccia"), ("Max RAM while saving", "RAM max durante il salvataggio"), ( diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 43785df8..13643892 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO強度"), ("About TextureCraft", "TextureCraftについて"), ("About TextureCraft...", "TextureCraftについて..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "この画像で塗りつぶしレイヤーを追加 (3Dビューにドラッグするとデカールとして配置)", - ), - ("Add a fill layer using this pattern", "このパターンで塗りつぶしレイヤーを追加"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "このマテリアルの塗りつぶしレイヤーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "下のレイヤーにアンカーポイントを追加すると、そのスタックをマスクとして使用できます。", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "ペイントを追加"), ("Add paint layer", "ペイントレイヤーを追加"), ("Add smart material from the shelf", "シェルフからスマートマテリアルを追加"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "スマートマテリアルのフォルダーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "この仕上げを選択中のレイヤーのラフネスとハイトに追加 (レイヤーへのドラッグも可)", - ), ("Add to the layer content", "レイヤーのコンテンツに追加"), ("Add to the mask", "マスクに追加"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "選択中のレイヤーのコンテンツ (マスク選択時はマスク) に追加 (レイヤーへのドラッグも可)", - ), ("Add white mask", "白マスクを追加"), ("Adjustments", "色調補正"), ( @@ -113,6 +92,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "軸"), ("Back to painting", "ペイントに戻る"), ("Backface culling", "背面カリング"), + ("Bake an ID map (F8) to pick colors from the mesh.", "メッシュから色を拾うには ID マップをベイクしてください (F8)。"), ("Bake Mesh Maps", "メッシュマップのベイク"), ("Bake mesh maps", "メッシュマップをベイク"), ( @@ -132,7 +112,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "ベントノーマル"), ("Bevel", "ベベル"), ("Black", "黒"), - ("Blend sharpness", "ブレンドのシャープさ"), ("Blending", "ブレンド"), ("Blending mode of the displayed channel", "表示中のチャンネルのブレンドモード"), ("Blur", "ぼかし"), @@ -149,6 +128,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "組み込み: {mesh}"), ("Cage: {name}", "ケージ: {name}"), ("Camera", "カメラ"), + ("Colors", "カラー"), + ("Go to camera 1", "カメラ 1 に移動"), + ("Go to camera 2", "カメラ 2 に移動"), + ("Go to camera 3", "カメラ 3 に移動"), + ("Go to camera 4", "カメラ 4 に移動"), + ("Go to camera 5", "カメラ 5 に移動"), + ("Go to camera 6", "カメラ 6 に移動"), + ("Go to camera 7", "カメラ 7 に移動"), + ("Go to camera 8", "カメラ 8 に移動"), + ("Go to camera 9", "カメラ 9 に移動"), ("Camera settings", "カメラ設定"), ("Cancel", "キャンセル"), ("Cancel the stroke", "ストロークをキャンセル"), @@ -157,6 +146,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "チャンネル"), ("Channel source: uniform value, procedural, image or anchor", "チャンネルのソース: 均一値、プロシージャル、画像、アンカー"), ("Channels", "チャンネル"), + ("Check for Updates...", "アップデートを確認..."), ("Checker", "チェッカー"), ("Clamp", "クランプ"), ("Clear", "クリア"), @@ -329,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "塗りつぶし"), ("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"), ("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"), + ("Filter", "フィルター"), ("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"), ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), @@ -574,6 +565,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "オービット"), ("Orthographic", "平行投影"), + ("Perspective", "透視投影"), ("Output directory", "出力先フォルダー"), ("Output high", "出力の上限"), ("Output low", "出力の下限"), @@ -582,6 +574,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "オーバーレイ"), ("Overlay opacity", "オーバーレイの不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - メタリック/ラフネス (TextureCraft)"), + ("Pick color", "色を拾う"), ("PNG image", "PNG画像"), ("Padding", "パディング"), ("Paint", "ペイント"), @@ -671,10 +664,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "パストレースによるレンダリング"), ("Replace", "置換"), ("Replace Color", "色の置き換え"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "選択中のレイヤーのマスクをこのスマートマスクで置換 (レイヤーへのドラッグも可)", - ), ("Replacement color", "置き換え後の色"), ("Report a bug...", "バグを報告..."), ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), @@ -711,6 +700,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "引っかき傷"), ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), + ("Search", "検索"), ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), @@ -829,16 +819,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ (テクスチャ付き)"), ("UV checker", "UVチェッカー"), ("UV island fill", "UVアイランド塗りつぶし"), + ("UV transformations", "UV変換"), ("UV projection", "UV投影"), ("UV tiles", "UVタイル"), ("UV tiles (UDIM)", "UVタイル (UDIM)"), ("Undo", "元に戻す"), ("Uniform value", "均一値"), ("Use an equirectangular .hdr or .exr image as the environment", "正距円筒図法の .hdr または .exr 画像を環境として使用"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "ブラシのアルファとして使用 (ビューポートやブラシプロパティへのドラッグも可)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", @@ -991,7 +978,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "法線を平均化"), ("BBox", "バウンディングボックス"), ("BSphere", "バウンディングスフィア"), - ("Bake Maps", "マップをベイク"), + ("Mesh Map Bakers", "メッシュマップベイカー"), + ("Common Settings", "共通設定"), + ("Mesh Map Settings", "メッシュマップ設定"), + ("Check All", "すべてチェック"), + ("No Parameters", "パラメーターなし"), ("Bake Selected Textures ({n})", "選択したテクスチャをベイク ({n})"), ("By Mesh Name", "メッシュ名で"), ("Cage", "ケージ"), @@ -1069,6 +1060,57 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Remove resolution override", "解像度の上書きを解除"), + ("Texture set resolution", "テクスチャセットの解像度"), + ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), + ("Baking Visualization", "ベイクの可視化"), + ("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"), + ("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"), + ("UV Seams", "UVシーム"), + ("Project Mesh (LP)", "投影メッシュ (LP)"), + ("Edges", "エッジ"), + ("Cavities", "くぼみ"), + ("Edges and cavities", "エッジとくぼみ"), + ("Raw curvature", "生の曲率"), + ("Detail sizes", "ディテールサイズ"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "曲率マップをベイクされたまま読み取ります。モードやサイズを変更するとディテールサイズが有効になります。", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします", + ), + ("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。", + ), + ("Fill mode", "塗りつぶしモード"), + ("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"), + ("Hit-test", "ヒットテスト"), + ("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"), + ("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"), + ("Rectangle fill", "矩形塗りつぶし"), + ("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"), + ("Selection mode", "選択モード"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします", + ), + ("Visible polygons only", "表示されているポリゴンのみ"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください", + ), + ("The file dialog couldn't be shown: {error}", "ファイルダイアログを表示できませんでした: {error}"), + ("The project changed while the dialog was open, so nothing was done", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"), ("Cores kept for the UI", "UI用に確保するコア数"), ("Max RAM while saving", "保存時のRAM上限"), ( diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 617838b0..f8bfba64 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 강도"), ("About TextureCraft", "TextureCraft 정보"), ("About TextureCraft...", "TextureCraft 정보..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "이 이미지로 채우기 레이어를 추가합니다 (또는 3D 뷰로 드래그하여 데칼로 배치)", - ), - ("Add a fill layer using this pattern", "이 패턴으로 채우기 레이어를 추가합니다"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 이 머티리얼로 채우기 레이어를 추가합니다 (또는 레이어 스택으로 드래그)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "아래 레이어에 앵커 포인트를 추가하면 해당 스택을 마스크로 사용할 수 있습니다."), ("Add anchor point", "앵커 포인트 추가"), ("Add as decal (view center)", "데칼로 추가 (뷰 중앙)"), @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "페인트 추가"), ("Add paint layer", "페인트 레이어 추가"), ("Add smart material from the shelf", "셸프에서 스마트 머티리얼 추가"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 스마트 머티리얼 폴더를 추가합니다 (또는 레이어 스택으로 드래그)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "선택한 레이어의 러프니스와 높이에 이 마감을 추가합니다 (또는 레이어로 드래그)", - ), ("Add to the layer content", "레이어 콘텐츠에 추가"), ("Add to the mask", "마스크에 추가"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "선택한 레이어의 콘텐츠에 추가하거나, 마스크가 선택된 경우 마스크에 추가합니다 (또는 레이어로 드래그)", - ), ("Add white mask", "흰색 마스크 추가"), ("Adjustments", "조정"), ( @@ -110,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "축"), ("Back to painting", "페인팅으로 돌아가기"), ("Backface culling", "후면 컬링"), + ("Bake an ID map (F8) to pick colors from the mesh.", "메시에서 색을 고르려면 ID 맵을 베이크하세요 (F8)."), ("Bake Mesh Maps", "메시 맵 베이크"), ("Bake mesh maps", "메시 맵 베이크"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "곡률, AO, 두께 기반 제너레이터를 사용하려면 메시 맵을 베이크하세요 (F8)."), @@ -126,7 +106,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "벤트 노멀"), ("Bevel", "베벨"), ("Black", "검은색"), - ("Blend sharpness", "블렌드 선명도"), ("Blending", "블렌딩"), ("Blending mode of the displayed channel", "표시된 채널의 블렌딩 모드"), ("Blur", "블러"), @@ -143,6 +122,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "기본 제공: {mesh}"), ("Cage: {name}", "케이지: {name}"), ("Camera", "카메라"), + ("Colors", "색상"), + ("Go to camera 1", "카메라 1 보기"), + ("Go to camera 2", "카메라 2 보기"), + ("Go to camera 3", "카메라 3 보기"), + ("Go to camera 4", "카메라 4 보기"), + ("Go to camera 5", "카메라 5 보기"), + ("Go to camera 6", "카메라 6 보기"), + ("Go to camera 7", "카메라 7 보기"), + ("Go to camera 8", "카메라 8 보기"), + ("Go to camera 9", "카메라 9 보기"), ("Camera settings", "카메라 설정"), ("Cancel", "취소"), ("Cancel the stroke", "스트로크 취소"), @@ -151,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "채널"), ("Channel source: uniform value, procedural, image or anchor", "채널 소스: 균일 값, 프로시저럴, 이미지 또는 앵커"), ("Channels", "채널"), + ("Check for Updates...", "업데이트 확인..."), ("Checker", "체커"), ("Clamp", "클램프"), ("Clear", "지우기"), @@ -326,6 +316,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "채우기"), ("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"), ("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"), + ("Filter", "필터"), ("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"), ("Filters", "필터"), ("Fine noise", "미세 노이즈"), @@ -565,6 +556,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "궤도 회전"), ("Orthographic", "직교"), + ("Perspective", "원근"), ("Output directory", "출력 디렉터리"), ("Output high", "출력 상한"), ("Output low", "출력 하한"), @@ -573,6 +565,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "오버레이"), ("Overlay opacity", "오버레이 불투명도"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 메탈릭 러프니스 (TextureCraft)"), + ("Pick color", "색 고르기"), ("PNG image", "PNG 이미지"), ("Padding", "패딩"), ("Paint", "페인트"), @@ -662,10 +655,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "렌더링, 패스 트레이싱"), ("Replace", "대체"), ("Replace Color", "색상 바꾸기"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "선택한 레이어의 마스크를 이 스마트 마스크로 대체합니다 (또는 레이어로 드래그)", - ), ("Replacement color", "대체 색상"), ("Report a bug...", "버그 신고..."), ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), @@ -702,6 +691,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "스크래치"), ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), + ("Search", "검색"), ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), @@ -820,13 +810,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "텍스처 포함 USDZ"), ("UV checker", "UV 체커"), ("UV island fill", "UV 아일랜드 채우기"), + ("UV transformations", "UV 변환"), ("UV projection", "UV 투영"), ("UV tiles", "UV 타일"), ("UV tiles (UDIM)", "UV 타일 (UDIM)"), ("Undo", "실행 취소"), ("Uniform value", "균일 값"), ("Use an equirectangular .hdr or .exr image as the environment", "등장방형 .hdr 또는 .exr 이미지를 환경으로 사용합니다"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "브러시 알파로 사용합니다 (또는 뷰포트나 브러시 속성으로 드래그)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), ("Value", "값"), ("Version {version}", "버전 {version}"), @@ -976,7 +966,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "노멀 평균화"), ("BBox", "경계 상자"), ("BSphere", "경계 구"), - ("Bake Maps", "맵 베이크"), + ("Mesh Map Bakers", "메시 맵 베이커"), + ("Common Settings", "공통 설정"), + ("Mesh Map Settings", "메시 맵 설정"), + ("Check All", "모두 선택"), + ("No Parameters", "매개변수 없음"), ("Bake Selected Textures ({n})", "선택한 텍스처 베이크 ({n})"), ("By Mesh Name", "메시 이름으로"), ("Cage", "케이지"), @@ -1054,6 +1048,54 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Remove resolution override", "해상도 재정의 제거"), + ("Texture set resolution", "텍스처 세트 해상도"), + ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"), + ("Not imported: {files}", "가져오지 않음: {files}"), + ("Baking Visualization", "베이크 시각화"), + ("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"), + ("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"), + ("UV Seams", "UV 심"), + ("Project Mesh (LP)", "투영 메시 (LP)"), + ("Edges", "가장자리"), + ("Cavities", "오목한 부분"), + ("Edges and cavities", "가장자리와 오목한 부분"), + ("Raw curvature", "원시 곡률"), + ("Detail sizes", "디테일 크기"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "곡률 맵을 베이크된 그대로 읽습니다. 모드나 크기를 바꾸면 디테일 크기가 켜집니다.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다", + ), + ("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.", + ), + ("Fill mode", "채우기 모드"), + ("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"), + ("Hit-test", "히트 테스트"), + ("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"), + ("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"), + ("Rectangle fill", "사각형 채우기"), + ("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"), + ("Selection mode", "선택 모드"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다", + ), + ("Visible polygons only", "보이는 폴리곤만"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), + ("The file dialog couldn't be shown: {error}", "파일 대화 상자를 표시할 수 없습니다: {error}"), + ("The project changed while the dialog was open, so nothing was done", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"), ("Cores kept for the UI", "UI용으로 남겨 둘 코어"), ("Max RAM while saving", "저장 시 최대 RAM"), ( diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 4e35f4f9..2c724c07 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidade de AO"), ("About TextureCraft", "Sobre o TextureCraft"), ("About TextureCraft...", "Sobre o TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Adicionar uma camada de preenchimento com esta imagem (ou arraste-a para a vista 3D para posicioná-la como decalque)", - ), - ("Add a fill layer using this pattern", "Adicionar uma camada de preenchimento com este padrão"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Adicionar uma camada de preenchimento com este material acima da camada selecionada (ou arraste-o para a pilha de camadas)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Adicione um ponto de ancoragem a uma camada abaixo para usar sua pilha como máscara.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Adicionar pintura"), ("Add paint layer", "Adicionar camada de pintura"), ("Add smart material from the shelf", "Adicionar material inteligente da prateleira"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Adicionar a pasta do material inteligente acima da camada selecionada (ou arraste-a para a pilha de camadas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Adicionar este acabamento à rugosidade e à altura da camada selecionada (ou arraste-o para uma camada)", - ), ("Add to the layer content", "Adicionar ao conteúdo da camada"), ("Add to the mask", "Adicionar à máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Adicionar ao conteúdo da camada selecionada, ou à sua máscara quando a máscara estiver selecionada (ou arraste-o para uma camada)", - ), ("Add white mask", "Adicionar máscara branca"), ("Adjustments", "Ajustes"), ( @@ -110,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Eixo"), ("Back to painting", "Voltar à pintura"), ("Backface culling", "Descarte de faces traseiras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Faça o bake de um mapa de ID (F8) para coletar cores da malha."), ("Bake Mesh Maps", "Bake de mapas de malha"), ("Bake mesh maps", "Fazer bake dos mapas de malha"), ( @@ -129,7 +109,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normais curvadas"), ("Bevel", "Chanfro"), ("Black", "Preto"), - ("Blend sharpness", "Nitidez da mistura"), ("Blending", "Mesclagem"), ("Blending mode of the displayed channel", "Modo de mesclagem do canal exibido"), ("Blur", "Desfoque"), @@ -146,6 +125,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Embutida: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Câmera"), + ("Colors", "Cores"), + ("Go to camera 1", "Ir para a câmera 1"), + ("Go to camera 2", "Ir para a câmera 2"), + ("Go to camera 3", "Ir para a câmera 3"), + ("Go to camera 4", "Ir para a câmera 4"), + ("Go to camera 5", "Ir para a câmera 5"), + ("Go to camera 6", "Ir para a câmera 6"), + ("Go to camera 7", "Ir para a câmera 7"), + ("Go to camera 8", "Ir para a câmera 8"), + ("Go to camera 9", "Ir para a câmera 9"), ("Camera settings", "Configurações da câmera"), ("Cancel", "Cancelar"), ("Cancel the stroke", "Cancelar o traço"), @@ -154,6 +143,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canal"), ("Channel source: uniform value, procedural, image or anchor", "Origem do canal: valor uniforme, procedural, imagem ou âncora"), ("Channels", "Canais"), + ("Check for Updates...", "Verificar atualizações..."), ("Checker", "Xadrez"), ("Clamp", "Limitar"), ("Clear", "Limpar"), @@ -332,6 +322,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Preenchimento"), ("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"), ("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"), ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), @@ -577,6 +568,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbitar"), ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), ("Output directory", "Pasta de saída"), ("Output high", "Saída alta"), ("Output low", "Saída baixa"), @@ -585,6 +577,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Sobrepor"), ("Overlay opacity", "Opacidade da sobreposição"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidade (TextureCraft)"), + ("Pick color", "Coletar cor"), ("PNG image", "Imagem PNG"), ("Padding", "Margem"), ("Paint", "Pintura"), @@ -677,10 +670,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderização com path tracing"), ("Replace", "Substituir"), ("Replace Color", "Substituir cor"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Substituir a máscara da camada selecionada por esta máscara inteligente (ou arraste-a para uma camada)", - ), ("Replacement color", "Cor de substituição"), ("Report a bug...", "Relatar um bug..."), ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), @@ -717,6 +706,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arranhões"), ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), + ("Search", "Pesquisar"), ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), @@ -835,16 +825,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ com texturas"), ("UV checker", "Xadrez UV"), ("UV island fill", "Preenchimento de ilhas UV"), + ("UV transformations", "Transformações UV"), ("UV projection", "Projeção UV"), ("UV tiles", "Tiles UV"), ("UV tiles (UDIM)", "Tiles UV (UDIM)"), ("Undo", "Desfazer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar uma imagem equirretangular .hdr ou .exr como ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alpha do pincel (ou arraste-o para a viewport ou para as propriedades do pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Use o canal de controle ou `texturecraft-cli render` para capturas de tela"), ("Value", "Valor"), ("Version {version}", "Versão {version}"), @@ -994,7 +981,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normais médias"), ("BBox", "Caixa delimitadora"), ("BSphere", "Esfera delimitadora"), - ("Bake Maps", "Bake de mapas"), + ("Mesh Map Bakers", "Bakers de mapas de malha"), + ("Common Settings", "Configurações comuns"), + ("Mesh Map Settings", "Configurações de mapas de malha"), + ("Check All", "Marcar todos"), + ("No Parameters", "Sem parâmetros"), ("Bake Selected Textures ({n})", "Fazer bake das texturas selecionadas ({n})"), ("By Mesh Name", "Por nome da malha"), ("Cage", "Gaiola"), @@ -1072,6 +1063,57 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Remove resolution override", "Remover resolução personalizada"), + ("Texture set resolution", "Resolução do conjunto de texturas"), + ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Baked maps imported: {count}", "Mapas com bake importados: {count}"), + ("Not imported: {files}", "Não importados: {files}"), + ("Baking Visualization", "Visualização do bake"), + ("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"), + ("High Definition Mesh (HP)", "Malha de alta resolução (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malha de projeção (LP)"), + ("Edges", "Bordas"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordas e cavidades"), + ("Raw curvature", "Curvatura bruta"), + ("Detail sizes", "Tamanhos de detalhe"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lê o mapa de curvatura como foi assado: mudar o modo ou um tamanho ativa os tamanhos de detalhe.", + ), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.", + ), + ("Fill mode", "Modo de preenchimento"), + ("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"), + ("Hit-test", "Teste de seleção"), + ("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"), + ("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"), + ("Rectangle fill", "Preenchimento retangular"), + ("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"), + ("Selection mode", "Modo de seleção"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV", + ), + ("Visible polygons only", "Apenas polígonos visíveis"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada", + ), + ("The file dialog couldn't be shown: {error}", "Não foi possível mostrar a caixa de diálogo de arquivos: {error}"), + ("The project changed while the dialog was open, so nothing was done", "O projeto mudou enquanto a caixa de diálogo estava aberta, então nada foi feito"), ("Cores kept for the UI", "Núcleos reservados para a interface"), ("Max RAM while saving", "RAM máx. ao salvar"), ( diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 5677d139..391e2b9b 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -19,12 +19,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 强度"), ("About TextureCraft", "关于 TextureCraft"), ("About TextureCraft...", "关于 TextureCraft..."), - ("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", "使用此图像添加填充图层(或将其拖到 3D 视图中作为贴花放置)"), - ("Add a fill layer using this pattern", "使用此图案添加填充图层"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "在所选图层上方添加使用此材质的填充图层(或将其拖入图层堆栈)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "在下方图层上添加锚点,以将其堆栈用作遮罩。"), ("Add anchor point", "添加锚点"), ("Add as decal (view center)", "添加为贴花(视图中心)"), @@ -45,14 +39,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "添加绘画"), ("Add paint layer", "添加绘画图层"), ("Add smart material from the shelf", "从资产架添加智能材质"), - ("Add the smart material folder above the selected layer (or drag it into the layer stack)", "在所选图层上方添加智能材质文件夹(或将其拖入图层堆栈)"), - ("Add this finish to the selected layer's roughness and height (or drag it onto a layer)", "将此表面处理添加到所选图层的粗糙度和高度(或将其拖到图层上)"), ("Add to the layer content", "添加到图层内容"), ("Add to the mask", "添加到遮罩"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "添加到所选图层的内容,选中遮罩时则添加到遮罩(或将其拖到图层上)", - ), ("Add white mask", "添加白色遮罩"), ("Adjustments", "调整"), ("Aligned: the offset set by the first stroke is kept. V + click sets a new source.", "对齐:保留第一笔设定的偏移。按住 V 并单击可设置新的源。"), @@ -92,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "轴"), ("Back to painting", "返回绘画"), ("Backface culling", "背面剔除"), + ("Bake an ID map (F8) to pick colors from the mesh.", "烘焙 ID 贴图(F8)以从网格上拾取颜色。"), ("Bake Mesh Maps", "烘焙网格贴图"), ("Bake mesh maps", "烘焙网格贴图"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "烘焙网格贴图(F8)以用于基于曲率、AO 和厚度的生成器。"), @@ -108,7 +97,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "弯曲法线"), ("Bevel", "斜角"), ("Black", "黑色"), - ("Blend sharpness", "混合锐度"), ("Blending", "混合"), ("Blending mode of the displayed channel", "所显示通道的混合模式"), ("Blur", "模糊"), @@ -125,6 +113,16 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "内置:{mesh}"), ("Cage: {name}", "笼体:{name}"), ("Camera", "相机"), + ("Colors", "颜色"), + ("Go to camera 1", "转到相机 1"), + ("Go to camera 2", "转到相机 2"), + ("Go to camera 3", "转到相机 3"), + ("Go to camera 4", "转到相机 4"), + ("Go to camera 5", "转到相机 5"), + ("Go to camera 6", "转到相机 6"), + ("Go to camera 7", "转到相机 7"), + ("Go to camera 8", "转到相机 8"), + ("Go to camera 9", "转到相机 9"), ("Camera settings", "相机设置"), ("Cancel", "取消"), ("Cancel the stroke", "取消笔画"), @@ -133,6 +131,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "通道"), ("Channel source: uniform value, procedural, image or anchor", "通道来源:统一值、程序纹理、图像或锚点"), ("Channels", "通道"), + ("Check for Updates...", "检查更新..."), ("Checker", "棋盘格"), ("Clamp", "钳制"), ("Clear", "清除"), @@ -290,6 +289,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "填充"), ("Fill the closed path (lasso)", "填充闭合路径(套索)"), ("Fill the path (close it first)", "填充路径(请先闭合)"), + ("Filter", "滤镜"), ("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"), ("Filters", "滤镜"), ("Fine noise", "细噪波"), @@ -520,6 +520,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "环绕"), ("Orthographic", "正交"), + ("Perspective", "透视"), ("Output directory", "输出目录"), ("Output high", "输出高"), ("Output low", "输出低"), @@ -528,6 +529,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "叠加"), ("Overlay opacity", "叠加层不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 金属度/粗糙度(TextureCraft)"), + ("Pick color", "拾取颜色"), ("PNG image", "PNG 图像"), ("Padding", "扩边"), ("Paint", "绘画"), @@ -614,7 +616,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "渲染,路径追踪"), ("Replace", "替换"), ("Replace Color", "替换颜色"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "用此智能遮罩替换所选图层的遮罩(或将其拖到图层上)"), ("Replacement color", "替换后的颜色"), ("Report a bug...", "报告错误..."), ("Rescan the library folder", "重新扫描库文件夹"), @@ -651,6 +652,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "划痕"), ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), + ("Search", "搜索"), ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), @@ -769,13 +771,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "带纹理的 USDZ"), ("UV checker", "UV 棋盘格"), ("UV island fill", "UV 岛填充"), + ("UV transformations", "UV 变换"), ("UV projection", "UV 投影"), ("UV tiles", "UV 图块"), ("UV tiles (UDIM)", "UV 图块(UDIM)"), ("Undo", "撤销"), ("Uniform value", "统一值"), ("Use an equirectangular .hdr or .exr image as the environment", "使用等距柱状投影的 .hdr 或 .exr 图像作为环境"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "用作笔刷 Alpha(或将其拖到视口或笔刷属性上)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), ("Value", "值"), ("Version {version}", "版本 {version}"), @@ -922,7 +924,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "平均法线"), ("BBox", "包围盒"), ("BSphere", "包围球"), - ("Bake Maps", "烘焙贴图"), + ("Mesh Map Bakers", "网格贴图烘焙器"), + ("Common Settings", "通用设置"), + ("Mesh Map Settings", "网格贴图设置"), + ("Check All", "全选"), + ("No Parameters", "无参数"), ("Bake Selected Textures ({n})", "烘焙所选纹理({n})"), ("By Mesh Name", "按网格名称"), ("Cage", "笼形"), @@ -1000,6 +1006,45 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Remove resolution override", "移除分辨率覆盖"), + ("Texture set resolution", "纹理集分辨率"), + ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"), + ("Not imported: {files}", "未导入:{files}"), + ("Baking Visualization", "烘焙可视化"), + ("Show for Selected Texture Set Only", "仅显示所选纹理集"), + ("High Definition Mesh (HP)", "高模网格 (HP)"), + ("UV Seams", "UV 接缝"), + ("Project Mesh (LP)", "投射网格 (LP)"), + ("Edges", "边缘"), + ("Cavities", "凹陷"), + ("Edges and cavities", "边缘和凹陷"), + ("Raw curvature", "原始曲率"), + ("Detail sizes", "细节尺寸"), + ("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", "按烘焙原样读取曲率贴图:更改模式或尺寸会启用细节尺寸。"), + ("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"), + ("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"), + ("Fill mode", "填充模式"), + ("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"), + ("Hit-test", "命中测试"), + ("How a rectangle selects polygons", "矩形选择多边形的方式"), + ("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"), + ("Rectangle fill", "矩形填充"), + ("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"), + ("Selection mode", "选择模式"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛", + ), + ("Visible polygons only", "仅可见多边形"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), + ("The file dialog couldn't be shown: {error}", "无法显示文件对话框:{error}"), + ("The project changed while the dialog was open, so nothing was done", "对话框打开期间项目已更改,因此未执行任何操作"), ("Cores kept for the UI", "为界面保留的核心数"), ("Max RAM while saving", "保存时的最大内存"), ( diff --git a/crates/ui-egui/src/id_color_pick.rs b/crates/ui-egui/src/id_color_pick.rs new file mode 100644 index 00000000..c4e99a65 --- /dev/null +++ b/crates/ui-egui/src/id_color_pick.rs @@ -0,0 +1,92 @@ +//! Pick mode of a color selection: the next click in the 3D or 2D view adds the ID color under it + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::{StackTarget, ViewMode}; + +use crate::TextureCraftApp; +use crate::state::Mode; + +/// Height in points of the eyedropper drawn as the pointer while picking +const EYEDROPPER_SIZE: f32 = 20.0; + +/// A color selection waiting for a click, and the view to return to once it comes +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct IdColorPick { + pub effect: LayerId, + /// The color the click replaces; None adds one + pub index: Option, + previous_view: ViewMode, +} + +impl IdColorPick { + /// Waits for a click that picks into `effect`, showing the ID map meanwhile + pub fn start(app: &mut TextureCraftApp, effect: LayerId, index: Option) { + let previous_view = match app.picking_id_color.take() { + Some(running) => running.previous_view, + None => app.session.view, + }; + + app.properties_popup = None; + app.picking_id_color = Some(IdColorPick { effect, index, previous_view }); + app.run("viewport.view", json!({"mode": format!("map:{}", BakedMap::Id.id())})); + } + + /// Leaves pick mode, returning to the earlier view unless the user chose another meanwhile + pub fn end(app: &mut TextureCraftApp) { + let Some(pick) = app.picking_id_color.take() else { return }; + + if app.session.view == ViewMode::MeshMap(BakedMap::Id) { + app.run("viewport.view", view_params(pick.previous_view)); + } + } + + /// Picks at `point` (`x`/`y`/`viewport` or `uv` params) and leaves pick mode + pub fn pick_at(app: &mut TextureCraftApp, point: Value) { + let Some(pick) = app.picking_id_color else { return }; + + let mut params = json!({"effect": pick.effect.0, "index": pick.index}); + if let (Some(target), Some(source)) = (params.as_object_mut(), point.as_object()) { + target.extend(source.clone()); + } + + app.run("effect.colorSelection.pick", params); + IdColorPick::end(app); + } + + /// An eyedropper in place of the pointer while it is over `rect`, its tip on the hotspot + pub fn draw_cursor(ui: &egui::Ui, rect: egui::Rect) { + let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pointer| rect.contains(*pointer)) else { return }; + + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + + // The glyph's tip is its bottom-left corner; a dark outline keeps it readable on any ID color + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("id_color_pick_cursor"))); + let font = egui::FontId::proportional(EYEDROPPER_SIZE); + let glyph = egui_phosphor::regular::EYEDROPPER; + for offset in [egui::vec2(-1.0, 0.0), egui::vec2(1.0, 0.0), egui::vec2(0.0, -1.0), egui::vec2(0.0, 1.0)] { + painter.text(pointer + offset, egui::Align2::LEFT_BOTTOM, glyph, font.clone(), egui::Color32::from_black_alpha(220)); + } + painter.text(pointer, egui::Align2::LEFT_BOTTOM, glyph, font, egui::Color32::WHITE); + } + + /// Ends pick mode once its effect is no longer selected or painting mode is left + pub fn end_when_stale(app: &mut TextureCraftApp) { + let Some(pick) = app.picking_id_color else { return }; + + if app.session.target != StackTarget::Effect(pick.effect) || app.ui.mode != Mode::Painting { + IdColorPick::end(app); + } + } +} + +/// The `viewport.view` params that show `view` +fn view_params(view: ViewMode) -> Value { + match view { + ViewMode::Material => json!({"mode": "material"}), + ViewMode::Channel(channel) => json!({"mode": channel.id()}), + ViewMode::MeshMap(map) => json!({"mode": format!("map:{}", map.id())}), + ViewMode::UvChecker => json!({"mode": "uvChecker"}), + ViewMode::Mask(layer) => json!({"mode": "mask", "layer": layer.0}), + } +} diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 32b61242..6129dbc7 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -4,12 +4,14 @@ use std::collections::BTreeMap; +use craft_keymap::egui::Dispatcher; +use craft_keymap::{Active, Bindable, Chord, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes}; use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2}; use egui_phosphor::regular as ic; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; -use crate::menus::{CATALOG, parse_shortcut}; +use crate::menus::CATALOG; use crate::theme::Tokens; use crate::widgets::{icon_button, section}; @@ -64,7 +66,18 @@ pub fn tip(keymap: &Keymap, label: &str, id: &str) -> String { } } -/// "Ctrl+Shift+E" notation (the inverse of `menus::parse_shortcut`). +/// craft-keymap's text of a shortcut: "Ctrl" here is the command modifier (Cmd on macOS), which the +/// crate writes "Cmd". +fn crate_text(text: &str) -> String { + text.split('+').map(|part| if part == "Ctrl" { "Cmd" } else { part }).collect::>().join("+") +} + +/// Read "Ctrl+Shift+E" notation. +pub fn parse(text: &str) -> Option { + Chord::parse(&crate_text(text)).ok() +} + +/// "Ctrl+Shift+E" notation (the inverse of [`parse`]). pub fn format_shortcut(sc: &KeyboardShortcut) -> String { let m = sc.modifiers; let mut s = String::new(); @@ -81,27 +94,118 @@ pub fn format_shortcut(sc: &KeyboardShortcut) -> String { s } -fn modifier_count(m: Modifiers) -> u8 { - u8::from(m.command || m.ctrl || m.mac_cmd) + u8::from(m.shift) + u8::from(m.alt) +/// Every bound shortcut as egui's shortcut type. +fn active(keymap: &Keymap) -> Vec { + bindings().iter().filter_map(|b| Some(parse(shortcut(keymap, b)?)?.to_egui_shortcut())).collect() } -/// Every bound shortcut with its item id, most modifiers first: egui ignores extra Shift and -/// Alt when matching, so Shift+C has to be tried before C. -pub fn active(keymap: &Keymap) -> Vec<(&'static str, KeyboardShortcut)> { - let mut v: Vec<(&'static str, KeyboardShortcut)> = bindings().iter().filter_map(|b| Some((b.id, parse_shortcut(shortcut(keymap, b)?)?))).collect(); - v.sort_by_key(|(_, sc)| std::cmp::Reverse(modifier_count(sc.modifiers))); - v +/// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared +/// shortcut. +fn catalog() -> Vec { + bindings() + .iter() + .map(|b| { + let item = Bindable::new(b.id, b.label, Scope::app()); + match b.default.and_then(parse) { + Some(chord) => item.with_default(craft_keymap::Binding::new(chord)), + None => item, + } + }) + .collect() } -/// Each binding's parsed shortcut, in `bindings()` order. -pub fn resolve(keymap: &Keymap) -> Vec> { - bindings().iter().map(|b| shortcut(keymap, b).and_then(parse_shortcut)).collect() +/// craft-keymap's text of a stored shortcut. A symbol that needs Shift is looked up without it, so +/// "Shift+Colon" is ":". +fn override_text(text: &str) -> String { + match parse(text) { + Some(chord) => Layout::new().resolve(&KeyInput::new(chord.mods).with_typed(chord.key)).unwrap_or(chord).to_string(), + None => crate_text(text), + } } -/// Another binding with the same shortcut as binding `i`. -pub fn conflict(resolved: &[Option], i: usize) -> Option { - let sc = resolved.get(i).copied().flatten()?; - resolved.iter().enumerate().position(|(j, o)| j != i && *o == Some(sc)) +/// The stored shortcuts as craft-keymap overrides ("" = no shortcut). +fn overrides(keymap: &Keymap) -> Overrides { + let mut out = Overrides::new(); + for (id, text) in keymap { + let texts = if text.is_empty() { Vec::new() } else { vec![override_text(text)] }; + // Only an overlong id or text is refused, and neither can be a shortcut. + let _ = out.insert(id.clone(), texts); + } + out +} + +/// The keymap with `keymap`'s shortcuts for `platform`. +fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap { + craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)) +} + +/// The resolved keymap and the dispatcher that runs it against each frame's keys. +pub struct Bindings { + stored: Keymap, + map: craft_keymap::Keymap, + dispatcher: Dispatcher, +} + +impl Default for Bindings { + fn default() -> Bindings { + let stored = Keymap::new(); + let map = resolved(&stored, Platform::current()); + // Held keys repeat their command. Copy, Cut and Paste events count as Ctrl+C, X and V. + Bindings { stored, map, dispatcher: Dispatcher::new().with_repeat(true).with_clipboard_events(true) } + } +} + +impl Bindings { + /// Follows the stored shortcuts and the platform; a no-op while neither changed. + pub(crate) fn sync(&mut self, keymap: &Keymap, platform: Platform) { + if self.stored != *keymap || self.map.platform() != platform { + self.stored = keymap.clone(); + self.map = resolved(keymap, platform); + } + } + + /// The ids of the commands this frame's key presses run, in press order. The presses are + /// removed from the input. + pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec { + self.dispatcher.dispatch(input, &self.map, &Active::NONE).into_iter().map(|hit| hit.command.id).collect() + } + + /// The id of the command a key press outside the main window runs. The press is matched as + /// the main window's presses are. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn command_of(&self, press: &Event) -> Option { + let input = KeyInput::from_egui(press, self.map.platform())?; + self.dispatcher.layout().candidates(&input).into_iter().find_map(|chord| match self.map.lookup(&chord, false, &Active::NONE) { + Lookup::Run(command) => Some(command.id), + Lookup::Cycle(commands) => commands.into_iter().next().map(|command| command.id), + _ => None, + }) + } + + /// The shortcut a press records: the chord it runs, keeping the held Ctrl and Cmd as they are. + fn recorded(&self, press: &Event, key: Key, modifiers: Modifiers, platform: Platform) -> KeyboardShortcut { + let chord = KeyInput::from_egui(press, platform).and_then(|input| self.dispatcher.layout().resolve(&input)); + match chord { + Some(chord) => KeyboardShortcut::new(Modifiers { shift: chord.mods.shift, ..modifiers }, chord.to_egui_shortcut().logical_key), + None => KeyboardShortcut::new(modifiers, key), + } + } + + /// Whether a Shift-only Cut or Paste, read as Shift+Delete or Shift+Insert, runs nothing. + pub(crate) fn shift_clipboard_is_free(&self, event: &Event) -> bool { + let key = match event { + Event::Cut => craft_keymap::Key::Delete, + Event::Paste(_) => craft_keymap::Key::Insert, + _ => return false, + }; + matches!(self.map.lookup(&Chord::new(Mods::SHIFT, key), false, &Active::NONE), Lookup::None) + } + + /// Another binding on the same shortcut as `b`. + fn conflict(&self, b: &Binding) -> Option<&'static Binding> { + let clash = self.map.conflicts_with(&CommandRef::new(b.id)).into_iter().find(|c| c.kind == ConflictKind::Clash)?; + bindings().iter().find(|x| x.id == clash.b.0.id) + } } /// Bind `b` to `value` ("" = no shortcut); the default is stored as no override. @@ -127,7 +231,6 @@ pub fn sync_captured(keymap: &Keymap) { let clipboard = [Key::C, Key::V, Key::X]; let keys: Vec = active(keymap) .into_iter() - .map(|(_, sc)| sc) .filter(|sc| { let fkey = sc.logical_key.name().strip_prefix('F').is_some_and(|n| n.parse::().is_ok()); (sc.modifiers.command || sc.modifiers.alt || fkey) && !(sc.modifiers.command && !sc.modifiers.shift && clipboard.contains(&sc.logical_key)) @@ -151,10 +254,11 @@ pub fn capturing(ctx: &egui::Context) -> bool { } /// The first key press this frame as a shortcut. -fn pressed(ctx: &egui::Context) -> Option { +fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option { + let platform = craft_keymap::egui::platform(ctx); ctx.input(|i| { i.events.iter().find_map(|e| match e { - Event::Key { key, pressed: true, modifiers, .. } => Some(KeyboardShortcut::new(*modifiers, *key)), + Event::Key { key, pressed: true, modifiers, .. } => Some(bindings.recorded(e, *key, *modifiers, platform)), _ => None, }) }) @@ -169,7 +273,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { let capture_id = Id::unique(CAPTURE); let filter_id = Id::unique("keymap_filter"); let mut capture: Option = ctx.data(|d| d.get_temp(capture_id)); - if let (Some(i), Some(sc)) = (capture, pressed(ctx)) { + if let (Some(i), Some(sc)) = (capture, pressed(ctx, &app.bindings)) { if (sc.logical_key != Key::Escape || !sc.modifiers.is_none()) && let Some(b) = bindings().get(i) { @@ -177,10 +281,10 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } capture = None; } + app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx)); let mut filter: String = ctx.data(|d| d.get_temp(filter_id)).unwrap_or_default(); let mut open = true; crate::windows::window("keyboard_shortcuts", tr("Keyboard shortcuts"), &mut open).default_width(480.0).show(ctx, |ui| { - let resolved = resolve(&app.ui.keymap); ui.horizontal(|ui| { ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); ui.add(egui::TextEdit::singleline(&mut filter).hint_text(tr("Search commands or keys")).desired_width(300.0)); @@ -190,7 +294,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); }); - let clashes = (0..resolved.len()).filter(|i| conflict(&resolved, *i).is_some()).count(); + let clashes = bindings().iter().filter(|b| app.bindings.conflict(b).is_some()).count(); if clashes > 0 { ui.label( RichText::new(format!("{} {}", ic::WARNING, trf("{n} items share a shortcut; the first one listed wins.", &[("n", &clashes)]))) @@ -220,7 +324,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } let bound = current.is_some(); ui.horizontal(|ui| { - if let Some(other) = conflict(&resolved, i).and_then(|j| bindings().get(j)) { + if let Some(other) = app.bindings.conflict(b) { ui.label(RichText::new(ic::WARNING).color(tk.danger)) .on_hover_text(trf("Also bound to {item} ({menu})", &[("item", &tr(other.label)), ("menu", &tr(other.group))])); } @@ -300,48 +404,154 @@ mod tests { fn shortcuts_round_trip_through_parse_and_format() { for b in bindings() { if let Some(s) = b.default { - let sc = parse_shortcut(s).unwrap_or_else(|| panic!("{} has an unparsable shortcut {s}", b.id)); - assert_eq!(format_shortcut(&sc), s); + let chord = parse(s).unwrap_or_else(|| panic!("{} has an unparsable shortcut {s}", b.id)); + assert_eq!(format_shortcut(&chord.to_egui_shortcut()), s); } } for s in ["Ctrl+Shift+Alt+F12", "Alt+OpenBracket", "Shift+Delete", "Ctrl+9"] { - assert_eq!(parse_shortcut(s).map(|sc| format_shortcut(&sc)).as_deref(), Some(s)); + assert_eq!(parse(s).map(|chord| format_shortcut(&chord.to_egui_shortcut())).as_deref(), Some(s)); } - assert!(parse_shortcut("Ctrl+").is_none() && parse_shortcut("Ctrl+NoSuchKey").is_none()); + assert!(parse("Ctrl+").is_none() && parse("Ctrl+NoSuchKey").is_none()); + } + + fn bindings_for(keymap: &Keymap) -> Bindings { + let mut out = Bindings::default(); + out.sync(keymap, Platform::Windows); + out + } + + fn binding(id: &str) -> &'static Binding { + bindings().iter().find(|b| b.id == id).unwrap() } #[test] fn default_shortcuts_do_not_conflict() { - let resolved = resolve(&Keymap::new()); - for (i, b) in bindings().iter().enumerate() { - assert!(conflict(&resolved, i).is_none(), "{} shares its default shortcut", b.id); + let resolved = bindings_for(&Keymap::new()); + for b in bindings() { + assert!(resolved.conflict(b).is_none(), "{} shares its default shortcut", b.id); } } #[test] fn rebinding_detects_conflicts_and_resets() { - let all = bindings(); - let save = all.iter().position(|b| b.id == "file.save").unwrap(); - let undo = all.iter().position(|b| b.id == "edit.undo").unwrap(); + let (save, undo) = (binding("file.save"), binding("edit.undo")); let mut keymap = Keymap::new(); - rebind(&mut keymap, &all[save], "Ctrl+Z"); - let resolved = resolve(&keymap); - assert_eq!(conflict(&resolved, save), Some(undo)); - assert_eq!(conflict(&resolved, undo), Some(save)); + rebind(&mut keymap, save, "Ctrl+Z"); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.conflict(save).map(|b| b.id), Some("edit.undo")); + assert_eq!(resolved.conflict(undo).map(|b| b.id), Some("file.save")); assert_eq!(shortcut_of(&keymap, "file.save"), Some("Ctrl+Z")); // Unbinding clears the conflict; binding back to the default drops the override. - rebind(&mut keymap, &all[save], ""); + rebind(&mut keymap, save, ""); assert_eq!(shortcut_of(&keymap, "file.save"), None); - assert!(conflict(&resolve(&keymap), undo).is_none()); - rebind(&mut keymap, &all[save], "Ctrl+S"); + assert!(bindings_for(&keymap).conflict(undo).is_none()); + rebind(&mut keymap, save, "Ctrl+S"); assert!(keymap.is_empty()); } + fn press(key: Key, modifiers: Modifiers) -> Event { + Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } + } + + fn press_at(key: Key, physical: Key, modifiers: Modifiers) -> Event { + Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers } + } + + fn dispatched(bindings: &mut Bindings, events: Vec, modifiers: Modifiers) -> Vec { + let mut input = egui::InputState::default(); + input.modifiers = modifiers; + input.events = events; + bindings.dispatch(&mut input) + } + #[test] - fn specific_shortcuts_are_tried_first() { - let active = active(&Keymap::new()); - let pos = |id: &str| active.iter().position(|(x, _)| *x == id).unwrap(); - assert!(pos("viewport.previousChannel") < pos("viewport.nextChannel")); - assert!(pos("file.saveAs") < pos("file.save")); + fn a_stored_shortcut_on_a_shifted_symbol_runs_on_that_press() { + for (stored, key, physical, modifiers) in [ + ("Shift+Colon", Key::Colon, Key::Semicolon, Modifiers::SHIFT), + ("Shift+Exclamationmark", Key::Exclamationmark, Key::Num1, Modifiers::SHIFT), + ("Shift+Questionmark", Key::Questionmark, Key::Slash, Modifiers::SHIFT), + ("Ctrl+Shift+Plus", Key::Plus, Key::Equals, Modifiers::COMMAND | Modifiers::SHIFT), + ] { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), stored.into()); + let mut resolved = bindings_for(&keymap); + assert_eq!(dispatched(&mut resolved, vec![press_at(key, physical, modifiers)], modifiers), ["file.save"], "{stored}"); + assert_eq!(resolved.command_of(&press_at(key, physical, modifiers)).as_deref(), Some("file.save"), "{stored} in a floating panel"); + } + } + + #[test] + fn a_recorded_shifted_symbol_is_the_chord_it_runs() { + let resolved = bindings_for(&Keymap::new()); + let recorded = |key, physical, modifiers| format_shortcut(&resolved.recorded(&press_at(key, physical, modifiers), key, modifiers, Platform::Windows)); + assert_eq!(recorded(Key::Colon, Key::Semicolon, Modifiers::SHIFT), "Colon"); + // The layout needs Shift for this slash; the key at that position is not a symbol. + assert_eq!(recorded(Key::Slash, Key::Num7, Modifiers::SHIFT), "Slash"); + assert_eq!(recorded(Key::E, Key::E, Modifiers::COMMAND | Modifiers::SHIFT), "Ctrl+Shift+E"); + } + + #[test] + fn a_floating_panel_matches_presses_as_the_main_window_does() { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "Equals".into()); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.command_of(&press(Key::Plus, Modifiers::NONE)).as_deref(), Some("file.save"), "+ stands for ="); + } + + #[test] + fn a_floating_panel_leaves_a_bound_shift_insert_to_its_binding() { + let paste = || Event::Paste("text".into()); + let free = bindings_for(&Keymap::new()); + let event = crate::menus::forwarded_press(&free, paste(), Modifiers::SHIFT); + assert_eq!(free.command_of(&event).as_deref(), Some("layer.paste")); + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "Shift+Insert".into()); + keymap.insert("file.saveAs".into(), "Shift+Delete".into()); + let bound = bindings_for(&keymap); + let event = crate::menus::forwarded_press(&bound, paste(), Modifiers::SHIFT); + assert_eq!(bound.command_of(&event).as_deref(), Some("file.save")); + let event = crate::menus::forwarded_press(&bound, Event::Cut, Modifiers::SHIFT); + assert_eq!(bound.command_of(&event).as_deref(), Some("file.saveAs")); + } + + #[test] + fn a_press_runs_the_command_bound_to_exactly_that_chord() { + let resolved = bindings_for(&Keymap::new()); + let run = |mods: Modifiers, key: Key| resolved.command_of(&press(key, mods)); + assert_eq!(run(Modifiers::COMMAND, Key::S).as_deref(), Some("file.save")); + assert_eq!(run(Modifiers::COMMAND | Modifiers::SHIFT, Key::S).as_deref(), Some("file.saveAs")); + assert_eq!(run(Modifiers::SHIFT, Key::C).as_deref(), Some("viewport.previousChannel")); + assert_eq!(run(Modifiers::NONE, Key::C).as_deref(), Some("viewport.nextChannel")); + assert_eq!(run(Modifiers::ALT, Key::C), None, "Alt+C is not bound"); + assert_eq!(run(Modifiers::SHIFT, Key::M), None, "Shift+M is not bound"); + } + + #[test] + fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "F5".into()); + keymap.insert("edit.undo".into(), String::new()); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None); + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None); + } + + #[test] + fn ctrl_in_the_notation_is_the_command_key_on_macos() { + let mut resolved = Bindings::default(); + resolved.sync(&Keymap::new(), Platform::Mac); + let cmd = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; + assert_eq!(resolved.command_of(&press(Key::S, cmd)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::S, Modifiers::CTRL)), None, "the Control key is another key"); + } + + #[test] + fn the_first_item_listed_wins_a_shared_shortcut() { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "Ctrl+Z".into()); + let resolved = bindings_for(&keymap); + let first = bindings().iter().find(|b| matches!(b.id, "file.save" | "edit.undo")).unwrap().id; + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)).as_deref(), Some(first)); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fd5c2351..09e203b1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,28 +8,51 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_mode; +mod bake_scene; +mod color_selection_editor; pub mod control; pub mod dock; pub mod docking; pub mod export_templates; +#[cfg(not(target_arch = "wasm32"))] +pub mod file_dialogs; +mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; +pub mod id_color_pick; pub mod keymap; +mod mask_preview_image; +mod material_preview_image; pub mod menus; +pub mod new_project_advanced; +mod orb_shape; pub mod parity; +mod preview_image; +mod preview_request; +mod preview_worker; pub mod profile; +pub mod properties_popup; pub mod render_mode; +mod resource_picker; +mod resource_picker_item; pub mod shelf; +pub mod shelf_preview; +mod soft_box; pub mod state; pub mod theme; pub mod thumbs; pub mod titlebar; pub mod toolbar; +pub mod ui_state_store; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod updates_ui; +pub mod uv_paint_point; pub mod viewport; pub mod web_files; pub mod widgets; pub mod windows; +mod worker_preview; use std::sync::Arc; use std::sync::atomic::Ordering; @@ -41,6 +64,14 @@ use texturecraft_engine::bake::Progress; pub use control::ControlRequest; pub use state::UiState; +/// The app as the updater knows it: its releases, and the icon and color of its update prompt. +#[cfg(not(target_arch = "wasm32"))] +pub const UPDATE_APP: craft_update::App = craft_update::App { + icon_png: Some(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png")), + accent: Some([0xc2, 0x67, 0x2b]), + ..craft_update::App::new("texturecraft", "TextureCraft", "3D texture painting", "storytold/texturecraft") +}; + /// A texture set resize running on a worker thread (`Session::resize_task`). pub struct ResizeJob { pub progress: Arc, @@ -75,7 +106,11 @@ pub struct Toast { pub struct TextureCraftApp { pub session: Session, + /// A smooth move to a saved camera in progress. + camera_glide: Option, pub ui: UiState, + /// Where `ui` is saved between runs + ui_store: ui_state_store::UiStateStore, pub gpu: Option, pub control: Option>, pub toasts: Vec, @@ -100,8 +135,14 @@ pub struct TextureCraftApp { pub profiler: profile::Profiler, /// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines. pub last_paint_point: Option, + /// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines + pub last_paint_uv: Option, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, + /// The Properties popup a right click in a view opens. + pub properties_popup: Option, + /// The color selection the next click in the 3D or 2D view picks an ID color for + pub picking_id_color: Option, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -118,25 +159,46 @@ pub struct TextureCraftApp { styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. focused: bool, + /// The update check and prompt (desktop only). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) updates_rt: updates_ui::Runtime, + /// Native file dialogs and their continuations (desktop only). + #[cfg(not(target_arch = "wasm32"))] + pub file_dialogs: file_dialogs::FileDialogs, + /// The unsaved-changes dialog's Save is waiting on the Save dialog's answer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) saving_for_prompt: bool, + /// That Save dialog saved the project; the prompt goes on at its next frame. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) prompt_saved: bool, + /// The resolved keymap and its key dispatcher. + pub(crate) bindings: keymap::Bindings, } impl TextureCraftApp { + /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] - texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + + // The first run speaks the OS (or browser) language + let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); + let ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + let mut app = TextureCraftApp { + camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -153,7 +215,10 @@ impl TextureCraftApp { brushes: None, render: render_mode::RenderView::default(), last_paint_point: None, + last_paint_uv: None, placing_decal: None, + properties_popup: None, + picking_id_color: None, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, @@ -162,29 +227,51 @@ impl TextureCraftApp { next_autosave, styled: None, focused: true, + #[cfg(not(target_arch = "wasm32"))] + updates_rt: updates_ui::Runtime::default(), + #[cfg(not(target_arch = "wasm32"))] + file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), + #[cfg(not(target_arch = "wasm32"))] + saving_for_prompt: false, + #[cfg(not(target_arch = "wasm32"))] + prompt_saved: false, + bindings: keymap::Bindings::default(), }; app.ui.rename = None; app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); + app.report_ui_storage_warning(); export_templates::load_library(&mut app, cc.storage); + #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } + let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } + app } /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { + // Going to a saved camera glides there; the control channel and CLI jump straight away. + let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { - Ok(v) => Some(v), + Ok(v) => { + if let Some(from) = glide_from.filter(|f| *f != self.session.camera) { + self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); + self.session.camera = from; + } + Some(v) + } Err(e) => { self.toast(e.to_string(), true); None @@ -192,6 +279,13 @@ impl TextureCraftApp { } } + fn report_ui_storage_warning(&mut self) { + if let Some(warning) = self.ui_store.take_warning() { + self.session.log.push(warning.clone()); + self.toast_sticky(warning); + } + } + pub fn toast(&mut self, text: impl Into, error: bool) { self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 } }); } @@ -418,6 +512,40 @@ impl TextureCraftApp { } } +/// A smooth move of the viewport camera (see [`TextureCraftApp::run`]). +struct CameraGlide { + from: texturecraft_engine::geom::OrbitCamera, + to: texturecraft_engine::geom::OrbitCamera, + start: f64, +} + +const GLIDE_SECONDS: f64 = 0.35; + +impl TextureCraftApp { + /// Advance the camera glide by one frame. + fn step_camera_glide(&mut self, ctx: &egui::Context) { + let Some(g) = &self.camera_glide else { return }; + let t = ((self.last_time - g.start) / GLIDE_SECONDS).clamp(0.0, 1.0) as f32; + let e = t * t * (3.0 - 2.0 * t); + let (a, b) = (g.from, g.to); + let mix = |x: f32, y: f32| x + (y - x) * e; + let mut c = b; + c.target = a.target.lerp(b.target, e); + c.yaw = mix(a.yaw, b.yaw); + c.pitch = mix(a.pitch, b.pitch); + c.distance = mix(a.distance, b.distance); + c.fov = mix(a.fov, b.fov); + // Orthographic switches at the end (the projections cannot be blended). + c.ortho = if t >= 1.0 { b.ortho } else { a.ortho }; + self.session.camera = c; + self.session.revision = self.session.revision.wrapping_add(1); + if t >= 1.0 { + self.camera_glide = None; + } + ctx.request_repaint(); + } +} + impl eframe::App for TextureCraftApp { /// The browser never tells eframe the page is closing, so save often there. fn auto_save_interval(&self) -> std::time::Duration { @@ -425,7 +553,8 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); + self.ui_store.save(&self.ui, storage); + self.report_ui_storage_warning(); export_templates::save_library(self, storage); } @@ -442,7 +571,10 @@ impl eframe::App for TextureCraftApp { theme::apply(ctx, style.0, style.1); self.styled = Some(style); } + self.step_camera_glide(ctx); control::poll(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + self.run_file_dialog_answers(); web_files::poll(self); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); for f in &dropped { @@ -473,6 +605,9 @@ impl eframe::App for TextureCraftApp { web_files::sync_unsaved(self); } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); + #[cfg(not(target_arch = "wasm32"))] + updates_ui::tick(self, ctx); + self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); // A stored path being edited repaints its sublayer as its points, brush or material change. if let Err(e) = self.session.path_live() { @@ -482,9 +617,12 @@ impl eframe::App for TextureCraftApp { profile::drive(self, ctx); self.toasts.retain(|t| t.until > now); self.profiler.logic_ms = (now_ms() - t0) as f32; + // Last, so it sees every close request this frame's work made. + windows::close_request(self, ctx); } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); let t0 = now_ms(); if !self.ui.hide_ui { @@ -500,10 +638,14 @@ impl eframe::App for TextureCraftApp { let hide = self.ui.hide_ui; let tk = theme::Tokens::get(&ctx); // The dock keeps the cards' gutter from the bars and rails around it. - let frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; - egui::CentralPanel::default().frame(frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); + let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; + egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); + #[cfg(not(target_arch = "wasm32"))] + updates_ui::show(self, &ctx); toasts(self, &ctx); + #[cfg(not(target_arch = "wasm32"))] + self.file_dialogs.show_pending(frame); let end = now_ms(); let dt = (end - t0) as f32; self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs new file mode 100644 index 00000000..de7368df --- /dev/null +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -0,0 +1,40 @@ +//! Smart masks appear white against a near-black surface + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::orb_preview::MaskPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space lighting uses an upper-left key and a weaker right fill +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// A faint sheen reveals the unmasked shape without a glossy finish +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit +const WHITE_SHADING: f32 = 0.2; + +/// Shade row-major `size²` mask pixels in sRGB with a transparent background +pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/material_preview_image.rs b/crates/ui-egui/src/material_preview_image.rs new file mode 100644 index 00000000..bc232b75 --- /dev/null +++ b/crates/ui-egui/src/material_preview_image.rs @@ -0,0 +1,100 @@ +//! Shading of the smart material previews: a dark studio whose soft boxes show in reflections and light the diffuse color + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::orb_preview::MaterialPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::preview_image::{aces, bumped_normal, height_slope, preview_radius}; +use crate::soft_box::{SoftBox, smoothstep}; + +/// The studio's soft boxes: a key at the upper right, a fill at the left and a rim light above and behind +const SOFT_BOXES: [SoftBox; 3] = [ + SoftBox { direction: [0.55, 0.75, 0.35], radius_rad: 0.6, intensity: 2.6 }, + SoftBox { direction: [-0.95, 0.2, 0.1], radius_rad: 0.7, intensity: 0.9 }, + SoftBox { direction: [0.1, 0.9, -0.45], radius_rad: 0.35, intensity: 1.6 }, +]; +/// The studio's backdrop brightness straight down and straight up (linear) +const FLOOR: f32 = 0.03; +const CEILING: f32 = 0.16; +/// The lowest roughness shaded (a perfect mirror would show the soft boxes' hard edges) +const MIN_ROUGHNESS: f32 = 0.02; +/// Reflectance of dielectrics at normal incidence +const DIELECTRIC_F0: f32 = 0.04; +/// Exposure before tone mapping +const EXPOSURE: f32 = 1.4; + +/// A smart material preview (sRGB, transparent off the shape) from `size²` preview pixels; height bumps the normals +pub fn material_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let radius = preview_radius(size); + let height = |index: usize| pixels.get(index).copied().flatten().map(|pixel| pixel.sample.height); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (index, (out, pixel)) in image.pixels.iter_mut().zip(pixels).enumerate() { + let Some(pixel) = pixel else { continue }; + + let sample = pixel.sample; + let normal = bumped_normal(pixel.normal, height_slope(size, index, sample.height, height), radius); + let roughness = sample.roughness.max(MIN_ROUGHNESS); + let normal_dot_view = normal.z.max(0.0); + // Mirror the direction towards the viewer (+Z) about the normal + let reflected = (2.0 * normal_dot_view * normal - Vec3::Z).normalize_or_zero(); + let specular_light = reflected_light(reflected, roughness); + let diffuse_light = diffuse_light(normal); + // Schlick's Fresnel term, damped on rough surfaces below + let fresnel = (1.0 - normal_dot_view).powi(5); + + let color = [0, 1, 2].map(|component| { + let base = sample.base[component]; + let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * sample.metallic; + let reflectance = f0 + ((1.0 - roughness).max(f0) - f0) * fresnel; + let linear = reflectance * specular_light + base * (1.0 - sample.metallic) * (1.0 - reflectance) * diffuse_light; + (linear_to_srgb(aces(linear * EXPOSURE)) * 255.0 + 0.5) as u8 + }); + let alpha = (pixel.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(color[0], color[1], color[2], alpha); + } + image +} + +/// How far unit direction component `y` points up: 0 straight down, 1 straight up +fn upward(y: f32) -> f32 { + y * 0.5 + 0.5 +} + +/// The backdrop's brightness `upward` of the way from the floor (0) to the ceiling (1) +fn backdrop(upward: f32) -> f32 { + FLOOR + (CEILING - FLOOR) * upward +} + +/// The studio seen along unit direction `view` by a surface of `roughness` +fn reflected_light(view: Vec3, roughness: f32) -> f32 { + // A soft horizon: reflections sweep from floor to ceiling smoothly + backdrop(smoothstep(upward(view.y))) + SOFT_BOXES.iter().map(|soft_box| soft_box.reflected(view, roughness)).sum::() +} + +/// The light reaching a diffuse surface with unit normal `normal` +fn diffuse_light(normal: Vec3) -> f32 { + backdrop(upward(normal.y)) + SOFT_BOXES.iter().map(|soft_box| soft_box.diffuse(normal)).sum::() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::preview::Sample; + + use super::*; + + #[test] + fn the_studio_lights_the_shape_from_the_upper_right() { + let polished_metal = Sample { base: [0.9; 3], metallic: 1.0, roughness: 0.3, height: 0.0 }; + let facing = |normal: Vec3| Some(MaterialPreviewPixel { sample: polished_metal, normal: normal.normalize(), coverage: 1.0 }); + // Halfway between the viewer and the key light, a mirror reflects the key + let towards_the_key = SOFT_BOXES[0].unit_direction() + Vec3::Z; + let pixels = [facing(towards_the_key), facing(Vec3::new(-0.3, -0.9, 0.3)), None, None]; + + let image = material_preview_image(2, &pixels); + let [lit, unlit, outside] = [0, 1, 2].map(|index| image.pixels[index]); + assert!(lit.r() > 200 && unlit.r() < 80, "the key light's reflection shows: {lit:?} vs {unlit:?}"); + assert_eq!((lit.a(), outside.a()), (255, 0), "opaque on the shape, transparent outside"); + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a2e85bf7..df5be69c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -2,13 +2,14 @@ //! texture-painting workflow, with stable ids; an item is live when the engine (or the shell, for `ui.*` ids) implements //! its id. The same catalog drives `docs/parity.md`. -use egui::{Key, KeyboardShortcut, Modifiers}; +use egui::{Key, Modifiers}; use serde_json::{Value, json}; use crate::TextureCraftApp; use crate::i18n::tr; use crate::state::{Mode, ViewLayout}; use crate::theme::Tokens; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; /// One menu entry. `label == "-"` is a separator; `sub` names a submenu group. #[derive(Clone, Copy, Debug)] @@ -61,12 +62,13 @@ pub const CATALOG: &[Item] = &[ it("Mode", "Painting", "ui.mode.paint", Some("F9")), it("Mode", "Rendering (path traced)", "ui.mode.render", Some("F10")), sub("Window", "Views", "Assets", "ui.view.assets", None), - sub("Window", "Views", "Bake Maps", "ui.view.bakeMaps", None), - sub("Window", "Views", "Settings", "ui.view.bakeSettings", None), + sub("Window", "Views", "Common Settings", "ui.view.bakeSettings", None), sub("Window", "Views", "Display Settings", "ui.view.display", None), sub("Window", "Views", "History", "ui.view.history", None), sub("Window", "Views", "Layers", "ui.view.layers", None), sub("Window", "Views", "Log", "ui.view.log", None), + sub("Window", "Views", "Mesh Map Bakers", "ui.view.meshMapBakers", None), + sub("Window", "Views", "Mesh Map Settings", "ui.view.bakeMaps", None), sub("Window", "Views", "Properties", "ui.view.properties", None), sub("Window", "Views", "Shader Settings", "ui.view.shader", None), sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), @@ -98,6 +100,8 @@ pub const CATALOG: &[Item] = &[ it("Help", "Report a bug...", "ui.help.bug", None), sep("Help"), it("Help", "Show log...", "ui.view.log", None), + #[cfg(not(target_arch = "wasm32"))] + it("Help", "Check for Updates...", "ui.help.checkForUpdates", None), it("Help", "About TextureCraft...", "ui.about", None), ]; @@ -163,6 +167,8 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.layout.2d" => app.ui.layout = ViewLayout::Only2D, "ui.help.shortcuts" => app.ui.windows.shortcuts = true, "ui.about" => app.ui.windows.about = true, + #[cfg(not(target_arch = "wasm32"))] + "ui.help.checkForUpdates" => crate::updates_ui::request_check(app, ctx), "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/texturecraft")), "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft#readme")), @@ -176,21 +182,6 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { } } -/// Parse "Ctrl+Shift+E" style shortcuts. -pub fn parse_shortcut(s: &str) -> Option { - let mut mods = Modifiers::NONE; - let mut key = None; - for part in s.split('+') { - match part { - "Ctrl" | "Cmd" => mods |= Modifiers::COMMAND, - "Shift" => mods |= Modifiers::SHIFT, - "Alt" => mods |= Modifiers::ALT, - k => key = Key::from_name(k), - } - } - key.map(|k| KeyboardShortcut::new(mods, k)) -} - /// The menus, then the mode label at the right of `ui` (the strip `titlebar::show` lays out). pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tk = Tokens::get(ui.ctx()); @@ -277,18 +268,35 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, /// Keys pressed in a floating panel's own OS window run the shortcuts the main window's keys do. #[cfg(not(target_arch = "wasm32"))] pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec, held: Modifiers) { - if crate::keymap::capturing(ctx) { + if crate::keymap::capturing(ctx) || crate::updates_ui::blocks_input(app) { return; } - let active = crate::keymap::active(&app.ui.keymap); + app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx)); for event in events { - let event = clipboard_key(&event, held).unwrap_or(event); - let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue }; - let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue }; - invoke(app, ctx, effect_command(app, id)); + let event = forwarded_press(&app.bindings, event, held); + if !matches!(event, egui::Event::Key { pressed: true, repeat: false, .. }) { + continue; + } + let Some(id) = app.bindings.command_of(&event) else { continue }; + invoke(app, ctx, effect_command(app, &id)); } } +/// The press a floating panel's event stands for. Cut and Paste with Shift alone are Shift+Delete +/// and Shift+Insert when something is bound to them, and clipboard shortcuts otherwise. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn forwarded_press(bindings: &crate::keymap::Bindings, event: egui::Event, held: Modifiers) -> egui::Event { + let shift_key = match event { + egui::Event::Cut => Some(Key::Delete), + egui::Event::Paste(_) => Some(Key::Insert), + _ => None, + }; + if let Some(key) = shift_key.filter(|_| shift_only(held) && !bindings.shift_clipboard_is_free(&event)) { + return egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held }; + } + clipboard_key(&event, held).unwrap_or(event) +} + /// Layer shortcuts act on the selected effect instead of its layer (copy, cut, duplicate, /// remove), and paste a copied effect onto the selection. fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { @@ -303,45 +311,66 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } +/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { - if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) { + if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { + return; + } + #[cfg(not(target_arch = "wasm32"))] + if crate::updates_ui::blocks_input(app) { return; } + // The dispatcher reads Copy, Cut and Paste as their chords. A pasted image is Ctrl+V here, and + // Shift+Delete and Shift+Insert (Cut and Paste on Windows) are Ctrl+X and Ctrl+V unless + // something is bound to them. ctx.input_mut(|input| { - let keys: Vec<_> = input.events.iter().filter_map(|event| clipboard_key(event, input.modifiers)).collect(); - input.events.extend(keys); + let held = input.modifiers; + let aliases: Vec<_> = input + .events + .iter() + .filter(|event| matches!(event, egui::Event::PasteImage(_)) || (shift_only(held) && app.bindings.shift_clipboard_is_free(event))) + .filter_map(|event| clipboard_key(event, held)) + .collect(); + input.events.extend(aliases); }); - if !ctx.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Key { pressed: true, .. }))) { - return; - } + // Escape closes an open popup first, before the Properties popup or the stroke + let popup_open = egui::Popup::is_any_open(ctx); - let active_shortcuts = crate::keymap::active(&app.ui.keymap); - let mut commands_to_invoke: Vec<&str> = Vec::new(); - ctx.input_mut(|input| { - for (id, shortcut) in &active_shortcuts { - if input.consume_shortcut(shortcut) { - commands_to_invoke.push(*id); + let commands_to_invoke = ctx.input_mut(|input| { + // egui's label selection copies on these events at the end of the frame + let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect(); + let commands = app.bindings.dispatch(input); + for copy in copies { + if !input.events.contains(©) { + input.events.push(copy); } } + // [ and ] shrink and grow the brush by this factor per press + const BRACKET_SIZE_STEP: f32 = 1.15; let size_down = input.consume_key(Modifiers::NONE, Key::OpenBracket); let size_up = input.consume_key(Modifiers::NONE, Key::CloseBracket); if app.ui.mode == Mode::Painting && (size_down || size_up) { - let scale = if size_up { 1.15 } else { 1.0 / 1.15 }; - app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(0.0005, 0.25); + let scale = if size_up { BRACKET_SIZE_STEP } else { 1.0 / BRACKET_SIZE_STEP }; + app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.properties_popup = None; + } else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + crate::id_color_pick::IdColorPick::end(app); + } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; } + commands }); - for id in commands_to_invoke { - if matches!(id, "layer.copy" | "layer.cut") + for id in &commands_to_invoke { + if matches!(id.as_str(), "layer.copy" | "layer.cut") && let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer)) { // Ctrl+V reaches the app only while the system clipboard holds text or an image @@ -361,5 +390,11 @@ fn clipboard_key(event: &egui::Event, held: Modifiers) -> Option { egui::Event::Paste(_) | egui::Event::PasteImage(_) => Key::V, _ => return None, }; - Some(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held | Modifiers::COMMAND }) + let modifiers = if shift_only(held) { Modifiers::COMMAND } else { held | Modifiers::COMMAND }; + Some(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }) +} + +/// Shift alone is held: a clipboard event that came from Shift+Delete or Shift+Insert. +fn shift_only(held: Modifiers) -> bool { + held.shift && !(held.command || held.ctrl || held.mac_cmd || held.alt) } diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs new file mode 100644 index 00000000..3247fc8e --- /dev/null +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -0,0 +1,163 @@ +//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation + +use std::collections::BTreeSet; + +use egui::{RichText, Sense, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::NewProject; +use crate::theme::{Tokens, caption}; +use crate::widgets::{section, section_chevron}; +use crate::windows::file_dialogs_available; + +/// Labels of every New project form row, so Basic and Advanced share one label column +const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; + +/// Each normal map format with its command id and label +const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; + +/// Width of the dialog's dropdowns +pub(crate) const COMBO_WIDTH: f32 = 200.0; + +/// Width of the Add... and Clear buttons +const FILE_BUTTON_WIDTH: f32 = 96.0; + +/// Tallest the list of added files grows before it scrolls +const FILE_LIST_HEIGHT: f32 = 160.0; + +/// Width of the widest form label, for the label column of every form grid in the dialog +pub(crate) fn form_label_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +} + +/// The collapsible Advanced settings section (closed until opened) +pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let id = ui.make_persistent_id("np_advanced"); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + + state.show_body_unindented(ui, |ui| { + egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { + ui.label(tr("Normal map format")); + normal_format_combo(app, ui); + ui.end_row(); + }); + if file_dialogs_available() { + ui.add_space(4.0); + section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| { + if baked_maps(&mut app.ui.new_project, ui) { + ask_baked_map_files(app); + } + }); + } + }); +} + +fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { + let new_project = &mut app.ui.new_project; + let template_format = app.session.template(&new_project.template).map(|template| template.normal_format).unwrap_or_default(); + let current = new_project.normal_format.unwrap_or(template_format); + let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); + egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + for (format, _, label) in NORMAL_FORMATS { + if ui.selectable_label(format == current, label).clicked() { + new_project.normal_format = Some(format); + } + } + }); +} + +/// The baked map list and its buttons; true when Add was clicked. +fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut add = false; + ui.horizontal(|ui| { + let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); + ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(hint_width); + ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + }); + if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + add = true; + } + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + new_project.baked_maps.clear(); + } + }); + if new_project.baked_maps.is_empty() { + return add; + } + + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); + add +} + +/// List picked baked map files (files already listed are skipped) +pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { + for path in paths { + if !new_project.baked_maps.contains(&path) { + new_project.baked_maps.push(path); + } + } +} + +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list +pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { + let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { + app.run("textureSet.settings", json!({ "normalFormat": id })); + } + if new_project.baked_maps.is_empty() { + return; + } + + let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { + return; + }; + + let assigned = result["assigned"].as_array().into_iter().flatten(); + let maps: BTreeSet<(u64, &str)> = assigned.filter_map(|entry| Some((entry["ts"].as_u64()?, entry["map"].as_str()?))).collect(); + let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); + let mut text = trf("Baked maps imported: {count}", &[("count", &maps.len())]); + if !not_imported.is_empty() { + text.push('\n'); + text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); + } + app.toast(text, !not_imported.is_empty()); + app.ui.new_project.baked_maps.clear(); +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn ask_baked_map_files(app: &mut TextureCraftApp) { + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, |app, files| { + add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect()); + }); +} + +#[cfg(target_arch = "wasm32")] +fn ask_baked_map_files(_app: &mut TextureCraftApp) {} diff --git a/crates/ui-egui/src/orb_shape.rs b/crates/ui-egui/src/orb_shape.rs new file mode 100644 index 00000000..3d220a5c --- /dev/null +++ b/crates/ui-egui/src/orb_shape.rs @@ -0,0 +1,33 @@ +//! The preview orb of the smart mask and smart material previews, baked on first use + +use texturecraft_engine::orb_preview::OrbPreview; + +/// Whether the preview orb is baked +#[derive(Default)] +pub enum OrbShape { + #[default] + NotBaked, + /// Box the large session to keep the unbaked worker small + Baked(Box), + /// The bake failed; previews on the orb stay empty + Failed, +} + +impl OrbShape { + /// Bake on first use; retain failure to avoid retrying every frame + pub fn get(&mut self) -> Option<&mut OrbPreview> { + if matches!(self, OrbShape::NotBaked) { + *self = match OrbPreview::new() { + Ok(preview) => OrbShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("preview orb: {e}"); + OrbShape::Failed + } + }; + } + match self { + OrbShape::Baked(preview) => Some(preview), + OrbShape::NotBaked | OrbShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs new file mode 100644 index 00000000..9b753b74 --- /dev/null +++ b/crates/ui-egui/src/preview_image.rs @@ -0,0 +1,196 @@ +//! CPU renderers for shelf spheres, swatches, strokes and imported images + +use egui::{Color32, ColorImage}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::{BrushSettings, Shape}; +use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::texel::linear_to_srgb; + +/// Pattern scale of the procedural swatches (repeats across the swatch) +const PROCEDURAL_SCALE: f32 = 3.0; +/// Samples per pixel along each axis of the alpha swatches +const ALPHA_SUPERSAMPLE: usize = 2; +/// Normal tilt per height step, relative to the shape's radius in pixels +const BUMP_PER_RADIUS: f32 = 0.75; +/// Exposure of the shaded previews before tone mapping +const EXPOSURE: f32 = 1.4; +/// Gap between a preview's shape and the image edge in pixels +const SHAPE_MARGIN_PX: f32 = 1.0; +/// Guards the normal division against a zero vector +const MIN_NORMAL_LENGTH: f32 = 1e-6; + +/// Linear shading for view-space normal `n`, viewed along +Z +pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { + let l = [0.45f32, 0.7, 0.55]; + let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); + let l = l.map(|v| v / len); + let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); + let ndv = n[2].max(0.0); + // The view direction is +Z + let h = [l[0], l[1], l[2] + 1.0]; + let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); + let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); + let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; + let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; + // Roughness blurs the reflected horizon toward the environment average + let ry = 2.0 * ndv * n[1]; + let w = 0.06 + rough * 0.9; + let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); + let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); + let env = sharp + (0.28 - sharp) * (rough * rough); + let fres = (1.0 - ndv).powi(5); + let sky = 0.35 + 0.25 * n[1]; + let mut out = [0.0; 3]; + for k in 0..3 { + let f0 = 0.04 + (base[k] - 0.04) * metal; + let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; + let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); + out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; + } + out +} + +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1 +pub fn aces(x: f32) -> f32 { + let v = x * 0.6; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) +} + +/// Shade row-major `size²` samples with height bumps and a transparent background +pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let radius = preview_radius(size); + let height = |index: usize| samples.get(index).copied().flatten().map(|sample| sample.height); + + for (index, normal) in preview::sphere_normals(size).enumerate() { + let (Some(normal), Some(Some(sample))) = (normal, samples.get(index)) else { continue }; + + // Anti-aliased outline: opaque from one pixel inside the rim + let coverage = ((1.0 - (normal.x * normal.x + normal.y * normal.y).sqrt()) * radius).clamp(0.0, 1.0); + image.pixels[index] = lit_pixel(normal, height_slope(size, index, sample.height, height), radius, sample, coverage); + } + image +} + +/// Radius in pixels of the shape filling a `size²` preview +pub(crate) fn preview_radius(size: usize) -> f32 { + (size as f32 * 0.5 - SHAPE_MARGIN_PX).max(0.5) +} + +/// Height change per pixel rightwards and upwards at `pixel`; None heights count as `center` +pub(crate) fn height_slope(size: usize, pixel: usize, center: f32, height: impl Fn(usize) -> Option) -> [f32; 2] { + let (x, y) = (pixel % size, pixel / size); + let at = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + height(y.checked_mul(size)?.checked_add(x)?) + }; + + // Image Y points down; the shading normal uses Y up + let right = at(Some(x + 1), Some(y)).unwrap_or(center) - at(x.checked_sub(1), Some(y)).unwrap_or(center); + let up = at(Some(x), y.checked_sub(1)).unwrap_or(center) - at(Some(x), Some(y + 1)).unwrap_or(center); + [right, up] +} + +/// Tilt a view-space normal by the height `slope` on a shape of `radius` pixels +pub(crate) fn bumped_normal(normal: Vec3, slope: [f32; 2], radius: f32) -> Vec3 { + let bump = radius * BUMP_PER_RADIUS; + let bumped = [normal.x - slope[0] * bump, normal.y - slope[1] * bump, normal.z]; + let length = (bumped[0] * bumped[0] + bumped[1] * bumped[1] + bumped[2] * bumped[2]).sqrt().max(MIN_NORMAL_LENGTH); + Vec3::from(bumped.map(|component| component / length)) +} + +/// One sphere pixel of `sample`, bumped by `slope` and `coverage` opaque +fn lit_pixel(normal: Vec3, slope: [f32; 2], radius: f32, sample: &Sample, coverage: f32) -> Color32 { + let linear = shade(bumped_normal(normal, slope, radius).to_array(), sample.base, sample.metallic, sample.roughness); + let color = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(color[0], color[1], color[2], (coverage * 255.0) as u8) +} + +/// Grayscale `size²` swatch of procedural `kind` +pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let pattern = Procedural { scale: PROCEDURAL_SCALE, ..Procedural::new(kind) }; + let mut img = ColorImage::filled([size, size], Color32::BLACK); + for (i, px) in img.pixels.iter_mut().enumerate() { + let uv = Vec2::new(((i % size) as f32 + 0.5) / size as f32, ((i / size) as f32 + 0.5) / size as f32); + let v = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); + *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + } + img +} + +/// White-on-black `size²` swatch of library alpha `alpha` +pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { + let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); + ColorImage::new([size, size], pixels) +} + +/// Letterbox into a `size²` square, compositing transparency over black +pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { + let aspect = img.width as f32 / img.height.max(1) as f32; + let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; + let mut preview = ColorImage::filled([size, size], Color32::BLACK); + for y in 0..size { + for x in 0..size { + let u = ((x as f32 + 0.5) / size as f32 - 0.5) * scale_u + 0.5; + let v = ((y as f32 + 0.5) / size as f32 - 0.5) * scale_v + 0.5; + if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { + continue; + } + + let sample = img.sample(u, v); + let alpha = sample[3]; + let encode = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * alpha.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * alpha) * 255.0) as u8 }; + preview.pixels[y * size + x] = Color32::from_rgb(encode(sample[0]), encode(sample[1]), encode(sample[2])); + } + } + preview +} + +/// Preview the brush along an S curve in an `n`-pixel square +pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { + let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = n as f32 * 0.11; + let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); + let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); + let mut cover = vec![0f32; n * n]; + // Stable jitter keeps the preview reproducible + let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; + let step = (b.spacing * 2.0 * radius).max(0.5); + let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + let mut last = curve(0.0); + while t <= 1.0 && i < 2000 { + let p = curve(t); + travelled += (p.0 - last.0).hypot(p.1 - last.1); + last = p; + t += 0.002; + if travelled < step { + continue; + } + travelled = 0.0; + i += 1; + let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); + let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); + let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); + let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + let (sin, cos) = angle.sin_cos(); + let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); + let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + for y in y0..y1 { + for x in x0..x1 { + let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); + let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; + let c = &mut cover[y * n + x]; + *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + } + } + } + ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +} diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs new file mode 100644 index 00000000..7797a7e3 --- /dev/null +++ b/crates/ui-egui/src/preview_request.rs @@ -0,0 +1,31 @@ +//! Shelf preview work submitted to [`crate::preview_worker::PreviewWorker`] + +use egui::ColorImage; + +use crate::mask_preview_image::mask_preview_image; +use crate::material_preview_image::material_preview_image; +use crate::orb_shape::OrbShape; +use crate::shelf_preview::ShelfPreview; + +/// Render `preview` at `size_px²`; the answer comes back under `key` +pub struct PreviewRequest { + pub key: String, + pub preview: ShelfPreview, + pub size_px: usize, + /// A hover preview: the worker renders the newest of these before anything else + // The web renders each request at once, so nothing is reordered there + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub hover: bool, +} + +impl PreviewRequest { + /// Render the asset, baking the orb on first use for smart masks and smart materials + /// Unknown assets and failed bakes return None + pub fn render(&self, shape: &mut OrbShape) -> Option { + match &self.preview { + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), + preview => preview.image(self.size_px), + } + } +} diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs new file mode 100644 index 00000000..c979e3e4 --- /dev/null +++ b/crates/ui-egui/src/preview_worker.rs @@ -0,0 +1,233 @@ +//! Native preview rendering uses a separate thread pool +//! Web requests render synchronously on the UI thread + +#[cfg(any(target_arch = "wasm32", test))] +use crate::orb_shape::OrbShape; +use crate::preview_request::PreviewRequest; + +/// Request key and rendered image; None on failure +pub type PreviewResult = (String, Option); + +/// The preview worker, started by the first request +#[derive(Default)] +pub enum PreviewWorker { + #[default] + NotStarted, + /// Native worker; dropping the request sender ends it after pending work + #[cfg(not(target_arch = "wasm32"))] + Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, + /// The web: requests render as they are made + #[cfg(any(target_arch = "wasm32", test))] + Inline { shape: OrbShape, results: Vec }, + /// The worker could not start or stopped; requests are refused + // The web has no thread to stop + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + Stopped, +} + +impl PreviewWorker { + /// Submit work, starting the worker on first use; false if it has stopped + /// Completed results request a repaint so the UI polls them on the next pass + pub fn request(&mut self, context: &egui::Context, request: PreviewRequest) -> bool { + if matches!(self, PreviewWorker::NotStarted) { + *self = PreviewWorker::start(context); + } + + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { requests, .. } => { + if requests.send(request).is_ok() { + return true; + } + + *self = PreviewWorker::Stopped; + false + } + #[cfg(any(target_arch = "wasm32", test))] + PreviewWorker::Inline { shape, results } => { + results.push((request.key.clone(), request.render(shape))); + context.request_repaint(); + true + } + PreviewWorker::NotStarted | PreviewWorker::Stopped => false, + } + } + + /// The results ready since the last call + pub fn poll(&mut self) -> Vec { + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { results, .. } => { + use std::sync::mpsc::TryRecvError; + + let mut ready = Vec::new(); + loop { + match results.try_recv() { + Ok(result) => ready.push(result), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + log::warn!("the shelf preview worker stopped"); + *self = PreviewWorker::Stopped; + break; + } + } + } + ready + } + #[cfg(any(target_arch = "wasm32", test))] + PreviewWorker::Inline { results, .. } => std::mem::take(results), + PreviewWorker::NotStarted | PreviewWorker::Stopped => Vec::new(), + } + } + + /// Whether the worker stopped: it refuses requests and answers none of the queued ones + pub fn is_stopped(&self) -> bool { + matches!(self, PreviewWorker::Stopped) + } + + /// Start the worker thread (Stopped when it cannot start) + #[cfg(not(target_arch = "wasm32"))] + fn start(ctx: &egui::Context) -> PreviewWorker { + use std::collections::VecDeque; + use std::sync::mpsc::channel; + + use crate::orb_shape::OrbShape; + + let (requests, request_rx) = channel::(); + let (result_tx, results) = channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { + // A separate pool keeps previews from queuing ahead of the UI's work + let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); + if let Err(e) = &pool { + log::warn!("shelf previews share the global thread pool: {e}"); + } + let mut shape = OrbShape::default(); + let mut queue = VecDeque::new(); + loop { + if queue.is_empty() { + let Ok(request) = request_rx.recv() else { break }; + + queue.push_back(request); + } + queue.extend(request_rx.try_iter()); + + let Some(request) = next_request(&mut queue) else { continue }; + + let image = match &pool { + Ok(pool) => pool.install(|| request.render(&mut shape)), + Err(_) => request.render(&mut shape), + }; + if result_tx.send((request.key, image)).is_err() { + break; + } + ctx.request_repaint(); + } + }); + + match spawned { + Ok(_) => PreviewWorker::Running { requests, results }, + Err(e) => { + log::warn!("could not start the shelf preview worker: {e}"); + PreviewWorker::Stopped + } + } + } + + /// Render inline (no threads on the web) + #[cfg(target_arch = "wasm32")] + fn start(_ctx: &egui::Context) -> PreviewWorker { + PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() } + } +} + +/// Prioritize the newest hover preview over older requests +#[cfg(not(target_arch = "wasm32"))] +fn next_request(queue: &mut std::collections::VecDeque) -> Option { + match queue.iter().rposition(|request| request.hover) { + Some(newest_hover) => queue.remove(newest_hover), + None => queue.pop_front(), + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::time::{Duration, Instant}; + + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::smart_masks::SMART_MASKS; + + use super::*; + use crate::shelf_preview::ShelfPreview; + + #[test] + fn inline_results_schedule_a_frame_to_display_them() { + for id in ["steel", "nope"] { + let context = egui::Context::default(); + for _ in 0..3 { + let mut output = context.run_pass(Default::default(), |_| {}); + + // No renderer consumes the texture updates in this scheduling test + output.textures_delta.clear(); + } + assert!(!context.has_requested_repaint(), "the UI is idle before the request"); + + let mut worker = PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }; + assert!(worker.poll().is_empty(), "the UI polls before submitting work"); + let request = PreviewRequest { key: id.into(), preview: ShelfPreview::Material(id), size_px: 8, hover: false }; + assert!(worker.request(&context, request)); + + let results = worker.poll(); + assert_eq!(results.len(), 1); + assert_eq!(results[0].1.is_some(), id == "steel"); + assert!(context.has_requested_repaint(), "the result needs another frame even when this is the only request"); + } + } + + #[test] + fn requests_are_answered_and_unknown_assets_get_none() { + let ctx = egui::Context::default(); + let mut worker = PreviewWorker::default(); + let size_px = 32; + let requests = [ + ("material", ShelfPreview::Material(MATERIALS[0].id)), + ("unknown material", ShelfPreview::Material("nope")), + ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), + ("unknown mask", ShelfPreview::SmartMask("nope")), + ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), + ("unknown smart material", ShelfPreview::SmartMaterial("nope")), + ]; + let requests_sent = requests.len(); + for (key, preview) in requests { + assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); + } + + let mut answers = HashMap::new(); + let start = Instant::now(); + while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { + answers.extend(worker.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + + for key in ["material", "mask", "smart material"] { + let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); + assert_eq!(image.size, [size_px, size_px], "{key}"); + } + for key in ["unknown material", "unknown mask", "unknown smart material"] { + assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); + } + assert!(!worker.is_stopped()); + } + + #[test] + fn the_newest_hover_preview_goes_first_then_the_oldest_request() { + let request = |key: &str, hover| PreviewRequest { key: key.into(), preview: ShelfPreview::Material("steel"), size_px: 8, hover }; + let mut queue: std::collections::VecDeque<_> = + [request("thumbnail 1", false), request("old hover", true), request("thumbnail 2", false), request("new hover", true)].into(); + + let order: Vec = std::iter::from_fn(|| next_request(&mut queue)).map(|r| r.key).collect(); + assert_eq!(order, ["new hover", "old hover", "thumbnail 1", "thumbnail 2"]); + } +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs new file mode 100644 index 00000000..5c174cdd --- /dev/null +++ b/crates/ui-egui/src/properties_popup.rs @@ -0,0 +1,79 @@ +//! The Properties panel's contents in a popup at the cursor: a right click in the 3D or 2D view opens it + +use egui::{PointerButton, Pos2, Rect, Ui}; + +use crate::TextureCraftApp; +use crate::state::Mode; +use crate::theme::Tokens; + +/// The popup's width, about the docked Properties panel's +const PROPERTIES_POPUP_WIDTH: f32 = 300.0; + +/// Share of the view's height the popup fills before its contents scroll +const PROPERTIES_POPUP_MAX_HEIGHT_SHARE: f32 = 0.7; + +/// Gap the popup keeps from the view's edges, so its border stays visible beside a split line +const PROPERTIES_POPUP_VIEW_MARGIN: f32 = 4.0; + +/// The Properties popup over a view +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PropertiesPopup { + /// Shown with its top-left corner at `at`, kept inside the view `bounds` + Open { at: Pos2, bounds: Rect }, + /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it + Closing, +} + +/// The popup's area, whose rect egui remembers between frames +pub fn area_id() -> egui::Id { + egui::Id::unique("properties_popup") +} + +/// Opens the popup on a plain right click in a view; right drags and modified clicks keep their gestures +pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, view: Rect, gesture_key_held: bool) { + let free = app.ui.mode == Mode::Painting + && app.properties_popup.is_none() + && !app.session.stroke_active() + && app.placing_decal.is_none() + && !gesture_key_held + && !crate::viewport::focus_picking(ui.ctx()) + && ui.input(|input| input.modifiers.is_none()); + if !free || !response.clicked_by(PointerButton::Secondary) { + return; + } + + if let Some(at) = response.interact_pointer_pos() { + app.properties_popup = Some(PropertiesPopup::Open { at, bounds: view }); + } +} + +/// Draws the open popup and closes it on a press outside it or when the app leaves Painting +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let (any_down, pressed_at) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()))); + match app.properties_popup { + _ if app.ui.mode != Mode::Painting => app.properties_popup = None, + Some(PropertiesPopup::Closing) if !any_down => app.properties_popup = None, + Some(PropertiesPopup::Open { .. }) => { + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))); + // A press in one of the popup's own dropdowns lands outside its area + if outside && !egui::Popup::is_any_open(ctx) { + app.properties_popup = Some(PropertiesPopup::Closing); + } + } + _ => {} + } + + let Some(PropertiesPopup::Open { at, bounds }) = app.properties_popup else { return }; + let tokens = Tokens::get(ctx); + egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + ui.set_width(PROPERTIES_POPUP_WIDTH); + // The area's remembered size would otherwise cap the scroll height + ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); + // A floating bar would cover the sliders' right-aligned values + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt("properties_popup_scroll").show(ui, |ui| crate::dock::properties_contents(app, ui)); + }); + }); +} diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 8228f51a..80248a32 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -611,11 +611,14 @@ fn save(app: &mut TextureCraftApp) { let name = format!("{}_render.png", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); #[cfg(not(target_arch = "wasm32"))] { - let Some(path) = rfd::FileDialog::new().add_filter(tr("PNG image"), &["png"]).set_file_name(name).save_file() else { return }; - match std::fs::write(&path, png) { - Ok(()) => app.toast(trf("Saved {path}", &[("path", &path.display())]), false), - Err(e) => app.toast(trf("Couldn't save the render: {error}", &[("error", &e)]), true), - } + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::save().filter(tr("PNG image"), &["png"]).file_name(name), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + match std::fs::write(path, &png) { + Ok(()) => app.toast(trf("Saved {path}", &[("path", &path.display())]), false), + Err(e) => app.toast(trf("Couldn't save the render: {error}", &[("error", &e)]), true), + } + }); } #[cfg(target_arch = "wasm32")] match crate::web_files::download(&name, &png) { diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs new file mode 100644 index 00000000..5b119c2f --- /dev/null +++ b/crates/ui-egui/src/resource_picker.rs @@ -0,0 +1,126 @@ +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name + +use egui::{Id, Response, Stroke, Ui}; + +use crate::i18n::tr; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +/// Four shelf tiles and the scrollbar +const PICKER_WIDTH: f32 = 320.0; +/// The grid's height, fixed so the popup keeps its place while searching +const PICKER_HEIGHT: f32 = 340.0; +const CURRENT_OUTLINE_WIDTH: f32 = 1.5; +const TILE_ROUNDING: f32 = 3.0; + +/// Opens the picker `popup_id` with an empty, focused search field, or closes it +pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { + if egui::Popup::is_id_open(ctx, popup_id) { + egui::Popup::close_id(ctx, popup_id); + return; + } + + egui::Popup::open_id(ctx, popup_id); + ctx.data_mut(|data| { + data.insert_temp(search_id(popup_id), String::new()); + data.insert_temp(focus_id(popup_id), true); + }); +} + +/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) +pub(crate) fn show( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + current: Option<&str>, + items: impl FnOnce(&mut Thumbs) -> Vec, + preview: impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let ctx = slot.ctx.clone(); + if !egui::Popup::is_id_open(&ctx, popup_id) { + return None; + } + + let items = items(thumbs); + let mut picked = None; + egui::Popup::from_response(slot) + .id(popup_id) + .open_memory(None) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::BOTTOM_END) + .width(PICKER_WIDTH) + .show(|ui| { + ui.set_width(PICKER_WIDTH); + let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let query = search_field(ui, popup_id, just_opened); + egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { + // A search that leaves few tiles must not shrink the popup, or egui moves it + ui.set_min_height(PICKER_HEIGHT); + picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + }); + }); + + if picked.is_some() { + egui::Popup::close_id(&ctx, popup_id); + } + picked +} + +/// The search field, focused the frame the picker opens; returns the lowercase query +fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { + let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); + let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text(tr("Search")).desired_width(f32::INFINITY)); + if just_opened { + field.request_focus(); + } + + let query = search.trim().to_lowercase(); + ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); + query +} + +/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked +fn grid( + ui: &mut Ui, + thumbs: &mut Thumbs, + items: &[ResourcePickerItem], + query: &str, + current: Option<&str>, + reveal_current: bool, + preview: &impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let tk = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); + let mut picked = None; + for group in shelf::categories(&shown, |item| item.group) { + shelf::header(ui, group); + shelf::tiles(ui, |ui| { + for item in shown.iter().filter(|item| item.group == group) { + let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); + if current == Some(item.id) { + if reveal_current { + response.scroll_to_me(Some(egui::Align::Center)); + } + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(item.id); + } + } + }); + } + picked +} + +/// Where the picker keeps its search text +fn search_id(popup_id: Id) -> Id { + popup_id.with("search") +} + +/// Set while the picker waits for its first frame open +fn focus_id(popup_id: Id) -> Id { + popup_id.with("focus") +} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs new file mode 100644 index 00000000..5b9e8071 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -0,0 +1,9 @@ +//! One choice offered by a resource picker + +/// A resource the picker offers: its id, translated label and group, and its thumbnail +pub(crate) struct ResourcePickerItem { + pub id: &'static str, + pub label: &'static str, + pub group: &'static str, + pub thumbnail: Option, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index f2aaeb65..05103100 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -11,7 +11,9 @@ use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; +use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::materials::MATERIALS; +use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -19,9 +21,32 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; +/// A shelf tile's size in points +const TILE_WIDTH: f32 = 72.0; +const TILE_HEIGHT: f32 = 86.0; +/// Corner radius of a tile's hover and selection highlights, in points +const TILE_ROUNDING: f32 = 3.0; +/// The thumbnail's size in a tile and its center below the tile's top, in points +const THUMBNAIL_SIZE: f32 = 56.0; +const THUMBNAIL_CENTER_Y: f32 = 32.0; +/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color +const LOADING_ICON_SCALE: f32 = 0.9; +const LOADING_ICON_OPACITY: f32 = 0.5; +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points +const LABEL_FONT_SIZE: f32 = 9.5; +const LABEL_GAP: f32 = 3.0; +const LABEL_MARGIN: f32 = 4.0; +/// The hover preview's size and its gap above the label, in points +const BIG_PREVIEW_SIZE: f32 = 256.0; +const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; +/// Dwell in seconds before rendering, shorter than the popup delay +const BIG_PREVIEW_DWELL: f32 = 0.1; + #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum Tab { Materials, @@ -119,11 +144,27 @@ pub enum DropZone { Brush, /// The 2D view: alphas and materials. View2d, - /// The 3D view: alphas, materials and textures (placed as decals where they drop). + /// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop). View3d, } -/// Highlight accepted shelf assets on hover and apply them on drop +/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to +pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + response.dnd_hover_payload::().filter(|drag| drag.asset.is_material())?; + set_under_pointer(app, ui, response) +} + +/// The texture set of the surface under the pointer in the 3D view `response` +fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + let local_position = ui.input(|input| input.pointer.interact_pos())? - response.rect.min; + app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport) +} + +/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`]) pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { if app.ui.mode != crate::state::Mode::Painting { return; @@ -136,54 +177,64 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag)) { + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material(); + if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } + let pointer = ui.input(|input| input.pointer.interact_pos()); - if let Some(drag) = dnd_release::(response) - && accepts(&drag) - { - match (&drag.asset, pointer) { - (Asset::Texture(name), Some(position)) => { - let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); - app.run( - "layer.add.decal", - json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]}), - ); - } - (asset, _) => apply(app, asset), + let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; + + match (&drag.asset, pointer) { + (Asset::Texture(name), Some(position)) => { + let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); + app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]})); } + // The background takes nothing + (asset, _) if onto_set(asset) => { + let Some(ts) = set_under_pointer(app, ui, response) else { return }; + + if app.run("textureSet.select", json!({"ts": ts})).is_some() { + apply(app, asset); + } + } + (asset, _) => apply(app, asset), } } -/// The Assets panel body (a dock tab). +/// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); let mut tab = app.ui.shelf_tab.min(TABS.len() - 1); let searching = !app.ui.shelf_filter.is_empty(); + ui.horizontal_wrapped(|ui| { + let button_size = ui.spacing().interact_size.y; ui.spacing_mut().item_spacing = vec2(2.0, 2.0); for (i, (_, icon, label)) in TABS.iter().enumerate() { - if icon_button(ui, icon, tr(label), i == tab && !searching, 24.0).clicked() { + if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() { tab = i; app.ui.shelf_filter.clear(); } } }); app.ui.shelf_tab = tab; + ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY)); }); ui.add_space(4.0); + let filter = app.ui.shelf_filter.to_lowercase(); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - // Searching shows matches from every tab, each under its tab's name. + // Searching shows matches from every tab, each under its tab's name for (i, (t, _, title)) in TABS.iter().enumerate() { if filter.is_empty() && i != tab { continue; } + let title = tr(title); match t { Tab::Materials => materials(app, ui, &ctx, &filter, false, title), @@ -216,7 +267,7 @@ fn drag_preview(ctx: &egui::Context) { p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); } -fn matches(filter: &str, texts: &[&str]) -> bool { +pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -225,13 +276,13 @@ fn title(ui: &mut Ui, text: &str) { ui.label(RichText::new(text).strong().color(tk.text_strong)); } -fn header(ui: &mut Ui, text: &str) { +pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); ui.label(RichText::new(text).size(11.0).color(tk.text_dim)); } -fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { +pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); body(ui); @@ -240,7 +291,7 @@ fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { } /// The distinct categories of `items`, in order of first appearance. -fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { +pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { let mut out: Vec<&'static str> = Vec::new(); for c in items.iter().map(category) { if !out.contains(&c) { @@ -250,25 +301,22 @@ fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st out } -/// Built-in materials (or smart materials), grouped by category. +/// Built-in materials or smart materials, grouped by category fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = MATERIALS.iter().filter(|m| m.smart == smart && matches(filter, &[m.label, m.category, m.id])).collect(); + let shown: Vec<_> = + MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); if shown.is_empty() { return; } + title(ui, name); - for cat in categories(&shown, |m| m.category) { - header(ui, cat); + for category in categories(&shown, |material| material.category) { + header(ui, category); tiles(ui, |ui| { - for m in shown.iter().filter(|m| m.category == cat) { - let tex = app.thumbs.material(ctx, m.id); - let hint = if m.smart { - tr("Add the smart material folder above the selected layer (or drag it into the layer stack)") - } else { - tr("Add a fill layer with this material above the selected layer (or drag it into the layer stack)") - }; - let asset = Asset::Material(m.id); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + for material in shown.iter().filter(|material| material.category == category) { + let texture = app.thumbs.material(ctx, material.id); + let asset = Asset::Material(material.id); + if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -335,8 +383,7 @@ fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt for m in shown { let tex = app.thumbs.smart_mask(ctx, m.id); let asset = Asset::SmartMask(m.id); - let hint = tr("Replace the selected layer's mask with this smart mask (or drag it onto a layer)"); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -356,13 +403,8 @@ fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for f in shown.iter().filter(|f| f.group == group) { let tex = app.thumbs.filter(ctx, f.id); - let hint = if f.mask { - tr("Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)") - } else { - tr("Add this finish to the selected layer's roughness and height (or drag it onto a layer)") - }; let asset = Asset::Filter(f.id); - if tile(ui, tex.as_ref(), tr(f.label), hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { apply(app, &asset); } } @@ -381,7 +423,7 @@ fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for p in shown.iter().filter(|p| p.category == cat) { let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, tex.as_ref(), p.label, tr("Use this brush (keeps its size)"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { app.run("brush.preset.apply", json!({"preset": p.id})); } } @@ -462,9 +504,9 @@ fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, fi for &a in shown.iter().filter(|a| a.category == cat) { let tex = app.thumbs.alpha(ctx, a); let asset = Asset::Alpha(&a.id); - let r = tile(ui, tex.as_ref(), &a.label, tr("Use as the brush alpha (or drag it onto the viewport or brush properties)"), Some(&asset)); + let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } if r.clicked() { apply(app, &asset); @@ -483,7 +525,7 @@ fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt tiles(ui, |ui| { for k in shown { let tex = app.thumbs.procedural(ctx, k); - if tile(ui, tex.as_ref(), tr(k.label()), tr("Add a fill layer using this pattern"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { app.run("layer.add.fill", json!({"name": k.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); } @@ -524,9 +566,11 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for name in names { let Some(img) = app.session.images.get(&name).cloned() else { continue }; + let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); - let r = tile(ui, Some(&tex), &name, tr("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)"), Some(&asset)); + let preview = || ShelfPreview::Image(name.clone(), img); + let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); if r.clicked() { apply(app, &asset); } @@ -544,33 +588,85 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: }); } -/// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. -fn tile(ui: &mut Ui, tex: Option<&egui::TextureHandle>, label: &str, hint: &str, drag: Option<&Asset>) -> egui::Response { +/// Asset tile with optional dragging and a larger hover preview +pub(crate) fn tile( + ui: &mut Ui, + thumbs: &mut Thumbs, + tex: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, +) -> egui::Response { let tk = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(72.0, 86.0), sense); + let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag && resp.drag_started() { resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } - let p = ui.painter(); + + let painter = ui.painter(); if resp.hovered() || resp.dragged() { - p.rect_filled(rect, 3.0, tk.row_hover); + painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let img = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 32.0), vec2(56.0, 56.0)); - match tex { - Some(t) => { - p.image(t.id(), img, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(painter, tex, image_rect, &tk); + let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + + let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; + resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) +} + +/// Start rendering during the popup delay once the pointer rests +fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { + let ctx = ui.ctx(); + let preview = preview(); + let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + + // High display scales must respect the orb camera's allocation limit + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + + // Scrolling moves tiles beneath a stationary pointer + let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); + if idle_seconds >= BIG_PREVIEW_DWELL { + return thumbs.big(ctx, preview, size_px); + } + + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - idle_seconds); + thumbs.rendered_big(ctx, &preview, size_px) +} + +/// `texture` drawn into `rect`, or a dim loading icon while it renders +fn thumbnail(painter: &egui::Painter, texture: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - p.circle_filled(img.center(), img.width() * 0.45, tk.row_hover); + let font = egui::FontId::proportional(rect.width() * LOADING_ICON_SCALE); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROWS_CLOCKWISE, + font, + tk.text_dim.gamma_multiply(LOADING_ICON_OPACITY), + ); } } - let galley = p.layout(label.to_string(), egui::FontId::proportional(9.5), tk.text, rect.width() - 4.0); - p.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, img.bottom() + 3.0), galley, tk.text); - resp.on_hover_ui(|ui| { - ui.label(format!("{label}: {hint}")); - }) +} + +/// Use the thumbnail as a placeholder until the hover preview arrives +fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { + let tk = Tokens::get(ui.ctx()); + ui.set_max_width(BIG_PREVIEW_SIZE); + ui.vertical_centered(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(BIG_PREVIEW_SIZE, BIG_PREVIEW_SIZE), Sense::hover()); + thumbnail(ui.painter(), big.or(small), rect, &tk); + ui.add_space(BIG_PREVIEW_LABEL_GAP); + ui.label(label); + }); } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs new file mode 100644 index 00000000..b512f250 --- /dev/null +++ b/crates/ui-egui/src/shelf_preview.rs @@ -0,0 +1,120 @@ +//! Shelf assets and their preview renderers + +use std::sync::Arc; + +use egui::ColorImage; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::materials; +use texturecraft_engine::paint::BrushSettings; +use texturecraft_engine::paint::alphas::LibraryAlpha; +use texturecraft_engine::paint::presets::BrushPreset; +use texturecraft_engine::preview; + +use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; + +/// The asset a shelf tile previews +pub enum ShelfPreview { + /// A built-in plain material on a sphere + Material(&'static str), + /// Smart material rendering requires the worker's baked orb + SmartMaterial(&'static str), + /// Smart mask rendering requires the worker's baked orb + SmartMask(&'static str), + /// A library filter on a sample material on a sphere + Filter(&'static str), + /// A procedural pattern as a grayscale swatch + Procedural(ProceduralKind), + /// A library brush alpha, white on black + Alpha(&'static LibraryAlpha), + /// A brush preset's stroke along an S curve + Brush(&'static BrushPreset), + /// An image resource by name + Image(String, Arc), +} + +impl ShelfPreview { + /// Smart materials preview on the orb, plain materials on a sphere + pub fn material(id: &'static str) -> ShelfPreview { + match materials::find(id) { + Some(found) if found.smart => ShelfPreview::SmartMaterial(id), + Some(_) | None => ShelfPreview::Material(id), + } + } + + /// The cache key of the preview (one per asset) + pub fn key(&self) -> String { + match self { + ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), + ShelfPreview::SmartMask(id) => format!("mask:{id}"), + ShelfPreview::Filter(id) => format!("filter:{id}"), + ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), + ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), + ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::Image(name, _) => format!("image:{name}"), + } + } + + /// Render a `size²` image; unknown assets return None + /// Smart masks and smart materials return None here because their bake belongs to the worker + pub fn image(&self, size: usize) -> Option { + match self { + ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), + ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), + ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), + ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + } + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::filter_lib::FILTERS; + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::paint::alphas; + use texturecraft_engine::paint::presets::PRESETS; + + use super::*; + + /// The hover preview's size at 100 % scale + const BIG_PX: usize = 256; + + #[test] + fn every_tab_renders_a_big_preview() { + let image = ImageRes { width: 4, height: 2, rgba: vec![[0.8, 0.4, 0.2, 1.0]; 8], srgb: true }; + let previews = [ + ShelfPreview::Material(MATERIALS[0].id), + ShelfPreview::Filter(FILTERS[0].id), + ShelfPreview::Procedural(ProceduralKind::ALL[0]), + ShelfPreview::Alpha(&alphas::library()[0]), + ShelfPreview::Brush(&PRESETS[0]), + ShelfPreview::Image("image".into(), Arc::new(image)), + ]; + for preview in previews { + let key = preview.key(); + let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); + assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); + assert!(image.pixels.iter().any(|color| color.a() > 0 && color.r().max(color.g()).max(color.b()) > 0), "{key}: something shows"); + } + + let finite = |samples: Vec>| { + samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)) + }; + assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); + assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb"); + assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb"); + } + + #[test] + fn smart_materials_and_only_they_preview_on_the_orb() { + for material in MATERIALS { + let on_the_orb = matches!(ShelfPreview::material(material.id), ShelfPreview::SmartMaterial(_)); + assert_eq!(on_the_orb, material.smart, "{}", material.id); + } + } +} diff --git a/crates/ui-egui/src/soft_box.rs b/crates/ui-egui/src/soft_box.rs new file mode 100644 index 00000000..9c2c8391 --- /dev/null +++ b/crates/ui-egui/src/soft_box.rs @@ -0,0 +1,48 @@ +//! A soft box of the smart material preview studio (see [`crate::material_preview_image`]) + +use texturecraft_engine::geom::glam::Vec3; + +/// How much roughness widens a soft box's reflection, in radians per unit of roughness +const BLUR_RAD_PER_ROUGHNESS: f32 = 1.1; +/// A reflected disc's soft edge: this share of its reflected radius plus a minimum in radians +const EDGE_SOFTNESS: f32 = 0.25; +const EDGE_SOFTNESS_MIN_RAD: f32 = 0.02; +/// The share of a soft box's light that reaches a diffuse surface facing it +const DIFFUSE_SHARE: f32 = 0.9; + +/// A round area light far away, seen as a disc in reflections +pub struct SoftBox { + /// Direction towards the light in view space (+X right, +Y up, +Z towards the viewer), not normalized + pub direction: [f32; 3], + /// Angular radius of the disc in radians + pub radius_rad: f32, + /// Brightness of the disc (linear) + pub intensity: f32, +} + +impl SoftBox { + /// The unit direction towards the light + pub fn unit_direction(&self) -> Vec3 { + Vec3::from(self.direction).normalize_or_zero() + } + + /// The light seen along unit direction `view` by a surface of `roughness`: rougher surfaces see the disc wider and dimmer (the same light spread out) + pub fn reflected(&self, view: Vec3, roughness: f32) -> f32 { + let reflected_radius_rad = self.radius_rad.hypot(roughness * BLUR_RAD_PER_ROUGHNESS); + let angle_rad = view.dot(self.unit_direction()).clamp(-1.0, 1.0).acos(); + let edge_width_rad = EDGE_SOFTNESS * reflected_radius_rad + EDGE_SOFTNESS_MIN_RAD; + let inside = smoothstep((reflected_radius_rad - angle_rad) / edge_width_rad); + self.intensity * (self.radius_rad / reflected_radius_rad).powi(2) * inside + } + + /// The light reaching a diffuse surface with unit normal `normal` + pub fn diffuse(&self, normal: Vec3) -> f32 { + self.intensity * self.radius_rad * self.radius_rad * DIFFUSE_SHARE * normal.dot(self.unit_direction()).max(0.0) + } +} + +/// Smooth 0..=1 ramp of `t` (clamped), flat at both ends +pub fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 45117787..56ef767d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -158,6 +158,12 @@ pub struct NewProject { /// Name typed to save the current project's settings as a template. #[serde(skip)] pub template_name: String, + /// Normal map format of the project and its imported normal maps; None keeps the template's + #[serde(default)] + pub normal_format: Option, + /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) + #[serde(skip)] + pub baked_maps: Vec, } fn default_template() -> String { @@ -174,6 +180,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } @@ -239,10 +247,20 @@ fn default_export_dir() -> String { } } +/// The split layout starts with the 3D and 2D views at equal width +fn default_split_ratio() -> f32 { + 0.5 +} +/// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` +const BAKE_LAYOUT_VERSION: u32 = 1; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub mode: Mode, pub layout: ViewLayout, + /// The 3D view's share of the viewport width in the split layout + #[serde(default = "default_split_ratio")] + pub split_ratio: f32, /// The docked, tabbed and floating panels around the viewport. #[serde(default)] pub dock: Dock, @@ -250,6 +268,12 @@ pub struct UiState { pub(crate) inactive_mode_dock: Dock, #[serde(default)] pub(crate) dock_is_baking: bool, + /// The bake layout version the bake dock was saved with; 0 before versions existed. + #[serde(default)] + pub(crate) bake_layout_version: u32, + /// The mesh map whose settings Mesh Map Settings shows; `None` follows the first enabled map. + #[serde(default)] + pub(crate) selected_baked_map: Option, /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, @@ -287,10 +311,16 @@ pub struct UiState { /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) + #[serde(default)] + pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } impl UiState { + /// Replace an outdated or unreadable saved bake dock by the bake layout, then give the mode its dock pub(crate) fn sync_mode_dock(&mut self) { + self.reset_outdated_bake_dock(); + let baking = self.mode == Mode::Baking; if baking != self.dock_is_baking { std::mem::swap(&mut self.dock, &mut self.inactive_mode_dock); @@ -298,6 +328,17 @@ impl UiState { } } + /// Replace a bake dock saved with an older bake layout, or one that could not be read, by the bake default + fn reset_outdated_bake_dock(&mut self) { + let bake_dock = if self.dock_is_baking { &mut self.dock } else { &mut self.inactive_mode_dock }; + if self.bake_layout_version >= BAKE_LAYOUT_VERSION && !bake_dock.replaced_unreadable() { + return; + } + + *bake_dock = Dock::for_baking(); + self.bake_layout_version = BAKE_LAYOUT_VERSION; + } + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export /// settings and recent files. pub fn adopt_layout(&mut self, layout: UiState) { @@ -317,9 +358,12 @@ impl Default for UiState { UiState { mode: Mode::Painting, layout: ViewLayout::Split, + split_ratio: default_split_ratio(), dock: Dock::default(), inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, + bake_layout_version: BAKE_LAYOUT_VERSION, + selected_baked_map: None, hide_ui: false, windows: Windows::default(), uv_zoom: 1.0, @@ -339,6 +383,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } } @@ -371,6 +416,52 @@ mod tests { assert_eq!(Prefs::default().data_folder, "", "the default is no choice"); } + #[test] + fn a_bake_dock_saved_before_the_bake_layout_version_loads_the_current_bake_layout() { + let old_bake_dock = serde_json::json!({"version": 2, "layout": {"root": {"Split": {"axis": "Horizontal", "size": {"FixedFirst": 320.0}, + "first": {"Tabs": {"panels": ["TextureSetList", "BakeSettings", "BakeMaps"], "active": 0}}, + "second": {"Tabs": {"panels": ["Viewport"], "active": 0}}}}, "floating": []}}); + for dock_is_baking in [false, true] { + let mut painting_dock = Dock::default(); + painting_dock.close(crate::docking::Panel::Assets); + let (bake_field, painting_field) = if dock_is_baking { ("dock", "inactive_mode_dock") } else { ("inactive_mode_dock", "dock") }; + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.remove("bake_layout_version"); + fields.insert("dock_is_baking".into(), serde_json::json!(dock_is_baking)); + fields.insert("mode".into(), serde_json::to_value(if dock_is_baking { Mode::Baking } else { Mode::Painting }).unwrap()); + fields.insert(bake_field.into(), old_bake_dock.clone()); + fields.insert(painting_field.into(), serde_json::to_value(&painting_dock).unwrap()); + + let mut ui: UiState = serde_json::from_value(saved).unwrap(); + let loaded_bake_dock = if dock_is_baking { &ui.dock } else { &ui.inactive_mode_dock }; + assert!(!loaded_bake_dock.is_open(crate::docking::Panel::MeshMapBakers), "the old layout loads without the bakers list"); + + ui.sync_mode_dock(); + let (bake_dock, painting) = if dock_is_baking { (&ui.dock, &ui.inactive_mode_dock) } else { (&ui.inactive_mode_dock, &ui.dock) }; + assert_eq!(*bake_dock, Dock::for_baking()); + assert_eq!(*painting, painting_dock, "the painting layout is kept"); + + let mut reloaded: UiState = serde_json::from_value(serde_json::to_value(&ui).unwrap()).unwrap(); + reloaded.sync_mode_dock(); + assert_eq!(reloaded, ui, "a current layout is not reset again"); + } + } + + #[test] + fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { + for mode in [Mode::Painting, Mode::Baking] { + let mut ui = UiState { mode, ..UiState::default() }; + ui.sync_mode_dock(); + + let mut restarted = crate::ui_state_store::tests::restart(&ui); + restarted.sync_mode_dock(); + let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; + assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); + assert!(bake_dock.is_open(crate::docking::Panel::MeshMapBakers), "{mode:?}"); + } + } + #[test] fn older_saved_state_without_a_dock_loads_the_default_layout() { let mut v = serde_json::to_value(UiState::default()).unwrap(); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..d0067411 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,95 +1,54 @@ -//! Thumbnails: shaded material spheres, smart mask spheres, procedural swatches and brush alpha -//! previews, rendered on the CPU into cached egui textures (no image assets). New shelf -//! thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a frame. +//! Shelf and brush preview caches +//! Small synchronous renders are limited per frame +//! Smart masks, smart materials and hover previews use [`PreviewWorker`] -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; -use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::texel::linear_to_srgb; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). -const PER_FRAME: usize = 2; -/// Shelf sphere thumbnail size in pixels. -const SPHERE_PX: usize = 72; +use crate::preview_image::{aces, image_preview, shade}; +use crate::preview_request::PreviewRequest; +use crate::preview_worker::PreviewWorker; +use crate::shelf_preview::ShelfPreview; +use crate::worker_preview::WorkerPreview; +/// UI-thread renders per frame at most; a web worker request uses the whole budget +const PER_FRAME: usize = 2; +/// Shelf sphere and smart mask thumbnail size in pixels +const SPHERE_PX: usize = 72; +/// Shelf procedural swatch size in pixels +const PROCEDURAL_PX: usize = 56; +/// Shelf alpha and brush stroke swatch size in pixels +const SWATCH_PX: usize = 64; +/// Image resource preview size in pixels +const IMAGE_PX: usize = 64; +/// Big hover previews kept at most (the least recently shown go first) +const BIG_PREVIEWS_KEPT: usize = 32; + +/// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by key (`mat:`, `mask:`, `filter:`, `proc:`, `alpha:`, - /// `brush:`). + /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, images: HashMap, - /// (frame, thumbnails rendered in it). + /// (frame, thumbnails rendered in it) budget: (u64, usize), -} - -fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { - let l = [0.45f32, 0.7, 0.55]; - let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); - let l = l.map(|v| v / len); - let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); - let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. - let h = [l[0], l[1], l[2] + 1.0]; - let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); - let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); - let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; - let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. - let ry = 2.0 * ndv * n[1]; - let w = 0.06 + rough * 0.9; - let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); - let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); - let env = sharp + (0.28 - sharp) * (rough * rough); - let fres = (1.0 - ndv).powi(5); - let sky = 0.35 + 0.25 * n[1]; - let mut out = [0.0; 3]; - for k in 0..3 { - let f0 = 0.04 + (base[k] - 0.04) * metal; - let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; - let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); - out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; - } - out -} - -fn aces(x: f32) -> f32 { - let v = x * 0.6; - ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) -} - -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. -pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; - let (x, y) = (i % size, i / size); - let c = s.height; - // Central differences (image y points down). - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); - } - img + /// Renders the orb thumbnails and the big previews + worker: PreviewWorker, + /// Worker-rendered previews by [`worker_key`] + rendered: HashMap, + /// The keys of the big previews in `rendered`, least recently shown first + big_shown: VecDeque, + /// The frame that last took in the worker's results + received_in_pass: u64, } impl Thumbs { - /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px). + /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { let key = format!("stencil:{name}"); if let Some(t) = self.images.get(&key) { @@ -110,145 +69,158 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, nearest downsample). + /// Cached preview of an image resource (64 px, letterboxed) pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); } - let n = 64usize; - // Letterboxed to keep its proportions, over black where it is transparent. - let aspect = img.width as f32 / img.height.max(1) as f32; - let (sx, sy) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; - let mut ci = ColorImage::filled([n, n], Color32::BLACK); - for y in 0..n { - for x in 0..n { - let (u, v) = (((x as f32 + 0.5) / n as f32 - 0.5) * sx + 0.5, ((y as f32 + 0.5) / n as f32 - 0.5) * sy + 0.5); - if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { - continue; - } - let s = img.sample(u, v); - let enc = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * s[3].clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * s[3]) * 255.0) as u8 }; - ci.pixels[y * n + x] = Color32::from_rgb(enc(s[0]), enc(s[1]), enc(s[2])); - } - } - let t = ctx.load_texture(format!("res_{name}"), ci, TextureOptions::LINEAR); + let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR); self.images.insert(name.to_string(), t.clone()); t } - /// A cached shelf thumbnail, rendering it with `render` if this frame's budget allows (None - /// until then; a repaint is requested so it follows shortly). - fn shelf(&mut self, ctx: &egui::Context, key: String, render: impl FnOnce() -> ColorImage) -> Option { - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + /// Render within the frame budget; deferred thumbnails request a repaint + fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = preview.key(); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); } + + if !self.spend_budget(ctx, 1) { + return None; + } + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Spend `renders` of this frame's UI-thread budget; when it is spent, request a repaint + fn spend_budget(&mut self, ctx: &egui::Context, renders: usize) -> bool { let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); } - if self.budget.1 >= PER_FRAME { + if self.budget.1 + renders > PER_FRAME { ctx.request_repaint(); - return None; + return false; } - self.budget.1 += 1; - let t = ctx.load_texture(format!("thumb_{key}"), render(), TextureOptions::LINEAR); - self.shelf.insert(key, t.clone()); - Some(t) + + self.budget.1 += renders; + true } - /// Sphere thumbnail of built-in material `id`. - pub fn material(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) + /// Request once per asset and size; return None while pending or after failure + /// Hover requests take priority in the native worker + fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { + self.receive(ctx); + + let key = worker_key(&preview, size_px); + if !self.rendered.contains_key(&key) && self.may_request(ctx) { + let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); + self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); + } + + self.ready(&key) } - /// Sphere thumbnail of smart mask `id`: white where the mask applies, over dark gray. - pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mask:{id}"), || { - let px = preview::smart_mask(id, SPHERE_PX).unwrap_or_default(); - let samples: Vec> = - px.iter().map(|m| m.map(|m| Sample { base: [0.04 + 0.76 * m; 3], metallic: 0.0, roughness: 0.6, height: 0.0 })).collect(); - sphere_image(SPHERE_PX, &samples) - }) + /// Native workers take every request; the web renders inline, so it takes one per frame + fn may_request(&mut self, ctx: &egui::Context) -> bool { + !cfg!(target_arch = "wasm32") || self.spend_budget(ctx, PER_FRAME) } - /// Sphere thumbnail of library filter `id` applied to a sample material. - pub fn filter(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("filter:{id}"), || sphere_image(SPHERE_PX, &preview::filter(id, SPHERE_PX).unwrap_or_default())) + /// The worker-rendered preview under `key` if it arrived + fn ready(&self, key: &str) -> Option { + match self.rendered.get(key) { + Some(WorkerPreview::Ready(t)) => Some(t.clone()), + Some(WorkerPreview::Rendering | WorkerPreview::Failed) | None => None, + } } - /// Grayscale swatch of procedural `k`. - pub fn procedural(&mut self, ctx: &egui::Context, k: ProceduralKind) -> Option { - use texturecraft_engine::compose::pattern::{Coords, procedural}; - use texturecraft_engine::core::{Procedural, Projection}; - use texturecraft_engine::geom::glam::{Vec2, Vec3}; - self.shelf(ctx, format!("proc:{k:?}"), || { - let n = 56usize; - let pr = Procedural { scale: 3.0, ..Procedural::new(k) }; - let mut img = ColorImage::filled([n, n], Color32::BLACK); - for (i, px) in img.pixels.iter_mut().enumerate() { - let uv = Vec2::new(((i % n) as f32 + 0.5) / n as f32, ((i / n) as f32 + 0.5) / n as f32); - let v = procedural(&pr, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); - *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + /// Poll once per pass and discard results evicted from the cache + fn receive(&mut self, ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + if self.received_in_pass == pass { + return; + } + self.received_in_pass = pass; + + for (key, image) in self.worker.poll() { + let Some(entry) = self.rendered.get_mut(&key) else { continue }; + + *entry = match image { + Some(image) => WorkerPreview::Ready(ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR)), + None => WorkerPreview::Failed, + }; + } + + // A stopped worker never answers the rest + if self.worker.is_stopped() { + for entry in self.rendered.values_mut().filter(|e| matches!(e, WorkerPreview::Rendering)) { + *entry = WorkerPreview::Failed; } - img - }) + } } - /// White-on-black swatch of library alpha `a`. - pub fn alpha(&mut self, ctx: &egui::Context, a: &alphas::LibraryAlpha) -> Option { - self.shelf(ctx, format!("alpha:{}", a.id), || { - let n = 64usize; - ColorImage::new([n, n], a.render(n, 2).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect()) - }) + /// Request a hover preview and evict the least recently shown beyond the cache limit + pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = worker_key(&preview, size_px); + self.big_shown.retain(|k| *k != key); + self.big_shown.push_back(key); + while self.big_shown.len() > BIG_PREVIEWS_KEPT { + if let Some(oldest) = self.big_shown.pop_front() { + self.rendered.remove(&oldest); + } + } + + self.worker_rendered(ctx, preview, size_px, true) } - /// A brush preset's stroke along an S curve. - pub fn brush_preset(&mut self, ctx: &egui::Context, p: &BrushPreset) -> Option { - self.shelf(ctx, format!("brush:{}", p.id), || stroke_preview(&p.applied(&BrushSettings::default()), 64)) + /// The big preview of `preview` if the worker already rendered it (requests nothing) + pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { + self.receive(ctx); + self.ready(&worker_key(preview, size_px)) + } + + /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres + pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + match ShelfPreview::material(id) { + preview @ ShelfPreview::SmartMaterial(_) => self.worker_rendered(ctx, preview, SPHERE_PX, false), + preview => self.shelf(ctx, preview, SPHERE_PX), + } + } + + /// Smart mask thumbnail; None until the worker returns it + pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) + } + + /// Sphere thumbnail of library filter `id` applied to a sample material + pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) + } + + /// Grayscale swatch of procedural `kind` + pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { + self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) + } + + /// White-on-black swatch of library alpha `alpha` + pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { + self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) + } + + /// A brush preset's stroke along an S curve + pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { + self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. -fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); - let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; - t += 0.002; - if travelled < step { - continue; - } - travelled = 0.0; - i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); - let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); - for y in y0..y1 { - for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); - } - } - } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +/// The key of a worker-rendered preview: one per asset and size +fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { + format!("{}@{size_px}", preview.key()) } /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 2c900ed3..889d2de7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1,5 +1,4 @@ -//! The context tool bar (brush size, flow, stroke opacity, spacing, lazy mouse, symmetry, view -//! toggles), the vertical tool shelf, the right icon rail and the status bar. +//! Context controls, view and mode buttons, tool shelf, icon rail and status bar use egui::{RichText, vec2}; use egui_phosphor::regular as ic; @@ -9,10 +8,14 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::docking::Panel; use crate::i18n::{tr, trf}; -use crate::keymap::tip; +use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; -use crate::widgets::{bar_slider, icon_button}; +use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip, icon_dropdown_button, icon_dropdown_button_width}; + +const BAR_SPACING: f32 = 10.0; +const COMPACT_BAR_SPACING: f32 = 4.0; +const BAR_SEPARATOR_WIDTH: f32 = 6.0; pub fn tool_icon(t: Tool) -> &'static str { match t { @@ -28,125 +31,309 @@ pub fn tool_icon(t: Tool) -> &'static str { } } +/// Keep mode buttons visible, with painting controls scrolling as space runs out pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { - ui.horizontal_centered(|ui| { - ui.spacing_mut().item_spacing.x = 10.0; - let tool = app.session.tool.tool; - ui.label(RichText::new(tool_icon(tool)).size(15.0).color(tokens.text_strong)).on_hover_text(tool.label()); - let brush = &mut app.session.tool.brush; - match tool { - Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { - let mut size = brush.size / 0.25 * 100.0; - if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { - brush.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); - } - let mut flow = brush.flow * 100.0; - if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { - brush.flow = flow / 100.0; - } - let mut opacity = brush.opacity * 100.0; - if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { - brush.opacity = opacity / 100.0; - } - let mut spacing = brush.spacing * 100.0; - if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { - brush.spacing = spacing / 100.0; - } - ui.separator(); - let lazy_on = brush.lazy > 0.0; - if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - brush.lazy = if lazy_on { 0.0 } else { 20.0 }; - } - if lazy_on { - let mut distance = brush.lazy; - if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { - brush.lazy = distance; - } - } - ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { - brush.symmetry.x = !brush.symmetry.x; - } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { - brush.symmetry.y = !brush.symmetry.y; - } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { - brush.particles.enabled = !brush.particles.enabled; - } - if tool == Tool::Smudge { - ui.separator(); - let mut strength = app.session.tool.smudge_strength * 100.0; - if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { - app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); - } - } - if tool == Tool::Clone && app.session.tool.clone_source.is_none() { - ui.separator(); - ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); - } - if tool == Tool::Path { - ui.separator(); - path_controls(app, ui); - } - } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - for (fill_mode, icon, tip) in [ - (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), - (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), - (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), - ] { - if icon_button(ui, icon, tip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { - app.session.tool.fill_mode = fill_mode; - } - } - } - Tool::ColorPicker => { - ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); - } - Tool::GeometryMask => { - ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); - } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let button_size = ui.spacing().interact_size.y; + let mode_width = 3.0 * button_size + 2.0 * BAR_SPACING; + let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING; + // Leave room for both scroll arrows and at least one button of content + let minimum_strip_width = 3.0 * button_size + 2.0 * BAR_SPACING; + let scroll_views = + ui.available_width() < mode_width + view_buttons_width(button_size, BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; + ui.spacing_mut().item_spacing.x = if scroll_views { COMPACT_BAR_SPACING } else { BAR_SPACING }; + mode_buttons(app, ui); + + if app.ui.mode != Mode::Painting { + return; } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, 24.0).clicked() { - app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); - } - ui.separator(); - for (layout, icon, label, id) in [ - (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), - (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), - (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), app.ui.layout == layout, 24.0).clicked() { - app.ui.layout = layout; - } - } - ui.separator(); - let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, 24.0).clicked() { - let mode = if checker { "material" } else { "uvChecker" }; - app.run("viewport.view", json!({"mode": mode})); - } + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if !scroll_views { + view_buttons(app, ui); + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } + + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + scrolling_tool_controls(app, ui, &tokens, scroll_views); }); }); }); }); } -/// Path tool options and actions (top bar and properties). +/// Width of `view_buttons`, so the bar knows when to move them into the scrolling strip +fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { + // Two icons, two dropdowns, two separators and the five gaps between them + 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + 2.0 * BAR_SEPARATOR_WIDTH + 5.0 * spacing +} + +/// View buttons in a right-to-left layout, with the screenshot button at the end +fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { + app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); + } + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + projection_dropdown(app, ui); + layout_dropdown(app, ui); + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { + let mode = if checker { "material" } else { "uvChecker" }; + app.run("viewport.view", json!({"mode": mode})); + } +} + +/// The 3D/2D, 3D-only and 2D-only layouts, showing the current one's icon +fn layout_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + const LAYOUTS: [(ViewLayout, &str, &str, &str); 3] = [ + (ViewLayout::Split, ic::SQUARE_SPLIT_HORIZONTAL, "3D/2D views", "ui.layout.split"), + (ViewLayout::Only3D, ic::SPHERE, "3D view only", "ui.layout.3d"), + (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), + ]; + + let (_, icon, label, command) = LAYOUTS.iter().find(|(layout, ..)| *layout == app.ui.layout).unwrap_or(&LAYOUTS[0]); + let tooltip = tip(&app.ui.keymap, tr(label), command); + let mut chosen = None; + icon_dropdown(ui, "view_layout", icon, &tooltip, |ui| { + for (layout, icon, label, command) in LAYOUTS { + if dropdown_row(ui, icon, tr(label), shortcut_of(&app.ui.keymap, command), app.ui.layout == layout) { + chosen = Some(command); + } + } + }); + + if let Some(command) = chosen { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } +} + +/// Perspective or orthographic projection, the same setting as the Display Settings checkbox +fn projection_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let projections = [(false, ic::PERSPECTIVE, tr("Perspective")), (true, ic::CUBE, tr("Orthographic"))]; + let ortho = app.session.camera.ortho; + let (_, icon, label) = projections.iter().find(|(choice, ..)| *choice == ortho).unwrap_or(&projections[0]); + let mut chosen = None; + icon_dropdown(ui, "view_projection", icon, label, |ui| { + for (choice, icon, label) in projections { + if dropdown_row(ui, icon, label, None, ortho == choice) { + chosen = Some(choice); + } + } + }); + + if let Some(choice) = chosen.filter(|choice| *choice != ortho) { + app.run("camera.set", json!({"ortho": choice})); + } +} + +/// An icon button with a caret that opens `menu` below it, highlighted while open +fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) { + let button_size = ui.spacing().interact_size.y; + let popup_id = ui.make_persistent_id(id_salt); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id); + let mut response = icon_dropdown_button(ui, icon, tooltip, open, button_size); + if !open { + response = response.on_hover_text(tooltip); + } + + egui::Popup::menu(&response).id(popup_id).show(menu); +} + +/// One dropdown entry: icon, label and shortcut. Returns true when clicked +fn dropdown_row(ui: &mut egui::Ui, icon: &str, label: &str, shortcut: Option<&str>, selected: bool) -> bool { + let mut button = egui::Button::new(format!("{icon} {label}")).selected(selected); + if let Some(shortcut) = shortcut { + button = button.shortcut_text(shortcut); + } + + ui.add(button).clicked() +} + +/// Scroll tool controls and, in narrow viewports, the view buttons +fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { + let button_size = ui.spacing().interact_size.y; + let strip_width = ui.available_width(); + let overflow_id = egui::Id::unique("tool_controls_overflow"); + let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); + + // A positive delta moves the content right, revealing its start + let arrow_scroll_step = strip_width / 2.0; + let mut scroll_delta = 0.0; + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, button_size).clicked() { + scroll_delta = arrow_scroll_step; + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, button_size).clicked() { + scroll_delta = -arrow_scroll_step; + } + + let scroll_area = egui::ScrollArea::horizontal() + .id_salt("tool_controls") + .min_scrolled_width(0.0) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); + let output = ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + scroll_area.show(ui, |ui| { + ui.scroll_with_delta(vec2(scroll_delta, 0.0)); + ui.horizontal_centered(|ui| { + tool_controls(app, ui, tokens); + if scroll_views { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height()); + ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); + } + }); + }) + }); + + // The arrows take room from the strip, so measure the overflow against its full width + let overflows_now = output.inner.content_size.x > strip_width; + if overflows_now != overflowing { + ui.data_mut(|data| data.insert_temp(overflow_id, overflows_now)); + ui.ctx().request_repaint(); + } + }); +} + +/// Largest brush radius as a fraction of the mesh diagonal; size sliders show it as 100 +pub(crate) const MAX_BRUSH_SIZE: f32 = 0.25; + +/// Smallest brush radius as a fraction of the mesh diagonal +pub(crate) const MIN_BRUSH_SIZE: f32 = 0.0005; + +/// The selected tool's icon and its settings +fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { + const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; + const TOOL_ICON_SIZE: f32 = 15.0; + + let button_size = ui.spacing().interact_size.y; + let tool = app.session.tool.tool; + ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); + + let brush = &mut app.session.tool.brush; + match tool { + Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { + let mut size = brush.size / MAX_BRUSH_SIZE * 100.0; + if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { + brush.size = (size / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } + + let mut flow = brush.flow * 100.0; + if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { + brush.flow = flow / 100.0; + } + + let mut opacity = brush.opacity * 100.0; + if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { + brush.opacity = opacity / 100.0; + } + + let mut spacing = brush.spacing * 100.0; + if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { + brush.spacing = spacing / 100.0; + } + + ui.separator(); + let lazy_on = brush.lazy > 0.0; + if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, button_size).clicked() { + brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE_PX }; + } + if lazy_on { + let mut distance = brush.lazy; + if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { + brush.lazy = distance; + } + } + + ui.separator(); + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, button_size).clicked() { + brush.symmetry.x = !brush.symmetry.x; + } + if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, button_size).clicked() { + brush.symmetry.y = !brush.symmetry.y; + } + if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, button_size).clicked() { + brush.particles.enabled = !brush.particles.enabled; + } + + if tool == Tool::Smudge { + ui.separator(); + let mut strength = app.session.tool.smudge_strength * 100.0; + if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { + app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); + } + } + + if tool == Tool::Clone && app.session.tool.clone_source.is_none() { + ui.separator(); + ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); + } + + if tool == Tool::Path { + ui.separator(); + path_controls(app, ui); + } + } + Tool::PolygonFill => fill_mode_buttons(app, ui), + Tool::ColorPicker => { + ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); + } + Tool::GeometryMask => { + ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); + } + } +} + +/// Bake, Painting and Rendering mode buttons for a right-to-left layout, so Rendering is added first +fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; + for (mode, icon, label, command) in [ + (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), + (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), + (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), + ] { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } + } +} + +/// Polygon fill's fill modes (top bar and properties) +pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + use texturecraft_engine::FillMode; + + let button_size = ui.spacing().interact_size.y; + for (fill_mode, icon, tooltip) in [ + (FillMode::Triangle, ic::TRIANGLE, tr("Triangle fill")), + (FillMode::Polygon, ic::PARALLELOGRAM, tr("Polygon fill")), + (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), + (FillMode::UvIsland, ic::CHECKERBOARD, tr("UV island fill")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { + app.session.tool.fill_mode = fill_mode; + } + } +} + +/// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, 24.0).clicked() { + if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() { path.closed = !path.closed; } let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; - if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, 24.0).clicked() { + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() { path.fill = !path.fill; } + let has_points = !path.points.is_empty(); if ui .add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply")))) @@ -165,19 +352,6 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { ui.spacing_mut().item_spacing.y = 3.0; - for (mode, icon, label, command) in [ - (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), - (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), - (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 28.0).clicked() { - crate::menus::invoke(app, &ui.ctx().clone(), command); - } - } - - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| { for tool in Tool::ALL { let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool; diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs new file mode 100644 index 00000000..dcce58df --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,618 @@ +//! The UI state kept between runs as JSON: `ui.json` beside eframe's settings on the desktop, a key of eframe's storage on the web + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use crate::UiState; + +/// eframe storage key of the UI state as JSON, where there is no file +const STORAGE_KEY: &str = "ui.json"; + +/// Name of the UI state in eframe's storage, before the extension, for the copies of unreadable states kept there +const STORAGE_STEM: &str = "ui"; + +/// eframe storage key under which earlier builds kept the UI state, as RON +const RON_STORAGE_KEY: &str = "ui"; + +/// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes +const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; + +/// Copies of unreadable saved states kept before saving stops +const MAX_UNREADABLE_COPIES: u32 = 10; + +/// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage +pub static FILE: OnceLock = OnceLock::new(); + +/// Where the UI state is saved, holding a saved state this build could not fully read until it is kept beside it +#[derive(Default)] +pub struct UiStateStore { + file: Option, + /// A saved state this build could not fully read and its file extension, kept by the next save + unreadable: Option<(Vec, &'static str)>, + /// A saved state could not be read or kept, so it is left as it is + frozen: bool, + warning: Option, + last_warning: Option, +} + +impl UiStateStore { + /// The store at `file`, or in eframe's storage without one + pub fn new(file: Option) -> Self { + UiStateStore { file, ..Self::default() } + } + + /// The saved UI state, else the one an earlier build saved; a state not fully read is kept for the next save + pub fn load(&mut self, storage: Option<&dyn eframe::Storage>) -> Option { + let saved = match &self.file { + Some(file) => match read_bytes(file) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + self.frozen = true; + self.warn(&format!( + "Settings could not be read: {error}. Saving is disabled for this session. Back up the settings, check access and restart." + )); + return None; + } + }, + None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), + }; + let Some(bytes) = saved else { return self.load_ron(storage?) }; + + if bytes.len() as u64 > MAX_FILE_BYTES { + self.frozen = true; + self.warn("Settings exceed the 16 MiB limit. Saving is disabled for this session. Back up the settings and reduce their size before restarting."); + return None; + } + + let ui = serde_json::from_slice::(&bytes).ok(); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some((bytes, "json")); + } + ui + } + + /// Preserve the original RON when decoding loses either dock, even if other settings load + fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { + let text = storage.get_string(RON_STORAGE_KEY)?; + let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some((text.into_bytes(), "ron")); + } + ui + } + + /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds + pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { + if self.frozen { + return; + } + + let json = match serde_json::to_string_pretty(ui) { + Ok(json) => json, + Err(error) => { + self.warn(&format!("Settings could not be encoded: {error}. The previous settings have been kept.")); + return; + } + }; + if json.len() as u64 > MAX_FILE_BYTES { + self.warn("Settings were not saved because they exceed the 16 MiB limit. Reduce their size and try again. The previous settings have been kept."); + return; + } + + // JSON turns non-finite numbers into null; a dock can also silently fall back during decoding + if !serde_json::from_str::(&json).as_ref().is_ok_and(fully_read) { + self.warn( + "Settings were not saved because they would not read back. Reset invalid view settings and try again. The previous settings have been kept.", + ); + return; + } + + if let Some((bytes, extension)) = self.unreadable.take() + && !self.keep_unreadable(&bytes, extension, storage) + { + self.frozen = true; + self.warn("The previous settings could not be backed up. Saving is disabled for this session. Check free space and access, move existing unreadable backups to a safe place, then restart."); + return; + } + + let saved = match &self.file { + Some(file) => write_file(file, json.as_bytes()), + None => write_storage(storage, STORAGE_KEY, json), + }; + if saved { + storage.remove_string(RON_STORAGE_KEY); + self.warning = None; + self.last_warning = None; + } else { + self.warn("Settings could not be saved. Check free space and write access, or browser storage permissions and quota. The previous settings have been kept; saving will be retried."); + } + } + + /// A new storage warning for the app to show once, until saving succeeds again + pub fn take_warning(&mut self) -> Option { + self.warning.take() + } + + fn warn(&mut self, detail: &str) { + let location = self.file.as_ref().map_or_else(|| "browser/app storage".to_owned(), |file| file.display().to_string()); + let warning = format!("UI settings ({location}): {detail}"); + if self.last_warning.as_ref() != Some(&warning) { + log::warn!("{warning}"); + self.warning = Some(warning.clone()); + self.last_warning = Some(warning); + } + } + + /// Keep a saved state this build could not fully read under the first free copy name, beside the file or in storage + fn keep_unreadable(&self, bytes: &[u8], extension: &str, storage: &mut dyn eframe::Storage) -> bool { + match &self.file { + Some(file) => keep_file_copy(file, bytes, extension), + None => { + let free = (1..=MAX_UNREADABLE_COPIES).map(|n| unreadable_name(STORAGE_STEM, n, extension)).find(|key| storage.get_string(key).is_none()); + let Some(key) = free else { return false }; + + write_storage(storage, &key, String::from_utf8_lossy(bytes).into_owned()) + } + } + } +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + serde_json::from_slice(&read_bytes(file).ok()?).ok() +} + +/// eframe's browser storage reports write failures only through logging, so verify before discarding old settings +fn write_storage(storage: &mut dyn eframe::Storage, key: &str, text: String) -> bool { + storage.set_string(key, text.clone()); + storage.get_string(key).as_deref() == Some(text.as_str()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn read_bytes(file: &Path) -> std::io::Result> { + use std::io::Read as _; + + let input = std::fs::File::open(file)?; + let too_large = || std::io::Error::new(std::io::ErrorKind::InvalidData, "UI settings exceed the 16 MiB limit"); + if input.metadata()?.len() > MAX_FILE_BYTES { + return Err(too_large()); + } + + // Bound the read itself in case the file grows after its metadata was checked + let mut bytes = Vec::new(); + input.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(too_large()); + } + + Ok(bytes) +} + +#[cfg(target_arch = "wasm32")] +fn read_bytes(_file: &Path) -> std::io::Result> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "UI settings use browser storage")) +} + +/// Whether both docks were read rather than replaced by a default +fn fully_read(ui: &UiState) -> bool { + !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() +} + +/// The `n`th copy name of an unreadable state: `.unreadable.`, then `.unreadable-N.` +fn unreadable_name(stem: &str, n: u32, extension: &str) -> String { + if n == 1 { format!("{stem}.unreadable.{extension}") } else { format!("{stem}.unreadable-{n}.{extension}") } +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(file: &Path, bytes: &[u8]) -> bool { + if let Some(folder) = file.parent() { + let _ = std::fs::create_dir_all(folder); + } + + texturecraft_engine::formats::write_atomic(file, bytes).is_ok() +} + +#[cfg(target_arch = "wasm32")] +fn write_file(_file: &Path, _bytes: &[u8]) -> bool { + false +} + +/// Copy `bytes` beside `file` under the first free copy name +#[cfg(not(target_arch = "wasm32"))] +fn keep_file_copy(file: &Path, bytes: &[u8], extension: &str) -> bool { + use std::io::Write as _; + + let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 1..=MAX_UNREADABLE_COPIES { + let copy_file = file.with_file_name(unreadable_name(&stem, n, extension)); + match std::fs::OpenOptions::new().write(true).create_new(true).open(copy_file) { + Ok(mut copy) => return copy.write_all(bytes).is_ok(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => return false, + } + } + false +} + +#[cfg(target_arch = "wasm32")] +fn keep_file_copy(_file: &Path, _bytes: &[u8], _extension: &str) -> bool { + false +} + +#[cfg(test)] +mod memory_storage; + +#[cfg(test)] +pub(crate) mod tests { + use super::memory_storage::MemoryStorage; + use super::*; + use crate::docking::{Dock, Panel, default_workspace, permissions}; + use craft_ui::docking::{Action, Placement}; + + /// Save `ui` and load it back, as closing and reopening the app does + pub(crate) fn restart(ui: &UiState) -> UiState { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(ui, &mut storage); + UiStateStore::default().load(Some(&storage)).unwrap_or_else(|| panic!("the saved state loads: {:?}", storage.values)) + } + + /// An empty folder of its own for one test + fn test_folder(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!("texturecraft-ui-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder + } + + /// The painting default with Layers moved into a tab beside Assets and Properties floating + fn moved_panels() -> Dock { + let mut workspace = default_workspace(); + let actions = [ + Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, + Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + + let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert!(!dock.replaced_unreadable(), "the moved layout is valid"); + dock + } + + #[test] + fn panel_layouts_survive_a_restart_in_the_file_and_in_storage() { + let folder = test_folder("layouts"); + for dock in [Dock::default(), moved_panels()] { + let ui = UiState { dock, split_ratio: 0.3, ..UiState::default() }; + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + + let restarted = UiStateStore::new(file.clone()).load(Some(&storage)).unwrap(); + assert!(fully_read(&restarted), "{file:?}"); + assert_eq!(restarted, ui, "{file:?}"); + } + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn the_state_an_earlier_build_saved_loads_and_its_copy_goes_on_the_next_save() { + let mut storage = MemoryStorage::default(); + let earlier = UiState { split_ratio: 0.3, ..UiState::default() }; + eframe::set_value(&mut storage, RON_STORAGE_KEY, &earlier); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).expect("the earlier state loads"); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + assert!(!storage.values.contains_key(RON_STORAGE_KEY)); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + + #[test] + fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { + let folder = test_folder("unreadable"); + let file = folder.join("ui.json"); + let ui = UiState { dock: moved_panels(), split_ratio: 0.3, ..UiState::default() }; + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + + let unreadable = [ + // A panel this build does not know + saved.replacen("\"Assets\"", "\"Bogus\"", 1), + // A layout from a newer format + saved.replacen("\"version\": 2", "\"version\": 99", 1), + // Not a saved state + "not json".to_owned(), + ]; + for (n, text) in unreadable.iter().enumerate() { + std::fs::write(&file, text).unwrap(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)); + if let Some(loaded) = &loaded { + assert_eq!(loaded.dock, Dock::default(), "{text}"); + assert_eq!(loaded.split_ratio, 0.3, "{text}"); + } + + store.save(&loaded.unwrap_or_default(), &mut storage); + let copy = unreadable_name("ui", n as u32 + 1, "json"); + assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); + assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { + let folder = test_folder("frozen"); + let file = folder.join("ui.json"); + for n in 1..=MAX_UNREADABLE_COPIES { + std::fs::write(folder.join(unreadable_name("ui", n, "json")), "").unwrap(); + } + std::fs::write(&file, "not json").unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "not json"); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_too_large_to_read_is_not_saved_over() { + let folder = test_folder("too-large"); + let file = folder.join("ui.json"); + std::fs::write(&file, vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::metadata(&file).unwrap().len(), MAX_FILE_BYTES + 1); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn unreadable_layouts_in_storage_are_each_kept_under_a_key_of_their_own() { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); + let saved = storage.values[STORAGE_KEY].clone(); + + for (n, panel) in [(1, "\"Bogus\""), (2, "\"Other\"")] { + let unreadable = saved.replacen("\"Assets\"", panel, 1); + storage.values.insert(STORAGE_KEY.to_owned(), unreadable.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.values[&unreadable_name(STORAGE_STEM, n, "json")], unreadable); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + assert_eq!(storage.values[&unreadable_name(STORAGE_STEM, 1, "json")], saved.replacen("\"Assets\"", "\"Bogus\"", 1), "the first copy stays"); + } + + #[test] + fn an_earlier_state_that_does_not_parse_is_kept_before_its_entry_goes() { + let folder = test_folder("ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + storage.values.insert(RON_STORAGE_KEY.to_owned(), "(not ron".to_owned()); + + let mut store = UiStateStore::new(file.clone()); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + let copy = match &file { + Some(_) => std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "ron"))).unwrap(), + None => storage.values[&unreadable_name(STORAGE_STEM, 1, "ron")].clone(), + }; + assert_eq!(copy, "(not ron", "{file:?}"); + assert!(!storage.values.contains_key(RON_STORAGE_KEY), "{file:?}"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_that_exists_but_cannot_be_read_is_not_saved_over() { + let folder = test_folder("read-error"); + let file = folder.join("ui.json"); + // A folder in the file's place fails to read with an error other than not found + std::fs::create_dir_all(&file).unwrap(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + + let mut store = UiStateStore::new(Some(file.clone())); + assert!(store.load(Some(&storage)).is_none(), "the earlier state is not loaded in its place"); + store.save(&UiState::default(), &mut storage); + assert!(file.is_dir()); + assert!(storage.values.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_state_that_would_not_read_back_is_not_saved() { + let mut storage = MemoryStorage::default(); + let mut store = UiStateStore::default(); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + let saved = storage.values[STORAGE_KEY].clone(); + + store.save(&UiState { uv_pan: [f32::NAN, 0.0], ..UiState::default() }, &mut storage); + assert_eq!(storage.values[STORAGE_KEY], saved); + } + + #[test] + fn rejected_storage_backup_preserves_the_unreadable_original() { + let mut storage = MemoryStorage::default(); + storage.values.insert(STORAGE_KEY.into(), "not json".into()); + storage.rejected_key = Some("ui.unreadable.json"); + let mut store = UiStateStore::default(); + assert!(store.load(Some(&storage)).is_none()); + + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(storage.values[STORAGE_KEY], "not json"); + } + + #[test] + fn rejected_storage_save_keeps_legacy_ron() { + let mut storage = MemoryStorage::default(); + let ui = UiState::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &ui); + let original = storage.values[RON_STORAGE_KEY].clone(); + storage.rejected_key = Some(STORAGE_KEY); + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values.get(RON_STORAGE_KEY), Some(&original)); + assert!(!storage.values.contains_key(STORAGE_KEY)); + } + + #[test] + fn parsed_legacy_ron_keeps_the_raw_custom_layout() { + let folder = test_folder("legacy-layout"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + // Recorded with the legacy eframe RON writer: Assets closed, Display floating, twenty recent projects + let original = include_str!("../tests/fixture/ui_state_before_json.ron").to_owned(); + storage.values.insert(RON_STORAGE_KEY.into(), original.clone()); + assert!(original.contains("panels:[Display]") && original.contains("960.0")); + let mut store = UiStateStore::new(file.clone()); + let loaded = store.load(Some(&storage)).unwrap(); + assert!(loaded.dock.replaced_unreadable()); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + let backup = match &file { + Some(_) => std::fs::read_to_string(folder.join("ui.unreadable.ron")).ok(), + None => storage.values.get("ui.unreadable.ron").cloned(), + }; + assert_eq!(backup, Some(original), "{file:?}"); + } + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn a_save_larger_than_the_read_limit_preserves_the_previous_state() { + let folder = test_folder("oversized-save"); + let file = folder.join("ui.json"); + let mut storage = MemoryStorage::default(); + let mut store = UiStateStore::new(Some(file.clone())); + store.save(&UiState::default(), &mut storage); + let previous = std::fs::read(&file).unwrap(); + let ui = UiState { shelf_filter: "x".repeat(MAX_FILE_BYTES as usize), ..UiState::default() }; + + store.save(&ui, &mut storage); + assert!(std::fs::read(&file).unwrap() == previous); + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn customized_painting_and_baking_docks_survive_each_active_mode() { + let folder = test_folder("both-modes"); + for mode in [crate::state::Mode::Painting, crate::state::Mode::Baking, crate::state::Mode::Rendering] { + let mut ui = UiState { dock: moved_panels(), ..UiState::default() }; + ui.inactive_mode_dock.close(Panel::MeshMapBakers); + ui.mode = mode; + ui.sync_mode_dock(); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + let mut loaded = UiStateStore::new(file).load(Some(&storage)).unwrap(); + loaded.sync_mode_dock(); + assert_eq!(loaded, ui, "{mode:?}"); + loaded.mode = crate::state::Mode::Painting; + loaded.sync_mode_dock(); + assert_eq!(loaded.dock, moved_panels()); + loaded.mode = crate::state::Mode::Baking; + loaded.sync_mode_dock(); + assert!(!loaded.dock.is_open(Panel::MeshMapBakers)); + } + } + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn failed_saves_report_once_and_retry_after_access_is_restored() { + let mut storage = MemoryStorage::default(); + storage.rejected_key = Some(STORAGE_KEY); + let mut store = UiStateStore::default(); + store.save(&UiState::default(), &mut storage); + assert!(store.take_warning().unwrap().contains("could not be saved")); + store.save(&UiState::default(), &mut storage); + assert!(store.take_warning().is_none()); + + storage.rejected_key = None; + store.save(&UiState::default(), &mut storage); + assert!(store.load(Some(&storage)).is_some()); + storage.rejected_key = Some(STORAGE_KEY); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + assert!(store.take_warning().is_some(), "a new failure after recovery is reported"); + } + + #[test] + fn failed_file_saves_keep_legacy_settings_and_report_the_path() { + let folder = test_folder("write-error"); + let file = folder.join("ui.json"); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + let original = storage.values[RON_STORAGE_KEY].clone(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)).unwrap(); + std::fs::create_dir(&file).unwrap(); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values[RON_STORAGE_KEY], original); + assert!(store.take_warning().unwrap().contains(&file.display().to_string())); + std::fs::remove_dir(&file).unwrap(); + store.save(&loaded, &mut storage); + assert!(read(&file).is_some()); + assert!(!storage.values.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn non_finite_legacy_pan_leaves_the_original_ron_for_the_next_restart() { + let folder = test_folder("nonfinite-ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState { uv_pan: [f32::NAN, 1.0], ..UiState::default() }); + let original = storage.values[RON_STORAGE_KEY].clone(); + let mut store = UiStateStore::new(file.clone()); + let loaded = store.load(Some(&storage)).unwrap(); + assert!(loaded.uv_pan[0].is_nan()); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values[RON_STORAGE_KEY], original); + assert!(store.take_warning().is_some()); + assert!(!storage.values.contains_key(STORAGE_KEY)); + assert!(!file.as_ref().is_some_and(|file| file.exists())); + let restarted = UiStateStore::new(file).load(Some(&storage)).unwrap(); + assert!(restarted.uv_pan[0].is_nan()); + } + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn an_unreadable_inactive_dock_is_backed_up_before_mode_sync() { + let mut storage = MemoryStorage::default(); + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + saved["inactive_mode_dock"]["version"] = 99.into(); + let original = saved.to_string(); + storage.values.insert(STORAGE_KEY.into(), original.clone()); + let mut store = UiStateStore::default(); + let mut loaded = store.load(Some(&storage)).unwrap(); + assert!(loaded.inactive_mode_dock.replaced_unreadable()); + loaded.sync_mode_dock(); + assert!(!loaded.inactive_mode_dock.replaced_unreadable()); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values["ui.unreadable.json"], original); + } +} diff --git a/crates/ui-egui/src/ui_state_store/memory_storage.rs b/crates/ui-egui/src/ui_state_store/memory_storage.rs new file mode 100644 index 00000000..794fc996 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store/memory_storage.rs @@ -0,0 +1,24 @@ +/// eframe's storage held in memory +#[derive(Default)] +pub(crate) struct MemoryStorage { + pub(crate) values: std::collections::HashMap, + pub(crate) rejected_key: Option<&'static str>, +} + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.values.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + if self.rejected_key != Some(key) { + self.values.insert(key.to_owned(), value); + } + } + + fn remove_string(&mut self, key: &str) { + self.values.remove(key); + } + + fn flush(&mut self) {} +} diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs new file mode 100644 index 00000000..fa1e6c4b --- /dev/null +++ b/crates/ui-egui/src/updates_ui.rs @@ -0,0 +1,325 @@ +//! Software updates on the desktop: the check at start, Help > Check for Updates and the update +//! prompt. An update that is ready starts its install helper when the app is dropped at exit. + +use craft_update::updater::{Action, Status, Updater}; +use craft_update::{CheckResultDialog, CheckResultResponse}; + +use crate::TextureCraftApp; + +pub(crate) struct Runtime { + updater: Updater, + /// The desktop app turns the check at start on; tests leave it off. + startup_check: bool, + check_requested: bool, +} + +impl Default for Runtime { + fn default() -> Self { + Self { updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")), startup_check: false, check_requested: false } + } +} + +impl TextureCraftApp { + /// Whether the app asks for a newer release when it starts (off until the desktop app turns it on). + pub fn set_startup_update_check(&mut self, on: bool) { + self.updates_rt.startup_check = on; + } +} + +/// Help > Check for Updates: the next frame starts a check that reports its outcome. +pub(crate) fn request_check(app: &mut TextureCraftApp, ctx: &egui::Context) { + app.updates_rt.check_requested = true; + ctx.request_repaint(); +} + +/// The update prompt and the modal result window hold the keyboard while they are open, so keys +/// do not act on the project behind them. +pub(crate) fn blocks_input(app: &TextureCraftApp) -> bool { + holds_keyboard(app.updates_rt.updater.status(), app.updates_rt.updater.prompt_open()) +} + +/// The prompt is modal, and the result window is modal for every status but [`Status::Updated`], +/// a notice that leaves the app usable behind it. +fn holds_keyboard(status: &Status, prompt_open: bool) -> bool { + prompt_open || !matches!(status, Status::Idle | Status::Updated(_)) +} + +pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) { + let rt = &mut app.updates_rt; + if std::mem::take(&mut rt.check_requested) { + rt.updater.check_now(ctx); + } else if rt.startup_check { + rt.updater.check_at_start(ctx); + } + rt.updater.tick(ctx); +} + +/// Whether the result window shows: for every status but idle (a requested check, and the first +/// start after an update, which reports that it installed or why it failed), and never over the +/// update prompt. +fn result_window_shows(status: &Status, prompt_open: bool) -> bool { + !prompt_open && !matches!(status, Status::Idle) +} + +/// Whether an update may install and close the app: the project has no unsaved changes and no +/// stroke, bake or resize is running. +fn safe_to_close(app: &TextureCraftApp) -> bool { + !app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let safe = safe_to_close(app); + match app.updates_rt.updater.show_if(ctx, safe) { + Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), + Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + Action::None => {} + } + let rt = &mut app.updates_rt; + if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) { + match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) { + CheckResultResponse::None => {} + CheckResultResponse::Close => rt.updater.dismiss_status(), + CheckResultResponse::CheckAgain => rt.check_requested = true, + CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::mpsc::{Receiver, channel}; + + use craft_update::updater::CheckSource; + use craft_update::{Arch, Asset, Os, PackageKind, Paths, Platform, Release, pick_asset}; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + use serde_json::json; + use texturecraft_engine::Tool; + use texturecraft_engine::bake::Progress; + use texturecraft_engine::geom::glam::Vec2; + + use super::*; + use crate::state::Mode; + + /// Stands in for GitHub: each check sends one message and finds nothing newer. + fn source() -> (CheckSource, Receiver<()>) { + let (sent, asked) = channel(); + let ask: CheckSource = Arc::new(move || { + let _ = sent.send(()); + Ok(None) + }); + (ask, asked) + } + + /// The harness draws the UI, and the i18n tests switch the process-wide language to ones + /// its fonts cannot draw. + fn language() -> std::sync::MutexGuard<'static, ()> { + crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The app with an updater that asks `ask` and keeps its records out of the user's folders. + fn harness(modified: bool, test: &str, ask: CheckSource) -> Harness<'static, TextureCraftApp> { + let root = std::env::temp_dir().join(format!("texturecraft-updates-{}-{test}", std::process::id())); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = modified; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().updates_rt.updater = + Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json")); + h.state_mut().ui.windows.start = false; + h.run_steps(2); + h + } + + fn offer(h: &mut Harness<'static, TextureCraftApp>) { + let release = Release { + tag: "v99.0.0".into(), + version: craft_update::parse_version("99.0.0"), + name: "TextureCraft 99.0.0".into(), + html_url: "https://github.com/storytold/texturecraft/releases/tag/v99.0.0".into(), + ..Default::default() + }; + h.state_mut().updates_rt.updater.offer(release); + h.run_steps(2); + } + + #[test] + fn default_runtime_is_idle() { + let rt = Runtime::default(); + assert!(!rt.startup_check); + assert!(!rt.check_requested); + assert!(!rt.updater.prompt_open()); + assert_eq!(rt.updater.status(), &Status::Idle); + } + + #[test] + fn the_menu_item_runs_a_check_that_reports_its_outcome() { + let _language = language(); + let (ask, asked) = source(); + let mut h = harness(false, "menu", ask); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "ui.help.checkForUpdates"); + h.step(); + let status = h.state().updates_rt.updater.status().clone(); + assert!(matches!(status, Status::Checking | Status::UpToDate), "{status:?}"); + // Dropping the app drops the only sender left when no check started, so this cannot hang. + drop(h); + assert!(asked.recv().is_ok(), "the check asked for the latest release"); + } + + #[test] + fn the_check_at_start_runs_only_when_the_desktop_app_turns_it_on() { + let _language = language(); + for on in [false, true] { + let (ask, asked) = source(); + let mut h = harness(false, if on { "start-on" } else { "start-off" }, ask); + h.state_mut().set_startup_update_check(on); + h.step(); + drop(h); + assert_eq!(asked.recv().is_ok(), on, "startup check {on}"); + } + } + + #[test] + fn an_offered_update_shows_the_prompt_and_later_closes_it() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "prompt", ask); + offer(&mut h); + assert!(h.state().updates_rt.updater.prompt_open()); + h.get_by_label("LATER").click(); + h.run_steps(2); + assert!(!h.state().updates_rt.updater.prompt_open()); + } + + #[test] + fn keys_do_not_reach_the_project_behind_the_prompt() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "keys", ask); + assert_eq!(h.state().ui.mode, Mode::Painting); + offer(&mut h); + assert!(crate::docking::input_blocked(h.state(), &h.ctx), "floating panels stop taking input"); + h.key_press(egui::Key::F8); + h.step(); + assert_eq!(h.state().ui.mode, Mode::Painting, "the prompt holds the keyboard"); + h.get_by_label("LATER").click(); + h.run_steps(2); + assert!(!crate::docking::input_blocked(h.state(), &h.ctx)); + h.key_press(egui::Key::F8); + h.step(); + assert_eq!(h.state().ui.mode, Mode::Baking, "the key works once the prompt is closed"); + } + + #[test] + fn the_path_tools_keys_do_not_reach_the_path_behind_the_prompt() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "path-keys", ask); + let state = h.state_mut(); + state.session.tool.tool = Tool::Path; + texturecraft_engine::execute(&mut state.session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + h.run_steps(2); + let points = |h: &Harness<'static, TextureCraftApp>| h.state().session.tool.path.points.len(); + assert_eq!(points(&h), 2); + offer(&mut h); + h.key_press(egui::Key::Backspace); + h.step(); + assert_eq!(points(&h), 2, "the prompt holds the keyboard"); + h.get_by_label("LATER").click(); + h.run_steps(2); + h.key_press(egui::Key::Backspace); + h.step(); + assert_eq!(points(&h), 1, "the key works once the prompt is closed"); + } + + #[test] + fn the_result_window_holds_the_keyboard_unless_it_is_the_updated_notice() { + let modal = [ + Status::Checking, + Status::UpToDate, + Status::Failed("offline".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::InstallFailed("locked".into()), + ]; + for status in &modal { + assert!(holds_keyboard(status, false), "{status:?}"); + } + assert!(!holds_keyboard(&Status::Idle, false)); + assert!(!holds_keyboard(&Status::Updated("99.0.0".into()), false)); + assert!(holds_keyboard(&Status::Idle, true), "the prompt is modal"); + } + + #[test] + fn unsaved_changes_and_running_work_hold_an_update_back() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "safe-to-close", ask); + assert!(safe_to_close(h.state())); + + h.state_mut().session.modified = true; + assert!(!safe_to_close(h.state()), "unsaved changes"); + h.state_mut().session.modified = false; + + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0 }); + assert!(!safe_to_close(h.state()), "a bake"); + h.state_mut().bake = None; + + h.state_mut().resize = Some(crate::ResizeJob { progress: Arc::new(Progress::new()), rx: channel().1 }); + assert!(!safe_to_close(h.state()), "a resize"); + h.state_mut().resize = None; + + let session = &mut h.state_mut().session; + texturecraft_engine::execute(session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + session.modified = false; + session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).unwrap(); + assert!(!safe_to_close(h.state()), "a stroke"); + h.state_mut().session.cancel_stroke(); + assert!(safe_to_close(h.state())); + } + + #[test] + fn result_window_shows_every_status_but_idle() { + let shown = [ + Status::Checking, + Status::UpToDate, + Status::Failed("offline".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::Updated("99.0.0".into()), + Status::InstallFailed("locked".into()), + ]; + for status in &shown { + assert!(result_window_shows(status, false), "{status:?} shows"); + assert!(!result_window_shows(status, true), "{status:?} waits for the prompt"); + } + assert!(!result_window_shows(&Status::Idle, false)); + } + + #[test] + fn the_update_app_finds_the_assets_a_release_publishes() { + let names = [ + "texturecraft-0.4.0-macos-universal.dmg", + "texturecraft-0.4.0-windows-x64.msi", + "texturecraft-0.4.0-windows-x64-portable.zip", + "texturecraft-0.4.0-linux-x86_64.AppImage", + "texturecraft-0.4.0-linux-x86_64.tar.gz", + "texturecraft-cli-0.4.0-macos-universal.zip", + "texturecraft-web-0.4.0.zip", + ]; + let assets = names.iter().map(|name| Asset { name: (*name).into(), size: 1, url: String::new(), sha256: None }).collect(); + let release = Release { assets, ..Default::default() }; + let stems = [crate::UPDATE_APP.id]; + let picked = |os, arch, kind| pick_asset(&release, &stems, Platform { os, arch }, &[kind]).map(|(asset, _)| asset.name.clone()); + assert_eq!(picked(Os::MacOs, Arch::Arm64, PackageKind::Dmg).as_deref(), Some(names[0])); + assert_eq!(picked(Os::Windows, Arch::X64, PackageKind::Msi).as_deref(), Some(names[1])); + assert_eq!(picked(Os::Windows, Arch::X64, PackageKind::PortableZip).as_deref(), Some(names[2])); + assert_eq!(picked(Os::Linux, Arch::X64, PackageKind::AppImage).as_deref(), Some(names[3])); + assert_eq!(picked(Os::Linux, Arch::X64, PackageKind::TarGz).as_deref(), Some(names[4])); + assert_eq!(crate::UPDATE_APP.bundle_id(), "ai.storyteller.texturecraft"); + assert_eq!(crate::UPDATE_APP.repo, "storytold/texturecraft"); + } +} diff --git a/crates/ui-egui/src/uv_paint_point.rs b/crates/ui-egui/src/uv_paint_point.rs new file mode 100644 index 00000000..5ff1cafb --- /dev/null +++ b/crates/ui-egui/src/uv_paint_point.rs @@ -0,0 +1,21 @@ +//! A finished stroke's endpoint in one mesh's UV layout + +use texturecraft_engine::{Session, geom::glam::Vec2}; + +/// A line anchor scoped to its project, UV layout and texture set +#[derive(Clone, Copy, Debug)] +pub struct UvPaintPoint { + mesh_id: u64, + texture_set: usize, + uv: Vec2, +} + +impl UvPaintPoint { + pub(crate) fn new(session: &Session, uv: Vec2) -> Self { + Self { mesh_id: session.mesh_id, texture_set: session.ts(), uv } + } + + pub(crate) fn uv_for(self, session: &Session) -> Option { + (self.mesh_id == session.mesh_id && self.texture_set == session.ts()).then_some(self.uv) + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index db50b2db..e864a5b2 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3,19 +3,21 @@ use std::sync::Mutex; -use egui::{Color32, PointerButton, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; +use egui::emath::GuiRounding as _; +use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::glam::{Vec2, Vec3}; -use texturecraft_engine::{Tool, ViewMode}; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_engine::{Session, Tool, ViewMode}; +use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::state::ViewLayout; use crate::theme::Tokens; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -34,6 +36,7 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { ctx.data_mut(|d| d.insert_temp(focus_pick_id(), on)); } +/// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; let bake_painting = mode == crate::state::Mode::Baking @@ -43,34 +46,50 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased }); app.ui.bake_paint_brush.on = bake_painting; - if mode == crate::state::Mode::Painting && !app.ui.hide_ui { + + if !app.ui.hide_ui { crate::toolbar::paint_bar(app, ui); } + crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); - let aux = match app.session.view { - _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), - ViewMode::MeshMap(m) => Some(crate::gpu::AuxView::MeshMap(m)), + let aux_view = match app.session.view { + _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask), + ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, }; - let mut sync = PendingSync(Some(aux)); + let mut sync = PendingSync(Some(aux_view)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); + // Skew painting needs the 2D view alongside the 3D Bake preview let layout = if mode == crate::state::Mode::Painting || bake_painting { app.ui.layout } else { ViewLayout::Only3D }; match layout { ViewLayout::Only3D => view_3d(app, ui, full, &mut sync), ViewLayout::Only2D => view_2d(app, ui, full, &mut sync), ViewLayout::Split => { - let midpoint = full.center().x; - let left = Rect::from_min_max(full.min, pos2(midpoint - 1.0, full.max.y)); - let right = Rect::from_min_max(pos2(midpoint + 1.0, full.min.y), full.max); + // The 2D view's edges sit on whole pixels, so rounding can't nudge a texture its zoom keeps at one size + let pixels_per_point = ui.ctx().pixels_per_point(); + let full = full.with_max_x(full.right().round_to_pixels(pixels_per_point)); + let divider_x = split_divider_x(app, ui, full); + let left = Rect::from_min_max(full.min, pos2(divider_x - SPLIT_LINE_HALF_WIDTH, full.max.y)); + let right = Rect::from_min_max(pos2(divider_x + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max); + // Each view draws only on its side, so overlays such as the texture set name stay out of a narrow neighbour + let clip = ui.clip_rect(); + ui.set_clip_rect(left.intersect(clip)); view_3d(app, ui, left, &mut sync); + ui.set_clip_rect(right.intersect(clip)); view_2d(app, ui, right, &mut sync); - ui.painter().line_segment([pos2(midpoint, full.top()), pos2(midpoint, full.bottom())], Stroke::new(2.0, tokens.chrome)); + ui.set_clip_rect(clip); + split_divider_grab(ui, full, divider_x); + let line = Stroke::new(SPLIT_LINE_HALF_WIDTH * 2.0, tokens.chrome); + ui.painter().line_segment([pos2(divider_x, full.top()), pos2(divider_x, full.bottom())], line); } } + + crate::properties_popup::show(app, ui.ctx()); + if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); } else if app.render.is_active() { @@ -79,20 +98,127 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { if mode == crate::state::Mode::Baking { crate::bake_mode::bake_bar(app, ui.ctx(), full); } + // Keep drawing until the 3D view finishes accumulating anti-aliasing samples let accumulating = layout != ViewLayout::Only2D - && app - .render_state - .as_ref() - .is_some_and(|rs| rs.renderer.read().callback_resources.get::().is_some_and(|g| g.renderer.accumulating(VIEW_3D))); + && app.render_state.as_ref().is_some_and(|render_state| { + render_state.renderer.read().callback_resources.get::().is_some_and(|gpu| gpu.renderer.accumulating(VIEW_3D)) + }); if app.session.stroke_active() || accumulating { ui.ctx().request_repaint(); } } +/// Half the split divider's line width: each view starts this far from the line's centre +const SPLIT_LINE_HALF_WIDTH: f32 = 1.0; + +/// Narrowest a split view may get: a sliver that is still easy to grab and drag back out +const MIN_SPLIT_VIEW_WIDTH: f32 = 16.0; + +/// Width of the split divider's grab zone, centred on its line +const SPLIT_DIVIDER_GRAB_WIDTH: f32 = 8.0; + +/// The split divider's widget id, shared by its drag read and its grab zone +fn split_divider_id(ui: &Ui) -> egui::Id { + ui.scope_id().with("split_divider") +} + +/// The 3D view's share of `width`, keeping both views at least [`MIN_SPLIT_VIEW_WIDTH`] wide when they fit +fn clamp_split_ratio(ratio: f32, width: f32) -> f32 { + let min_ratio = (MIN_SPLIT_VIEW_WIDTH / width).min(0.5); + let ratio = if ratio.is_finite() { ratio } else { 0.5 }; + ratio.clamp(min_ratio, 1.0 - min_ratio) +} + +/// The split divider's x position: while it is dragged it follows the pointer and changes the 2D zoom so the texture keeps its size on screen +fn split_divider_x(app: &mut TextureCraftApp, ui: &Ui, full: Rect) -> f32 { + // The 2D view's left edge, beside the line, sits on a whole pixel + let pixels_per_point = ui.ctx().pixels_per_point(); + let divider_x = |ratio: f32| { + let unsnapped = full.left() + full.width() * clamp_split_ratio(ratio, full.width()); + (unsnapped + SPLIT_LINE_HALF_WIDTH).round_to_pixels(pixels_per_point) - SPLIT_LINE_HALF_WIDTH + }; + let old_x = divider_x(app.ui.split_ratio); + + // Read the drag before the views lay out so they follow the pointer in the same frame + let ctx = ui.ctx(); + if ctx.is_being_dragged(split_divider_id(ui)) + && ctx.input(|i| i.pointer.primary_down()) + && let Some(pointer) = ctx.pointer_interact_pos() + { + // `max` and `min` rather than `clamp`, so a NaN bound from a corrupt saved zoom can't panic + let (min_x, max_x) = divider_range_keeping_uv_size(&app.ui, full, old_x, pixels_per_point); + let target_x = pointer.x.max(min_x).min(max_x); + app.ui.split_ratio = clamp_split_ratio((target_x - full.left()) / full.width(), full.width()); + let new_x = divider_x(app.ui.split_ratio); + keep_uv_view_on_screen(&mut app.ui, full, old_x, new_x); + } + + divider_x(app.ui.split_ratio) +} + +/// Lowest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 0.05) +const UV_VIEW_MIN_ZOOM: f32 = 0.1; + +/// Highest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 64) +const UV_VIEW_MAX_ZOOM: f32 = 40.0; + +/// UV zoom change per point of mouse wheel, as a fraction of the zoom +const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; + +/// Dash length of the straight-line preview, in points +const RUBBER_BAND_DASH: f32 = 6.0; + +/// Gap between the straight-line preview's dashes, in points +const RUBBER_BAND_GAP: f32 = 4.0; + +/// Opacity of the UV tile outlines in the 2D view +const UV_TILE_OUTLINE_ALPHA: u8 = 40; + +/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible +const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; + +/// The 2D view's width when the split divider is at `divider_x` +fn uv_view_width(full: Rect, divider_x: f32) -> f32 { + (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) +} + +/// The share of the 2D view's height that a zoom of 1 fills at `width`: the view fits the texture to its narrower side +fn uv_view_fit(full: Rect, width: f32) -> f32 { + (width / full.height().max(1.0)).min(1.0) +} + +/// The divider positions where the 2D zoom that keeps the texture's screen size stays inside the 2D zoom range +fn divider_range_keeping_uv_size(ui_state: &crate::state::UiState, full: Rect, old_x: f32, pixels_per_point: f32) -> (f32, f32) { + // The zoom times the fit is the texture's screen size, which a divider drag keeps + let screen_zoom = ui_state.uv_zoom * uv_view_fit(full, uv_view_width(full, old_x)); + + // Whole pixels, rounded inward, so snapping the divider to a pixel can't step past the range + let narrowest_view = (full.height() * screen_zoom / UV_VIEW_MAX_ZOOM * pixels_per_point).ceil() / pixels_per_point; + let widest_view = (full.height() * screen_zoom / UV_VIEW_MIN_ZOOM * pixels_per_point).floor() / pixels_per_point; + + let edge = full.right() - SPLIT_LINE_HALF_WIDTH; + (edge - widest_view, edge - narrowest_view) +} + +/// Keeps the 2D view's texture at the same size and offset from the view's centre when the divider moves its left edge from `old_x` to `new_x` +fn keep_uv_view_on_screen(ui_state: &mut crate::state::UiState, full: Rect, old_x: f32, new_x: f32) { + let (old_width, new_width) = (uv_view_width(full, old_x), uv_view_width(full, new_x)); + ui_state.uv_zoom *= uv_view_fit(full, old_width) / uv_view_fit(full, new_width); + + // The horizontal pan is in half view widths + ui_state.uv_pan[0] *= old_width / new_width; +} + +/// The split divider's grab zone with a resize cursor, claimed after the views so it wins the pointer over them +fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { + let zone = Rect::from_x_y_ranges(divider_x - SPLIT_DIVIDER_GRAB_WIDTH * 0.5..=divider_x + SPLIT_DIVIDER_GRAB_WIDTH * 0.5, full.y_range()); + ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal); +} + fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing => (2, 0), + _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (2, 0), ViewMode::Material => (0, 0), ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32), ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), @@ -100,16 +226,26 @@ fn shade(app: &TextureCraftApp) -> Shade { }; let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + // Polygon fill shows the polygons it fills without changing the saved wireframe toggles + let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe, - wireframe_3d: app.ui.wireframe_3d, + wireframe: app.ui.uv_wireframe || polygon_fill_tool, + wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool, ..Shade::from_project(&app.session.doc.project) } } +/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color +fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + let set = crate::shelf::material_drop_set(app, ui, response)?; + let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); + + Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) +} + /// Show what the GPU side reported (each message once while its toast is up). fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) { let names: Vec = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect(); @@ -167,45 +303,84 @@ const MAX_NAME_CHARS: usize = 32; /// that view handled its input: a stroke shows in the frame it is painted, not the next. pub struct PendingSync(Option>); -fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); +/// A view's render size in pixels, rounded as egui rounds the rect it draws the frame into, so the frame is never stretched +fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { + let pixels_per_point = ui.ctx().pixels_per_point(); + let pixels = |from: f32, to: f32| ((to * pixels_per_point).round() - (from * pixels_per_point).round()).max(1.0) as u32; + [pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())] +} + +fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) { + let tokens = Tokens::get(ui.ctx()); + let bake = bake_visualization(app); + frame.shade.bake = bake.filter(|_| frame.kind == ViewKind::Scene); let scene = match (sync.0.take(), app.gpu.as_mut()) { - (Some(aux), Some(g)) => { - let t0 = crate::now_ms(); - let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); - let reports = g.take_reports(); - app.profiler.sync_ms += (crate::now_ms() - t0) as f32; + (Some(aux), Some(gpu_link)) => { + let sync_start_ms = crate::now_ms(); + let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + let reports = gpu_link.take_reports(); + app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); - // Display tiles left for later frames (the frame budget ran out). - if app.session.caches.iter().any(|c| !c.upload.is_empty()) { + + // Display tiles left for later frames (the frame budget ran out), or the bake visualization still being worked out + if app.session.caches.iter().any(|cache| !cache.upload.is_empty()) || app.gpu.as_ref().is_some_and(crate::gpu::GpuLink::bake_busy) { ui.ctx().request_repaint(); } Some(scene) } _ => None, }; + let Some(gpu) = &app.gpu else { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, tr("No GPU renderer available"), egui::FontId::proportional(14.0), tk.viewport_text); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("No GPU renderer available"), + egui::FontId::proportional(NO_GPU_TEXT_SIZE), + tokens.viewport_text, + ); return; }; - let cb = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; - ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); + + let callback = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; + ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, callback)); } -/// The view-mode dropdown shown at the top of each view. +/// Text size of the notice a view shows without a GPU renderer +const NO_GPU_TEXT_SIZE: f32 = 14.0; + +/// Width of the camera and view pickers centred at the top of a view +const VIEW_HEADER_WIDTH: f32 = 300.0; + +/// Height of the view pickers' row +const VIEW_HEADER_HEIGHT: f32 = 22.0; + +/// Gap between the view's top edge and its pickers +const VIEW_HEADER_TOP_GAP: f32 = 8.0; + +/// Width of each of the two pickers +const VIEW_PICKER_WIDTH: f32 = 130.0; + +/// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { - let header = Rect::from_min_size(rect.min + vec2(rect.width() * 0.5 - 150.0, 8.0), vec2(300.0, 22.0)); + if rect.width() < VIEW_HEADER_WIDTH { + return; + } + + let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP); + let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); + let current = texturecraft_engine::camera_cmds::current(&app.session); - let names: Vec = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect(); - let shown = current.and_then(|i| names.get(i)).map_or(tr(DEFAULT_CAMERA), String::as_str); - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(130.0).selected_text(shown).show_ui(&mut child, |ui| { + let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); + let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); + egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { app.run("camera.select", json!({})); } - for (i, name) in names.iter().enumerate() { - if ui.selectable_label(current == Some(i), name).clicked() { - app.run("camera.select", json!({"index": i})); + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(current == Some(index), name).clicked() { + app.run("camera.select", json!({"index": index})); } } ui.separator(); @@ -213,26 +388,27 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); + let label = match app.session.view { ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(), _ => app.session.view.label(), }; - let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(130.0).selected_text(tr(&label)).show_ui(&mut child, |ui| { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| { if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { app.run("viewport.view", json!({"mode": "material"})); } ui.separator(); - for c in channels { - if ui.selectable_label(app.session.view == ViewMode::Channel(c), tr(c.label())).clicked() { - app.run("viewport.view", json!({"mode": c.id()})); + for channel in channels { + if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { + app.run("viewport.view", json!({"mode": channel.id()})); } } ui.separator(); - for m in BakedMap::ALL { - if ui.selectable_label(app.session.view == ViewMode::MeshMap(m), trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(m)))])).clicked() - { - app.run("viewport.view", json!({"mode": format!("map:{}", m.id())})); + for map in BakedMap::ALL { + let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { + app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); } } ui.separator(); @@ -266,222 +442,308 @@ fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { } } +/// Camera turn per point of a drag (radians) +const ORBIT_RADIANS_PER_POINT: f32 = 0.008; + +/// Camera zoom per point of an Alt+right drag +const DRAG_ZOOM_PER_POINT: f32 = 0.01; + +/// Camera zoom per point of mouse wheel +const WHEEL_ZOOM_PER_POINT: f32 = 0.0025; + +/// Environment light turn per point of a Shift+right drag (degrees) +const LIGHT_DEGREES_PER_POINT: f32 = 0.5; + +/// Brush size change per point of Shift+wheel, as a fraction of the size +const WHEEL_BRUSH_SIZE_PER_POINT: f32 = 0.002; + +/// Stencil turn per point of an S+left drag (degrees) +const STENCIL_DEGREES_PER_POINT: f32 = 0.4; + +/// Stencil scale change per point of an S+right drag, as a fraction of the scale +const STENCIL_SCALE_PER_POINT: f32 = 0.005; + +/// Smallest stencil scale an S+right drag reaches +const MIN_STENCIL_SCALE: f32 = 0.05; + +/// Largest stencil scale an S+right drag reaches +const MAX_STENCIL_SCALE: f32 = 10.0; + +/// Smallest viewport the camera projects into, so a collapsed view keeps a usable aspect (points) +const MIN_CAMERA_VIEWPORT: f32 = 16.0; + fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let resp = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); app.viewport_rect = rect; let size = rect.size(); - app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0)); - let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift)); - let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top()); - let adjusting = brush_drag(app, ui, &resp); - let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down())); + app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT)); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); + let local = |pointer: egui::Pos2| Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); + let adjusting = brush_drag(app, ui, &response); + let navigating = !adjusting && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); - // Navigation (S + drag manipulates the projection stencil instead, below). - let delta = ui.input(|i| i.pointer.delta()); - let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); + // Navigation; S + drag moves the projection stencil instead, below + let delta = ui.input(|input| input.pointer.delta()); + let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); let stencil_drag = s_held && app.session.tool.stencil.is_some(); if stencil_drag || adjusting { - // The stencil moves, turns and scales instead of the camera (handled below), or the - // brush changes. - } else if resp.dragged_by(PointerButton::Middle) { + // The stencil or the brush changes instead of the camera + } else if response.dragged_by(PointerButton::Middle) { app.session.camera.pan(delta.x / size.y, delta.y / size.y); - } else if alt && resp.dragged_by(PointerButton::Primary) { - app.session.camera.orbit(delta.x * 0.008, delta.y * 0.008); - } else if resp.dragged_by(PointerButton::Secondary) { + } else if alt && response.dragged_by(PointerButton::Primary) { + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + } else if response.dragged_by(PointerButton::Secondary) { if alt { - app.session.camera.zoom(-delta.y * 0.01); + app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT); } else if shift { - // Shift + right drag turns the environment light. - let d = &mut app.session.doc.project.display; - d.env_rotation = (d.env_rotation + delta.x * 0.5).rem_euclid(360.0); + let display = &mut app.session.doc.project.display; + display.env_rotation = (display.env_rotation + delta.x * LIGHT_DEGREES_PER_POINT).rem_euclid(360.0); } else { - app.session.camera.orbit(delta.x * 0.008, delta.y * 0.008); + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); } } - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); + + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { if shift && app.ui.mode == crate::state::Mode::Painting { let brush = &mut app.session.tool.brush; - brush.size = (brush.size * (1.0 + scroll * 0.002)).clamp(0.0005, 0.25); + brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } else { - app.session.camera.zoom(scroll * 0.0025); + app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } } } - // Touch screens: two fingers orbit and pinch zooms, three fingers pan. A second finger - // cancels the stroke the first one started, so navigating leaves no paint behind. - let touch = ui.input(|i| i.multi_touch()).filter(|_| resp.contains_pointer() || resp.dragged()); - if let Some(t) = touch { + // Touch: two fingers orbit and pinch zooms, three pan; a second finger cancels the first one's stroke + let touch = ui.input(|input| input.multi_touch()).filter(|_| response.contains_pointer() || response.dragged()); + if let Some(gesture) = touch { if app.session.stroke_active() { app.session.cancel_stroke(); } - let d = t.translation_delta; - if t.num_touches >= 3 { - app.session.camera.pan(d.x / size.y, d.y / size.y); + + let moved = gesture.translation_delta; + if gesture.num_touches >= 3 { + app.session.camera.pan(moved.x / size.y, moved.y / size.y); } else { - app.session.camera.orbit(d.x * 0.008, d.y * 0.008); + app.session.camera.orbit(moved.x * ORBIT_RADIANS_PER_POINT, moved.y * ORBIT_RADIANS_PER_POINT); } - if t.zoom_delta.is_finite() && t.zoom_delta > 0.0 { - app.session.camera.zoom(t.zoom_delta.ln()); + if gesture.zoom_delta.is_finite() && gesture.zoom_delta > 0.0 { + app.session.camera.zoom(gesture.zoom_delta.ln()); } } - // Stencil: S + left drag rotates, S + right drag scales, S + middle drag moves. - if s_held && let Some(st) = app.session.tool.stencil.as_mut() { - if resp.dragged_by(PointerButton::Primary) { - st.rotation = (st.rotation + delta.x * 0.4).rem_euclid(360.0); - } else if resp.dragged_by(PointerButton::Secondary) { - st.scale = (st.scale * (1.0 + delta.x * 0.005)).clamp(0.05, 10.0); - } else if resp.dragged_by(PointerButton::Middle) { - st.center[0] += delta.x / size.x * 2.0; - st.center[1] -= delta.y / size.y * 2.0; + // Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it + if s_held && let Some(stencil) = app.session.tool.stencil.as_mut() { + if response.dragged_by(PointerButton::Primary) { + stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); + } else if response.dragged_by(PointerButton::Secondary) { + stencil.scale = (stencil.scale * (1.0 + delta.x * STENCIL_SCALE_PER_POINT)).clamp(MIN_STENCIL_SCALE, MAX_STENCIL_SCALE); + } else if response.dragged_by(PointerButton::Middle) { + stencil.center[0] += delta.x / size.x * 2.0; + stencil.center[1] -= delta.y / size.y * 2.0; } } - // Clone source: V + click. + + // Clone source: V + click let v_held = clone_source_key(app, ui); if v_held && !alt - && (resp.clicked_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) - && let Some(p) = resp.interact_pointer_pos() + && (response.clicked_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary)) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("tool.cloneSource", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } - // Depth of field focus pick: a click focuses there instead of painting. + + // Depth of field focus pick: a click focuses there instead of painting let focus_pick = focus_picking(ui.ctx()); if focus_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && resp.clicked_by(PointerButton::Primary) - && let Some(p) = resp.interact_pointer_pos() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("viewport.focusAt", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("viewport.focusAt", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); set_focus_picking(ui.ctx(), false); } } - // Decal placement: a click moves the decal being placed there. + + // Decal placement: a click moves the decal being placed there let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); if let Some(layer) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && resp.clicked_by(PointerButton::Primary) - && let Some(p) = resp.interact_pointer_pos() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("layer.decal.set", json!({"layer": layer.0, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("layer.decal.set", json!({"layer": layer.0, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); app.placing_decal = None; } } - // The selected decal's frame and handles: drag to move, scale or turn it. - let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect); - // Painting. + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + let popup = app.properties_popup.is_some(); + + // A pending ID color pick takes the next click instead of the brush + let picking_id_color = app.picking_id_color.is_some(); + if picking_id_color { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(position) = response.interact_pointer_pos() + { + let (pixel, viewport) = (local(position), app.session.viewport); + crate::id_color_pick::IdColorPick::pick_at(app, json!({"x": pixel.x, "y": pixel.y, "viewport": [viewport.x, viewport.y]})); + } + } + + // The selected decal's frame and handles: drag to move, scale or turn it + let decal_drag = !alt + && !s_held + && !v_held + && !focus_pick + && !popup + && placing.is_none() + && !picking_id_color + && touch.is_none() + && decal_input(app, ui, &response, rect); + + // Painting let painting = app.ui.mode == crate::state::Mode::Painting + && !popup && !alt && !adjusting && !s_held && !v_held && !focus_pick && placing.is_none() + && !picking_id_color && touch.is_none() && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; - let vp = app.session.viewport; - let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p); + let viewport = app.session.viewport; + let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); + let mut fill_box = None; if painting && path_tool { - path_input(app, ui, &resp, false, |app, p| app.session.pick(local(p), vp).map(|h| h.pos), show); + path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill(local(point), viewport), + |session, corner, opposite| session.drag_polygon_fill_box(local(corner), local(opposite), viewport), + ); } else if painting { let pressure = pen_pressure(ui); - if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { - // Shift+click paints a straight line from where the last stroke ended. + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + // Shift+click paints a straight line from where the last stroke ended let line_from = if shift { app.last_paint_point } else { None }; - if let Some(p) = resp.interact_pointer_pos() { - match app.session.begin_stroke(line_from.unwrap_or(local(p)), app.session.viewport, pressure) { + if let Some(pointer) = response.interact_pointer_pos() { + match app.session.begin_stroke(line_from.unwrap_or(local(pointer)), app.session.viewport, pressure) { Ok(_) => { if line_from.is_some() { - app.session.continue_stroke(local(p), pressure); + app.session.continue_stroke(local(pointer), pressure); } - app.last_paint_point = Some(local(p)); + app.last_paint_point = Some(local(pointer)); } - Err(e) => app.toast(e.to_string(), true), + Err(error) => app.toast(error.to_string(), true), } } - if resp.clicked_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.clicked_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - } else if resp.dragged_by(PointerButton::Primary) + } else if response.dragged_by(PointerButton::Primary) && app.session.stroke_active() - && let Some(p) = resp.interact_pointer_pos() + && let Some(pointer) = response.interact_pointer_pos() { - app.session.continue_stroke(local(p), pressure); - app.last_paint_point = Some(local(p)); + app.session.continue_stroke(local(pointer), pressure); + app.last_paint_point = Some(local(pointer)); } - if resp.drag_stopped_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.drag_stopped_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } } let frame = Frame { view_id: crate::viewport::VIEW_3D, - size: [(size.x * ui.ctx().pixels_per_point()).max(1.0) as u32, (size.y * ui.ctx().pixels_per_point()).max(1.0) as u32], + size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: shade(app), - visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection, an alpha on the brush. - crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d); + polygon_fill_box_overlay(ui, rect, fill_box); - // Brush cursor. + // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush + crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); + + // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began if app.ui.mode == crate::state::Mode::Painting && !navigating - && resp.hovered() + && response.hovered() && brush_tool(app.session.tool.tool) - // While a Ctrl+drag changes the brush, its cursor stays where the drag began. - && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() } - && let Some(hit) = app.session.pick(local(hp), app.session.viewport) + && app.picking_id_color.is_none() + && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } + && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); brush_cursor(app, ui, rect, hit.pos, hit.nrm); if app.session.tool.tool == Tool::Clone - && let Some(src) = app.session.clone_source_point(Some(hit.uv)) + && let Some(source) = app.session.clone_source_point(Some(hit.uv)) { - clone_marker(app, ui, rect, src); + clone_marker(app, ui, rect, source); } - // Shift: preview the straight line Shift+click paints from the last stroke. + + // Shift: preview the straight line Shift+click paints from the last stroke if shift && !path_tool && let Some(from) = app.last_paint_point { - rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hp); + rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos); } } + if app.ui.mode == crate::state::Mode::Painting && path_tool { - path_overlay(app, ui, rect, &resp, false, show); + path_overlay(app, ui, rect, &response, false, show); } stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); - brush_readout(app, ui, &resp, adjusting); - if app.session.quick_mask.editing { + brush_readout(app, ui, &response, adjusting); + if app.session.quick_mask.editing && app.picking_id_color.is_none() { ui.painter_at(rect).text( - rect.left_top() + vec2(12.0, 40.0), + rect.left_top() + QUICK_MASK_NOTICE_OFFSET, egui::Align2::LEFT_TOP, tr("Editing quick mask: paint where painting is allowed (U to finish)"), - egui::FontId::proportional(12.0), - Color32::from_rgb(0xe8, 0x6a, 0x6a), + egui::FontId::proportional(QUICK_MASK_NOTICE_TEXT_SIZE), + QUICK_MASK_NOTICE_COLOR, ); } + if app.ui.mode == crate::state::Mode::Baking { + crate::bake_mode::bake_visualization_panel(app, ui, rect); + } view_header(app, ui, rect, "v3d"); axis_gizmo(ui, rect, app, false); } +/// Where the quick-mask editing notice sits from the 3D view's top-left corner, its text size and its warning red +const QUICK_MASK_NOTICE_OFFSET: egui::Vec2 = vec2(12.0, 40.0); +const QUICK_MASK_NOTICE_TEXT_SIZE: f32 = 12.0; +const QUICK_MASK_NOTICE_COLOR: Color32 = Color32::from_rgb(0xe8, 0x6a, 0x6a); + +/// What bake mode's 3D view draws besides the low poly (nothing in the other modes) +fn bake_visualization(app: &TextureCraftApp) -> Option { + (app.ui.mode == crate::state::Mode::Baking).then(|| app.ui.bake_visualization.visualization(app.session.ts())).flatten() +} + /// What a drag on the selected decal's frame does. #[derive(Clone, Copy, Debug, PartialEq)] enum DecalGrab { @@ -716,6 +978,10 @@ const HANDLE_GRAB: f32 = 8.0; /// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with /// the global shortcuts, cancels it). fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { + #[cfg(not(target_arch = "wasm32"))] + if crate::updates_ui::blocks_input(app) { + return; + } if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() @@ -809,11 +1075,101 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons } } -/// Dashed preview of a straight segment. +/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes. fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let p = ui.painter_at(rect); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0)); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); + let Some(visible) = visible_dashes(rect, from, to) else { return }; + let painter = ui.painter_at(rect); + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + } +} + +/// The part of `from`→`to` inside `rect`, its start moved back to a whole dash period so the dashes keep their place. +fn visible_dashes(rect: Rect, from: Pos2, to: Pos2) -> Option<[Pos2; 2]> { + let direction = to - from; + let length = direction.length(); + if length == 0.0 { + return rect.contains(from).then_some([from, to]); + } + + // Clip the segment's parameter range against each axis's slab + let (mut enter, mut exit) = (0.0_f32, 1.0_f32); + for (delta, origin, low, high) in [(direction.x, from.x, rect.left(), rect.right()), (direction.y, from.y, rect.top(), rect.bottom())] { + if delta == 0.0 { + if origin < low || origin > high { + return None; + } + continue; + } + let (at_low, at_high) = ((low - origin) / delta, (high - origin) / delta); + enter = enter.max(at_low.min(at_high)); + exit = exit.min(at_low.max(at_high)); + } + if enter > exit { + return None; + } + + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let start = (enter * length / period).floor() * period / length; + Some([from + direction * start, from + direction * exit]) +} + +/// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image +fn polygon_fill_input( + app: &mut TextureCraftApp, + ui: &Ui, + response: &egui::Response, + fill_at: impl Fn(&mut Session, Pos2) -> texturecraft_engine::Result, + drag_box: impl Fn(&mut Session, Pos2, Pos2) -> texturecraft_engine::Result, +) -> Option { + let origin_id = response.id.with("polygon_fill_box"); + let dragging = response.dragged_by(PointerButton::Primary); + let released = response.drag_stopped_by(PointerButton::Primary); + let held = ui.input(|input| input.pointer.primary_down()); + if !held && !released { + // A drag this view started and cut short (Alt, a second finger) keeps what it filled as one step + if ui.data_mut(|data| data.remove_temp::(origin_id)).is_some() { + app.session.end_polygon_fill_box(); + } + } else if dragging && let Some(press) = ui.input(|input| input.pointer.press_origin()) { + ui.data_mut(|data| data.insert_temp(origin_id, press)); + } + + // Consume the origin on release so a new press cannot resume the previous rectangle + let origin = if released { ui.data_mut(|data| data.remove_temp::(origin_id)) } else { ui.data(|data| data.get_temp::(origin_id)) }; + let pointer = ui.input(|input| input.pointer.latest_pos()); + let (filled, dragged_box) = match (origin, pointer) { + _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), + (Some(origin), Some(pointer)) if released => { + // The drag ends on release even when its last move failed + let shown = drag_box(&mut app.session, origin, pointer); + let filled = app.session.end_polygon_fill_box(); + (Some(shown.map(|_| filled)), None) + } + _ if released => { + app.session.end_polygon_fill_box(); + (None, None) + } + (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), + _ => (None, None), + }; + + if let Some(Err(error)) = filled { + app.toast(error.to_string(), true); + } + + dragged_box +} + +/// How strongly the polygon fill box tints what it covers (0..1) +const FILL_BOX_TINT: f32 = 0.15; + +/// The polygon fill box being dragged, over view `rect` +fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option) { + let Some(fill_box) = fill_box else { return }; + + let accent = Tokens::get(ui.ctx()).viewport_accent; + ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside); } /// V held with the Clone tool in painting mode: clicks set the clone source. @@ -880,15 +1236,23 @@ fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjustin p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); } -/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else -/// the flow (x) and angle (y); dragging up raises hardness and angle. -fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) { +/// Size fraction, hardness and flow change per point of a Ctrl+drag +const CTRL_DRAG_RATE_PER_POINT: f32 = 0.005; + +/// Brush angle change per point of a Ctrl+left drag (degrees) +const CTRL_DRAG_DEGREES_PER_POINT: f32 = 0.5; + +/// Highest hardness a Ctrl+right drag sets +const CTRL_DRAG_MAX_HARDNESS: f32 = 0.999; + +/// Brush change for a Ctrl+drag by `drag` points: a right drag sets the size (x) and hardness (y), a left drag the flow (x) and angle (y); up raises hardness and angle +fn adjust_brush(brush: &mut texturecraft_engine::paint::BrushSettings, right: bool, drag: egui::Vec2) { if right { - b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25); - b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999); + brush.size = (brush.size * (1.0 + drag.x * CTRL_DRAG_RATE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + brush.hardness = (brush.hardness - drag.y * CTRL_DRAG_RATE_PER_POINT).clamp(0.0, CTRL_DRAG_MAX_HARDNESS); } else { - b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0); - b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0; + brush.flow = (brush.flow + drag.x * CTRL_DRAG_RATE_PER_POINT).clamp(0.0, 1.0); + brush.angle = (brush.angle - drag.y * CTRL_DRAG_DEGREES_PER_POINT + 180.0).rem_euclid(360.0) - 180.0; } } @@ -953,137 +1317,210 @@ fn pen_pressure(ui: &Ui) -> f32 { } } +/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); - let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|i| i.modifiers.alt); - let adjusting = brush_drag(app, ui, &resp); - let delta = ui.input(|i| i.pointer.delta()); - if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) { + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); + let adjusting = brush_drag(app, ui, &response); + + // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor + let delta = ui.input(|input| input.pointer.delta()); + if response.dragged_by(PointerButton::Middle) || (alt && response.dragged_by(PointerButton::Primary)) { app.ui.uv_pan[0] += delta.x / size.x * 2.0; app.ui.uv_pan[1] -= delta.y / size.y * 2.0; } - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { - let old = app.ui.uv_zoom; - let new = (old * (1.0 + scroll * 0.002)).clamp(0.1, 40.0); - // Zoom about the cursor. - if let Some(hp) = resp.hover_pos() { - let c = [(hp.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hp.y - rect.top()) / size.y * 2.0]; - for k in 0..2 { - app.ui.uv_pan[k] = c[k] - (c[k] - app.ui.uv_pan[k]) * new / old; + let old_zoom = app.ui.uv_zoom; + let new_zoom = (old_zoom * (1.0 + scroll * UV_WHEEL_ZOOM_PER_POINT)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); + if let Some(hover_pos) = response.hover_pos() { + let cursor = [(hover_pos.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hover_pos.y - rect.top()) / size.y * 2.0]; + for axis in 0..2 { + app.ui.uv_pan[axis] = cursor[axis] - (cursor[axis] - app.ui.uv_pan[axis]) * new_zoom / old_zoom; } } - app.ui.uv_zoom = new; + app.ui.uv_zoom = new_zoom; } } + + // Conversions between the view's points and the texture set's UV space let ts = app.session.ts(); let set = app.session.doc.project.texture_sets.get(ts); - let [sx, sy] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |t| t.size())); + let [scale_x, scale_y] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |texture_set| texture_set.size())); let pan = app.ui.uv_pan; - let to_uv = |p: egui::Pos2| { - let xc = (p.x - rect.left()) / size.x * 2.0 - 1.0; - let yc = 1.0 - (p.y - rect.top()) / size.y * 2.0; - Vec2::new(((xc - pan[0]) / sx + 1.0) * 0.5, (1.0 - (yc - pan[1]) / sy) * 0.5) + let to_uv = |pointer: egui::Pos2| { + let clip_x = (pointer.x - rect.left()) / size.x * 2.0 - 1.0; + let clip_y = 1.0 - (pointer.y - rect.top()) / size.y * 2.0; + Vec2::new(((clip_x - pan[0]) / scale_x + 1.0) * 0.5, (1.0 - (clip_y - pan[1]) / scale_y) * 0.5) }; - let to = |u: f32, v: f32| { - let x = (u * 2.0 - 1.0) * sx + pan[0]; - let y = (1.0 - v * 2.0) * sy + pan[1]; - pos2(rect.left() + (x * 0.5 + 0.5) * size.x, rect.top() + (0.5 - y * 0.5) * size.y) + let to_screen = |u: f32, v: f32| { + let clip_x = (u * 2.0 - 1.0) * scale_x + pan[0]; + let clip_y = (1.0 - v * 2.0) * scale_y + pan[1]; + pos2(rect.left() + (clip_x * 0.5 + 0.5) * size.x, rect.top() + (0.5 - clip_y * 0.5) * size.y) }; - let show = |_: &TextureCraftApp, p: Vec3| Some(to(p.x, p.y)); + let show = |_: &TextureCraftApp, point: Vec3| Some(to_screen(point.x, point.y)); let path_tool = app.session.tool.tool == Tool::Path; - // Clone source (V + click) and painting in UV space. + + // Clone source: V + click let v_held = clone_source_key(app, ui); if v_held - && (resp.clicked_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) - && let Some(p) = resp.interact_pointer_pos() + && (response.clicked_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary)) + && let Some(pointer) = response.interact_pointer_pos() { - let uv = to_uv(p); + let uv = to_uv(pointer); app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]})); } + let bake_paint_on = app.ui.mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on && !alt; if bake_paint_on { - bake_paint_input(app, ui, &resp, &to_uv); + bake_paint_input(app, ui, &response, &to_uv); } - let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held; + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); + + // A pending ID color pick takes the next click instead of the brush + let picking_id_color = app.picking_id_color.is_some(); + if picking_id_color { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(position) = response.interact_pointer_pos() + { + let uv = to_uv(position); + crate::id_color_pick::IdColorPick::pick_at(app, json!({"uv": [uv.x, uv.y]})); + } + } + + // Painting in UV space + let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held && !picking_id_color; + let mut fill_box = None; if painting && path_tool { - path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show); + path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill_uv(to_uv(point)), + |session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)), + ); } else if painting { - let pressure = pen_pressure(ui); - if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { - if let Some(p) = resp.interact_pointer_pos() - && let Err(e) = app.session.begin_stroke_uv(to_uv(p), pressure) - { - app.toast(e.to_string(), true); - } - if resp.clicked_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() - { - app.toast(e.to_string(), true); - } - } else if resp.dragged_by(PointerButton::Primary) - && app.session.stroke_active() - && let Some(p) = resp.interact_pointer_pos() - { - app.session.continue_stroke_uv(to_uv(p), pressure); - } - if resp.drag_stopped_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() - { - app.toast(e.to_string(), true); - } + paint_2d_input(app, ui, &response, shift, &to_uv); } - if resp.double_clicked() && !(painting && path_tool) { + if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; app.ui.uv_pan = [0.0, 0.0]; } + let frame = Frame { view_id: VIEW_2D, - size: [(size.x * ui.ctx().pixels_per_point()).max(1.0) as u32, (size.y * ui.ctx().pixels_per_point()).max(1.0) as u32], + size: frame_size_in_pixels(ui, rect), kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), - visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View2d); - // The UV tile outlines (numbered for UDIM sets) and the path being edited. + polygon_fill_box_overlay(ui, rect, fill_box); + crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); + + // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |r: Rect| painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); - match set.and_then(|t| Some((t, t.tile_grid()?))) { - Some((t, g)) => { - for (udim, (bx, by)) in t.uv_tiles.iter().filter_map(|u| Some((*u, g.block(*u)?))) { - // A tile smaller than its block fills the block's top-left corner. - let (u0, v0, k) = (bx as f32 / g.cols as f32, by as f32 / g.rows as f32, t.tile_scale(udim)); - let r = Rect::from_two_pos(to(u0, v0), to(u0 + k / g.cols as f32, v0 + k / g.rows as f32)); - outline(r); - painter.text(r.left_top() + vec2(6.0, 4.0), egui::Align2::LEFT_TOP, udim.to_string(), egui::FontId::proportional(11.0), tk.viewport_text); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); + match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { + Some((texture_set, grid)) => { + for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { + // A tile smaller than its block fills the block's top-left corner + let (u0, v0) = (block_x as f32 / grid.cols as f32, block_y as f32 / grid.rows as f32); + let tile_scale = texture_set.tile_scale(udim); + let tile = Rect::from_two_pos(to_screen(u0, v0), to_screen(u0 + tile_scale / grid.cols as f32, v0 + tile_scale / grid.rows as f32)); + outline(tile); + painter.text( + tile.left_top() + vec2(6.0, 4.0), + egui::Align2::LEFT_TOP, + udim.to_string(), + egui::FontId::proportional(11.0), + tokens.viewport_text, + ); } } None => { - outline(Rect::from_two_pos(to(0.0, 0.0), to(1.0, 1.0))); + outline(Rect::from_two_pos(to_screen(0.0, 0.0), to_screen(1.0, 1.0))); } } if app.ui.mode == crate::state::Mode::Painting && path_tool { - path_overlay(app, ui, rect, &resp, true, show); + path_overlay(app, ui, rect, &response, true, show); } + + // Shift: preview the straight line Shift+click paints from the last stroke + if painting + && shift + && !path_tool + && brush_tool(app.session.tool.tool) + && let Some(from) = app.last_paint_uv.and_then(|point| point.uv_for(&app.session)) + && let Some(hover) = response.hover_pos() + { + rubber_band(ui, rect, to_screen(from.x, from.y), hover); + } + if app.ui.mode == crate::state::Mode::Baking { - bake_paint_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0)); - if bake_paint_on && let Some(hover) = resp.hover_pos() { - let r = (to(app.ui.bake_paint_brush.radius, 0.0).x - to(0.0, 0.0).x).abs().max(2.0); - painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200))); + bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); + if bake_paint_on && let Some(hover) = response.hover_pos() { + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); + painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } - brush_readout(app, ui, &resp, adjusting); + + brush_readout(app, ui, &response, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); - let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default(); - ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tk.viewport_text); - let _ = (RichText::new(""), Channel::BaseColor); + let name = app.session.doc.project.texture_sets.get(ts).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); + ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); +} + +/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. +fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let pressure = pen_pressure(ui); + + // Where the stroke under way is; it becomes the line start only when the stroke finishes + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + let line_start = app.last_paint_uv.filter(|_| shift).and_then(|point| point.uv_for(&app.session)); + if let Some(pointer) = response.interact_pointer_pos() { + let uv = to_uv(pointer); + match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) { + Ok(()) => { + if line_start.is_some() { + app.session.continue_stroke_uv(uv, pressure); + } + ui.data_mut(|data| data.insert_temp(stroke_end, crate::uv_paint_point::UvPaintPoint::new(&app.session, uv))); + } + Err(error) => app.toast(error.to_string(), true), + } + } + } else if response.dragged_by(PointerButton::Primary) + && app.session.stroke_active() + && let Some(pointer) = response.interact_pointer_pos() + { + let uv = to_uv(pointer); + app.session.continue_stroke_uv(uv, pressure); + ui.data_mut(|data| data.insert_temp(stroke_end, crate::uv_paint_point::UvPaintPoint::new(&app.session, uv))); + } + + // Escape cancels the stroke and ends the drag without a primary release, so a cancelled stroke never gets here + if response.clicked_by(PointerButton::Primary) || response.drag_stopped_by(PointerButton::Primary) { + let finishing = app.session.stroke_active(); + match app.session.end_stroke() { + Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) => {} + Err(error) => app.toast(error.to_string(), true), + } + } } /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). @@ -1137,3 +1574,34 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t }; painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + +#[cfg(test)] +mod tests { + use super::*; + + const VIEW: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); + const DASH_PERIOD: f32 = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + + #[test] + fn a_far_start_is_clipped_to_the_view_on_a_whole_dash_period() { + let far_start = pos2(-10_003.0, 50.0); + + let [start, end] = visible_dashes(VIEW, far_start, pos2(50.0, 50.0)).unwrap(); + + assert!(start.x <= VIEW.left() && start.x > VIEW.left() - DASH_PERIOD, "starts at the view's edge: {start:?}"); + let periods = (start.x - far_start.x) / DASH_PERIOD; + assert!((periods - periods.round()).abs() < 1e-3, "a whole number of dash periods from the real start: {periods}"); + assert_eq!(end, pos2(50.0, 50.0)); + } + + #[test] + fn a_segment_inside_the_view_is_kept_whole() { + assert_eq!(visible_dashes(VIEW, pos2(10.0, 20.0), pos2(90.0, 80.0)), Some([pos2(10.0, 20.0), pos2(90.0, 80.0)])); + } + + #[test] + fn a_segment_outside_the_view_draws_nothing() { + assert_eq!(visible_dashes(VIEW, pos2(-50.0, -10.0), pos2(150.0, -10.0)), None); + assert_eq!(visible_dashes(VIEW, pos2(-50.0, 120.0), pos2(120.0, 300.0)), None); + } +} diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 6ebe87ec..759d5576 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -77,28 +77,33 @@ pub fn poll(app: &mut TextureCraftApp) { } } -/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog; in -/// the browser they arrive on a later frame. +/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog. The +/// meshes load on a later frame, when the dialog answers. #[cfg(not(target_arch = "wasm32"))] pub fn import_bake_mesh(app: &mut TextureCraftApp, _ctx: &egui::Context, cage: bool) { - let dialog = rfd::FileDialog::new().add_filter(tr("Meshes"), &MESH_EXTENSIONS); - let paths = if cage { dialog.pick_file().into_iter().collect() } else { dialog.pick_files().unwrap_or_default() }; - for p in paths { - let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; - app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); - } + use crate::file_dialogs::{Bound, FileDialog}; + let dialog = if cage { FileDialog::open() } else { FileDialog::open_many() }; + app.ask_file(dialog.filter(tr("Meshes"), &MESH_EXTENSIONS), Bound::Project, move |app, paths| { + for p in paths { + let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; + app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); + } + }); } /// Display settings › Import HDR: pick an equirect `.hdr`/`.exr`, import it as a resource and -/// light the scene with it (in the browser the file arrives on a later frame). +/// light the scene with it, on a later frame when the dialog answers. #[cfg(not(target_arch = "wasm32"))] pub fn import_environment(app: &mut TextureCraftApp, _ctx: &egui::Context) { - let Some(p) = rfd::FileDialog::new().add_filter(tr("HDR environments"), ENV_EXTS).pick_file() else { return }; - if let Some(r) = app.run("resource.import", serde_json::json!({ "path": p.display().to_string() })) - && let Some(name) = r.get("name").and_then(|n| n.as_str()) - { - use_environment(app, name); - } + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::open().filter(tr("HDR environments"), ENV_EXTS), Bound::Project, |app, paths| { + let Some(p) = paths.first() else { return }; + if let Some(r) = app.run("resource.import", serde_json::json!({ "path": p.display().to_string() })) + && let Some(name) = r.get("name").and_then(|n| n.as_str()) + { + use_environment(app, name); + } + }); } /// Make image resource `name` the environment. diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eb3a8eb4..79aa7eab 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -174,25 +174,56 @@ pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color painter.layout_job(job) } -/// A square icon button (Phosphor glyph) in a rounded tool well: `selected` sits in the accent -/// tinted well (the shared Craft icon button, `craft_ui::buttons`). +/// A square Phosphor icon button with a tooltip and an accent well when selected pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: f32) -> Response { - let tk = Tokens::get(ui.ctx()); + icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) +} + +/// Icon glyph size as a fraction of the button height +const ICON_SCALE: f32 = 0.62; + +/// Extra width an `icon_dropdown_button` gives its caret, as a fraction of the button height +const CARET_STRIP_SCALE: f32 = 0.34; + +/// An `icon_button` with no tooltip, whose `label` still names it for screen readers +pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * ICON_SCALE), color); + }) +} + +/// Width of an `icon_dropdown_button` `size` high: the square icon and the caret strip after it +pub fn icon_dropdown_button_width(size: f32) -> f32 { + size * (1.0 + CARET_STRIP_SCALE) +} + +/// An `icon_button_without_tooltip` with a dropdown caret after the icon, drawn in the icon's color +pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { + // Caret glyph size, and how far its center sits from the right edge, as fractions of the height + const CARET_SCALE: f32 = 0.34; + const CARET_INSET_SCALE: f32 = 0.25; + + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { + let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); + let caret_center = rect.right_center() - vec2(size * CARET_INSET_SCALE, 0.0); + ui.painter().text(icon_center, egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * ICON_SCALE), color); + ui.painter().text(caret_center, egui::Align2::CENTER_CENTER, egui_phosphor::regular::CARET_DOWN, egui::FontId::proportional(size * CARET_SCALE), color); + }) +} + +/// Transparent at rest, a hover well, and the active-tool well when pressed or selected +fn icon_button_style(tokens: &Tokens) -> IconButtonStyle { let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; - let style = IconButtonStyle { - normal: well(Color32::TRANSPARENT, tk.text), - hovered: well(tk.row_hover, tk.text_strong), - pressed: Some(well(tk.tool_active, tk.text_strong)), - selected: well(tk.tool_active, tk.text_strong), + IconButtonStyle { + normal: well(Color32::TRANSPARENT, tokens.text), + hovered: well(tokens.row_hover, tokens.text_strong), + pressed: Some(well(tokens.tool_active, tokens.text_strong)), + selected: well(tokens.tool_active, tokens.text_strong), corner_radius: CornerRadius::same(6), - focus_stroke: Stroke::new(1.0, tk.accent), - }; - IconButton::new(tooltip, vec2(size, size), &style) - .selected(selected) - .show(ui, |ui, rect, color| { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); - }) - .on_hover_text(tooltip) + focus_stroke: Stroke::new(1.0, tokens.accent), + } } /// A flat button filled with the accent, white lettering (a dialog's main action). diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 7708e21f..46c8f1db 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -9,8 +9,11 @@ use texturecraft_engine::geom::primitives::BUILTINS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; +#[cfg(not(target_arch = "wasm32"))] +use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; +use crate::new_project_advanced::COMBO_WIDTH; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; @@ -36,52 +39,100 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved app.session.modified } +/// The close decision, once per frame in `logic` (which also runs while the window is minimized): +/// a close with unsaved changes waits on the dialog, in a window brought back so it can be +/// answered. A close nothing holds open quits through the platform's own path (craft-quit). +pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { + let closing = ctx.input(|i| i.viewport().close_requested()); + // A stroke still open at the close, or released in this frame, is a change to ask about. + if closing + && app.session.stroke_active() + && let Err(error) = app.session.end_stroke() + { + app.toast(error.to_string(), true); + } + if closing && ask_to_save(app, crate::state::Unsaved::Quit) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + if ctx.input(|i| i.viewport().minimized == Some(true)) { + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + } + craft_quit::on_close_request(ctx); +} + /// Quitting, opening or closing a project with unsaved changes asks whether to save them first /// (in the browser, Save downloads the project). fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; - if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - } - let Some(then) = app.ui.windows.unsaved.clone() else { return }; + + let Some(pending) = app.ui.windows.unsaved.clone() else { return }; + + #[cfg(not(target_arch = "wasm32"))] + let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt, std::mem::take(&mut app.prompt_saved)); + #[cfg(target_arch = "wasm32")] + let (waiting_for_save, saved_by_dialog) = (false, false); + let mut open = true; - let mut save = None; + let mut save_first = None; let mut cancel = false; - let name: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; - let question = - if then == Unsaved::Quit { trf("Save the changes to {name} before closing?", &name) } else { trf("Save the changes to {name} first?", &name) }; + let question_args: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; + let question = if pending == Unsaved::Quit { + trf("Save the changes to {name} before closing?", &question_args) + } else { + trf("Save the changes to {name} first?", &question_args) + }; dialog("unsaved", tr("Unsaved changes"), &mut open).show(ctx, |ui| { ui.label(question); ui.add_space(8.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(primary_button(ui, tr("Save"))).clicked() { - save = Some(true); - } - if ui.button(tr("Don't save")).clicked() { - save = Some(false); - } - if ui.button(tr("Cancel")).clicked() { - cancel = true; - } + + // One row keeps the window to its contents; a bare right-to-left layout fills the screen height + ui.horizontal(|ui| { + // The answers wait while the Save dialog is open + ui.add_enabled_ui(!waiting_for_save, |ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(primary_button(ui, tr("Save"))).clicked() { + save_first = Some(true); + } + if ui.button(tr("Don't save")).clicked() { + save_first = Some(false); + } + if ui.button(tr("Cancel")).clicked() { + cancel = true; + } + }); + }); }); }); if !open || cancel { app.ui.windows.unsaved = None; + #[cfg(not(target_arch = "wasm32"))] + { + app.saving_for_prompt = false; + } } - match save { + + match save_first { Some(true) => { + // An untitled project is saved from a dialog that answers on a later frame + #[cfg(not(target_arch = "wasm32"))] + { + app.saving_for_prompt = app.session.path.is_none(); + } file_action(app, ctx, "file.save"); } - // Going ahead anyway: the changes are let go. + // Going ahead anyway: the changes are let go Some(false) => app.session.modified = false, + None if saved_by_dialog => {} None => return, } - // A cancelled or failed save keeps the project and this dialog open. + + // A canceled or failed save keeps the project and this dialog open if app.session.modified { return; } app.ui.windows.unsaved = None; - match then { + match pending { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), #[cfg(not(target_arch = "wasm32"))] @@ -377,24 +428,28 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; } + let mut open = true; let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { ui.label(tr("3D mesh")); ui.horizontal(|ui| { let label = app.ui.new_project.file.clone().unwrap_or_else(|| { BUILTINS .iter() .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, l)| trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) .unwrap_or_default() }); - egui::ComboBox::from_id_salt("np_mesh").width(200.0).selected_text(label).show_ui(ui, |ui| { - for (id, l) in BUILTINS { + egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| { + for (id, builtin_label) in BUILTINS { if ui - .selectable_label(app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .selectable_label( + app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), + trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]), + ) .clicked() { app.ui.new_project.mesh = id.to_string(); @@ -402,22 +457,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { } } }); - if file_dialogs_available() - && ui.button(tr("Select...")).clicked() - && let Some(p) = pick_mesh_file() - { - app.ui.new_project.file = Some(p); + if file_dialogs_available() && ui.button(tr("Select...")).clicked() { + ask_mesh_file(app); } }); ui.end_row(); ui.label(tr("Project template")); - let np = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(200.0).selected_text(np.template.clone()).show_ui(ui, |ui| { - let user = app.session.templates.list.iter(); - for t in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user) { - if ui.selectable_label(t.name == np.template, &t.name).clicked() { - np.template = t.name.clone(); - np.resolution = t.resolution; + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + let user_templates = app.session.templates.list.iter(); + for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { + if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { + new_project.template = template.name.clone(); + new_project.resolution = template.resolution; + new_project.normal_format = None; } } }); @@ -436,20 +489,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); ui.label(tr("Document resolution")); egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| { - for r in [512u32, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_project.resolution, r, format!("{r} x {r}")); + for size in [512u32, 1024, 2048, 4096] { + ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}")); } }); ui.end_row(); ui.label(tr("UV tiles (UDIM)")); - let tiles_label = |m: Option| match m { + let tiles_label = |tiles: Option| match tiles { None => tr("Automatic (from the mesh UVs)"), Some(true) => tr("On"), Some(false) => tr("Off"), }; egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| { - for m in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, m, tiles_label(m)); + for tiles in [None, Some(true), Some(false)] { + ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); } }); ui.end_row(); @@ -458,6 +511,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + crate::new_project_advanced::advanced_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Create"))).clicked() { @@ -470,15 +525,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); if create { - let np = app.ui.new_project.clone(); - let (cmd, mesh) = match &np.file { + let new_project = app.ui.new_project.clone(); + let (command, mesh) = match &new_project.file { Some(path) => ("file.new", path.clone()), - None => ("project.new", np.mesh.clone()), + None => ("project.new", new_project.mesh.clone()), }; - let r = app.run(cmd, json!({"mesh": mesh, "resolution": np.resolution, "name": np.name, "uvTiles": np.uv_tiles, "template": np.template})).map(|_| ()); - if r.is_some() { + let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template}); + if app.run(command, params).is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; + crate::new_project_advanced::apply_after_create(app, &new_project); } } if !open { @@ -491,6 +547,8 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = app.ui.windows.settings; // A language whose script no font draws is listed by its English name and disabled. let drawable = LANGUAGES.each_ref().map(|l| crate::fonts::Script::of_language(l.code).is_none_or(|s| app.fonts.covers(s))); + #[cfg(not(target_arch = "wasm32"))] + let mut pick_data_folder = false; window("settings", tr("Settings"), &mut open).default_width(360.0).show(ctx, |ui| { let p = &mut app.ui.prefs; // Every section is a two-column form: labels on the left, controls aligned beside them. @@ -592,10 +650,8 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { let default = crate::data_folder("").display().to_string(); ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(260.0)); - if ui.button("...").clicked() - && let Some(d) = rfd::FileDialog::new().set_directory(crate::data_folder(&p.data_folder)).pick_folder() - { - p.data_folder = d.display().to_string(); + if ui.button("...").clicked() { + pick_data_folder = true; } }); ui.end_row(); @@ -620,10 +676,17 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); app.ui.windows.settings = open; + #[cfg(not(target_arch = "wasm32"))] + if pick_data_folder { + app.ask_file(FileDialog::folder().directory(crate::data_folder(&app.ui.prefs.data_folder)), Bound::App, |app, paths| { + if let Some(d) = paths.first() { + app.ui.prefs.data_folder = d.display().to_string(); + } + }); + } } -/// Browser File › Export Mesh: pick the download format (the desktop picks it in the save -/// dialog). +/// Browser File › Export Mesh: pick the download format #[cfg(target_arch = "wasm32")] fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { let formats = [ @@ -634,18 +697,20 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export_mesh { return; } + let mut open = true; let mut picked = None; dialog("export_mesh", tr("Export mesh"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Download as"))); - for (ext, label, hint) in formats { - if ui.add_sized(vec2(220.0, 24.0), egui::Button::new(label)).on_hover_text(hint).clicked() { - picked = Some(ext); + for (extension, label, hint) in formats { + if ui.add_sized(vec2(220.0, ui.spacing().interact_size.y), egui::Button::new(label)).on_hover_text(hint).clicked() { + picked = Some(extension); } } }); - if let Some(ext) = picked { - crate::web_files::export_mesh(app, ext); + + if let Some(extension) = picked { + crate::web_files::export_mesh(app, extension); open = false; } app.ui.windows.export_mesh = open; @@ -688,14 +753,17 @@ pub fn file_dialogs_available() -> bool { } #[cfg(not(target_arch = "wasm32"))] -fn pick_mesh_file() -> Option { - rfd::FileDialog::new().add_filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS).pick_file().map(|p| p.display().to_string()) +fn ask_mesh_file(app: &mut TextureCraftApp) { + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::App, |app, paths| { + if let Some(p) = paths.first() { + app.ui.new_project.file = Some(p.display().to_string()); + } + }); } #[cfg(target_arch = "wasm32")] -fn pick_mesh_file() -> Option { - None -} +fn ask_mesh_file(_app: &mut TextureCraftApp) {} /// Remember a project path in File ▸ Recent projects. pub fn remember(app: &mut TextureCraftApp, path: &str) { @@ -708,28 +776,29 @@ pub fn remember(app: &mut TextureCraftApp, path: &str) { #[cfg(not(target_arch = "wasm32"))] pub fn layout_file(app: &mut TextureCraftApp, save: bool) { let dir = crate::user_dir("layouts"); - let dialog = rfd::FileDialog::new().add_filter(tr("UI layout"), &["json"]).set_directory(&dir); - let result = if save { - let Some(path) = dialog.set_file_name("layout.json").save_file() else { return }; - let layout = crate::UiState { recent: Vec::new(), ..app.ui.clone() }; - std::fs::create_dir_all(&dir) - .map_err(|e| e.to_string()) - .and_then(|_| serde_json::to_vec_pretty(&layout).map_err(|e| e.to_string())) - .and_then(|bytes| std::fs::write(&path, bytes).map_err(|e| e.to_string())) - .map(|_| trf("Saved UI layout {path}", &[("path", &path.display())])) - } else { - let Some(path) = dialog.pick_file() else { return }; - std::fs::read(&path).map_err(|e| e.to_string()).and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())).map( - |layout| { - app.ui.adopt_layout(layout); - trf("Loaded UI layout {path}", &[("path", &path.display())]) - }, - ) - }; - match result { - Ok(msg) => app.toast(msg, false), - Err(e) => app.toast(trf("UI layout: {error}", &[("error", &e)]), true), - } + let dialog = if save { FileDialog::save().file_name("layout.json") } else { FileDialog::open() }; + app.ask_file(dialog.filter(tr("UI layout"), &["json"]).directory(dir.clone()), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + let result = if save { + let layout = crate::UiState { recent: Vec::new(), ..app.ui.clone() }; + std::fs::create_dir_all(&dir) + .map_err(|e| e.to_string()) + .and_then(|_| serde_json::to_vec_pretty(&layout).map_err(|e| e.to_string())) + .and_then(|bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())) + .map(|_| trf("Saved UI layout {path}", &[("path", &path.display())])) + } else { + std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())).map( + |layout| { + app.ui.adopt_layout(layout); + trf("Loaded UI layout {path}", &[("path", &path.display())]) + }, + ) + }; + match result { + Ok(msg) => app.toast(msg, false), + Err(e) => app.toast(trf("UI layout: {error}", &[("error", &e)]), true), + } + }); } /// The browser has no file paths; layouts persist with the rest of the UI state. @@ -743,10 +812,11 @@ pub fn layout_file(app: &mut TextureCraftApp, _save: bool) { pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool { match id { "file.open" => { - let pick = rfd::FileDialog::new().add_filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS).pick_file(); - if let Some(p) = pick { - open_path(app, &p.display().to_string()); - } + app.ask_file(FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS), Bound::App, |app, paths| { + if let Some(p) = paths.first() { + open_path(app, &p.display().to_string()); + } + }); true } "file.save" if app.session.path.is_some() => { @@ -756,83 +826,126 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } true } - "file.save" | "file.saveAs" | "file.saveCopy" => { - let name = crate::web_files::project_file_name(app); - if let Some(p) = - rfd::FileDialog::new().add_filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]).set_file_name(name).save_file() - { - let path = p.display().to_string(); - let cmd = if id == "file.saveCopy" { "file.saveCopy" } else { "file.saveAs" }; - if app.run(cmd, json!({"path": path})).is_some() { - remember(app, &path); - app.toast(trf("Saved {path}", &[("path", &path)]), false); - } - } + "file.save" | "file.saveAs" => { + ask_save_project(app, "file.saveAs"); + true + } + "file.saveCopy" => { + ask_save_project(app, "file.saveCopy"); true } "material.load" => { - for p in rfd::FileDialog::new().add_filter(tr("Materials"), crate::web_files::MATERIAL_EXTS).pick_files().unwrap_or_default() { - app.run("material.load", json!({"path": p.display().to_string()})); - } + app.ask_file(FileDialog::open_many().filter(tr("Materials"), crate::web_files::MATERIAL_EXTS), Bound::Project, |app, paths| { + for p in paths { + app.run("material.load", json!({"path": p.display().to_string()})); + } + }); true } "file.importResources" | "resource.import" => { - let picks = rfd::FileDialog::new().add_filter(tr("Images"), crate::web_files::IMAGE_EXTS).pick_files(); - for p in picks.unwrap_or_default() { - if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { - let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::Project, |app, paths| { + if paths.is_empty() { + return; } - } - app.ui.dock.focus(crate::docking::Panel::Assets); + for p in paths { + if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { + let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Imported {name}", &[("name", &name)]), false); + } + } + app.ui.dock.focus(crate::docking::Panel::Assets); + }); true } "file.importMaterialX" => { - if let Some(p) = rfd::FileDialog::new().add_filter(tr("MaterialX materials"), &["mtlx"]).pick_file() - && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) - { - let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { - app.session.log.push(format!("MaterialX {name}: {w}")); + app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| { + if let Some(p) = paths.first() + && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) + { + let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { + app.session.log.push(format!("MaterialX {name}: {w}")); + } + app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ui.dock.focus(crate::docking::Panel::Layers); } - app.toast(trf("Imported {name}", &[("name", &name)]), false); - app.ui.dock.focus(crate::docking::Panel::Layers); - } + }); true } "file.exportMesh" => { let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); - if let Some(p) = rfd::FileDialog::new() - .add_filter(tr("Wavefront OBJ with MTL, textures alongside"), &["obj"]) - .add_filter(tr("glTF binary with textures"), &["glb"]) - .add_filter(tr("USDZ with textures"), &["usdz"]) - .add_filter(tr("USD text, textures alongside"), &["usda"]) - .add_filter(tr("USD binary, textures alongside"), &["usdc"]) - .set_file_name(name) - .save_file() - && let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()})) - { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false); - } + let dialog = FileDialog::save() + .filter(tr("Wavefront OBJ with MTL, textures alongside"), &["obj"]) + .filter(tr("glTF binary with textures"), &["glb"]) + .filter(tr("USDZ with textures"), &["usdz"]) + .filter(tr("USD text, textures alongside"), &["usda"]) + .filter(tr("USD binary, textures alongside"), &["usdc"]) + .file_name(name); + app.ask_file(dialog, Bound::Project, |app, paths| { + if let Some(p) = paths.first() + && let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()})) + { + let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false); + } + }); true } "file.reimportMesh" => { - // Painted strokes follow the surface when the new mesh's UVs differ. - let path = match app.session.mesh_source { - Some(_) => None, - None => match rfd::FileDialog::new().add_filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS).pick_file() { - Some(p) => Some(p.display().to_string()), - None => return true, - }, - }; - app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})); + // The file the mesh came from is read again from disk; ask only when it's gone. + if let Some(path) = app.session.remembered_mesh_path().map(str::to_string) { + reimport_mesh(app, path); + return true; + } + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::Project, |app, paths| { + if let Some(p) = paths.first() { + reimport_mesh(app, p.display().to_string()); + } + }); true } _ => false, } } +/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog +/// request, so Save As and Save a Copy queue separately. +#[cfg(not(target_arch = "wasm32"))] +#[track_caller] +fn ask_save_project(app: &mut TextureCraftApp, cmd: &'static str) { + let name = crate::web_files::project_file_name(app); + let dialog = FileDialog::save().filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]).file_name(name); + // Save a Copy leaves the project unsaved, so it never answers the unsaved-changes prompt. + let for_prompt = app.saving_for_prompt && cmd == "file.saveAs"; + let asked = app.ask_file(dialog, Bound::Project, move |app, paths| { + let mut saved = false; + if let Some(p) = paths.first() { + let path = p.display().to_string(); + saved = app.run(cmd, json!({"path": path})).is_some(); + if saved { + remember(app, &path); + app.toast(trf("Saved {path}", &[("path", &path)]), false); + } + } + // The answer ends the wait. A canceled or failed save leaves the prompt open for an answer. + if for_prompt { + app.saving_for_prompt = false; + app.prompt_saved = saved && !app.session.modified; + } + }); + // A Save As already on its way answers for itself: the prompt's buttons stay usable. + if for_prompt && !asked { + app.saving_for_prompt = false; + } +} + +/// Reimport the mesh; painted strokes follow the surface when the new mesh's UVs differ. +#[cfg(not(target_arch = "wasm32"))] +fn reimport_mesh(app: &mut TextureCraftApp, path: String) { + app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})); +} + /// Open a project or mesh by path (menus, Recent projects, drag and drop). #[cfg(not(target_arch = "wasm32"))] pub fn open_path(app: &mut TextureCraftApp, path: &str) { @@ -920,10 +1033,12 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur ui.label(tr("Output directory")); ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut app.ui.export.dir).desired_width(360.0)); - if ui.button("...").clicked() - && let Some(d) = rfd::FileDialog::new().set_directory(&app.ui.export.dir).pick_folder() - { - app.ui.export.dir = d.display().to_string(); + if ui.button("...").clicked() { + app.ask_file(FileDialog::folder().directory(app.ui.export.dir.clone()), Bound::App, |app, paths| { + if let Some(d) = paths.first() { + app.ui.export.dir = d.display().to_string(); + } + }); } }); ui.end_row(); @@ -1104,3 +1219,95 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.export = false; } } + +#[cfg(test)] +mod tests { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + + use super::*; + use crate::state::Unsaved; + + fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(2); + h + } + + #[test] + fn a_canceled_save_dialog_does_not_answer_the_prompt() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = harness(); + let app = h.state_mut(); + app.file_dialogs.set_override(Some(Box::new(|_| crate::file_dialogs::Answer::Cancelled))); + app.ui.windows.unsaved = Some(Unsaved::Quit); + // Saved elsewhere, by a script, while the dialog was open. + app.session.modified = false; + app.saving_for_prompt = true; + ask_save_project(app, "file.saveAs"); + h.run_steps(3); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the prompt still waits for an answer"); + } + + #[test] + fn the_prompts_buttons_wait_for_its_save_dialog() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = harness(); + let app = h.state_mut(); + app.ui.windows.unsaved = Some(Unsaved::Quit); + app.session.modified = true; + h.run_steps(2); + for label in ["Save", "Don't save", "Cancel"] { + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} answers while no dialog is open"); + } + h.state_mut().saving_for_prompt = true; + h.run_steps(2); + for label in ["Save", "Don't save", "Cancel"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} waits for the Save dialog"); + } + } + + #[test] + fn a_save_a_copy_answer_does_not_end_the_prompts_wait() { + let mut h = harness(); + let app = h.state_mut(); + app.file_dialogs.set_override(Some(Box::new(|_| crate::file_dialogs::Answer::Cancelled))); + app.saving_for_prompt = true; + ask_save_project(app, "file.saveCopy"); + h.run_steps(3); + assert!(h.state().saving_for_prompt, "only the prompt's own Save As ends the wait"); + } + + #[test] + fn a_save_as_already_on_its_way_ends_the_prompts_wait() { + let mut h = harness(); + let app = h.state_mut(); + // One call site, as File › Save As and the prompt's Save share one. + for waiting in [false, true] { + app.saving_for_prompt = waiting; + ask_save_project(app, "file.saveAs"); + } + assert_eq!(app.file_dialogs.pending(), 1); + assert!(!app.saving_for_prompt, "the prompt's buttons work again"); + } + + /// A change that lands after the Save dialog saved (a bake finishing that frame) keeps the + /// question open with buttons that still answer. + #[test] + fn a_change_after_the_dialog_saved_leaves_the_prompt_usable() { + // The harness keeps the process-wide language at English while this asserts on labels. + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = harness(); + let app = h.state_mut(); + app.ui.windows.unsaved = Some(Unsaved::Quit); + app.session.modified = true; + app.prompt_saved = true; + h.run_steps(2); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the project has unsaved changes again"); + assert!(!h.state().saving_for_prompt); + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(h.state().ui.windows.unsaved.is_none()); + } +} diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs new file mode 100644 index 00000000..27c3525b --- /dev/null +++ b/crates/ui-egui/src/worker_preview.rs @@ -0,0 +1,12 @@ +//! Cached state of a worker-rendered preview + +use egui::TextureHandle; + +/// A pending, ready or failed preview +pub enum WorkerPreview { + /// Requested; the worker has not answered yet + Rendering, + Ready(TextureHandle), + /// The asset is unknown or the worker could not render it (the tile keeps its loading icon) + Failed, +} diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs deleted file mode 100644 index 409966c6..00000000 --- a/crates/ui-egui/tests/bake_mode.rs +++ /dev/null @@ -1,119 +0,0 @@ -use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; -use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization}; -use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::docking::Panel; -use texturecraft_ui_egui::state::Mode; - -fn harness(map: Option) -> Harness<'static, TextureCraftApp> { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - session.doc.project.texture_sets[0].bake = Default::default(); - session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64; - session.doc.project.texture_sets[0].bake.maps.select(map); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.mode = Mode::Baking; - harness.run_steps(4); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness -} - -fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { - harness.get_by_label(label).scroll_to_me(); - harness.run_steps(3); - harness.get_by_label(label).click(); - harness.run_steps(3); -} - -#[test] -fn output_axes_unlock_independently_and_relock_to_width() { - let mut harness = harness(None); - harness.get_by_label("Texture Sets"); - harness.get_by_label("Bake Maps"); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); - harness.run_steps(3); - let width = harness.state().session.doc.project.texture_sets[0].bake.common.resolution.pixels().to_string(); - assert!(harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); - - click(&mut harness, "Lock Output Size"); - assert!(!harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); - harness.get_all_by_value(&width).next().unwrap().click(); - harness.run_steps(3); - click(&mut harness, "128"); - let settings = &harness.state().session.doc.project.texture_sets[0].bake.common; - assert_eq!(settings.resolution, BakeResolution::R128); - assert_eq!(settings.resolution_height.map(BakeResolution::pixels), Some(width.parse().unwrap())); - - click(&mut harness, "Lock Output Size"); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.common.output_size(), (128, 128)); - assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); - harness.run_steps(3); - assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); - - harness.state_mut().ui.mode = Mode::Painting; - harness.run_steps(3); - assert!(!harness.state().ui.dock.is_open(Panel::BakeSettings)); - assert!(harness.state().ui.dock.is_open(Panel::Assets)); -} - -#[test] -fn height_controls_follow_enablement_and_manual_normalization() { - let mut harness = harness(None); - assert!(harness.query_by_label("Normalization").is_none()); - click(&mut harness, "Height"); - assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); - assert!(harness.query_by_label("Scaling Divisor").is_none()); - click(&mut harness, "Normalization"); - click(&mut harness, "Manual"); - harness.get_by_label("Scaling Divisor"); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); - - click(&mut harness, "Restore Defaults"); - assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); - assert!(harness.query_by_label("Scaling Divisor").is_none()); - click(&mut harness, "Height"); - assert!(harness.query_by_label("Normalization").is_none()); -} - -#[test] -fn curvature_controls_follow_the_method_and_notes_visibility_rules() { - let mut harness = harness(Some(BakedMap::Curvature)); - harness.get_by_label("Details"); - harness.get_by_label("Seams Intensity"); - click(&mut harness, "Enable Seams"); - assert!(harness.query_by_label("Seams Intensity").is_none()); - click(&mut harness, "Method"); - click(&mut harness, "Generate from Mesh"); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.method, CurvatureMethod::Mesh); - assert!(harness.query_by_label("Details").is_none()); - harness.get_by_label("Sampling Radius"); - assert!(harness.query_by_label("Value Bounds Min").is_none()); - assert!(harness.query_by_label("Value Bounds Max").is_none()); - click(&mut harness, "Auto Tonemapping"); - harness.get_by_label("Value Bounds Min"); - harness.get_by_label("Value Bounds Max"); - assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.mesh.auto_tonemapping); -} - -#[test] -fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { - let mut harness = harness(None); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); - harness.run_steps(3); - assert!(harness.query_by_label("Cage Type").is_none()); - assert!(harness.query_by_label("Skew Correction").is_none()); - harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); - harness.run_steps(3); - harness.get_by_label("Max Frontal Distance"); - harness.get_by_label("Skew Correction"); - click(&mut harness, "Cage Type"); - click(&mut harness, "Custom File"); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); - harness.get_by_label("Cage Scene"); - assert!(harness.query_by_label("Max Frontal Distance").is_none()); - assert!(harness.query_by_label("Skew Correction").is_none()); -} diff --git a/crates/ui-egui/tests/fixture/ui_state_before_json.ron b/crates/ui-egui/tests/fixture/ui_state_before_json.ron new file mode 100644 index 00000000..db17d424 --- /dev/null +++ b/crates/ui-egui/tests/fixture/ui_state_before_json.ron @@ -0,0 +1 @@ +(mode:Painting,layout:Split,split_ratio:0.3,dock:(version:2,layout:(root:Some(Split(axis:Horizontal,size:Ratio(0.78),first:Tabs(panels:[Viewport],active:0),second:Split(axis:Vertical,size:Ratio(0.125),first:Tabs(panels:[TextureSetList],active:0),second:Split(axis:Vertical,size:Ratio(0.57),first:Tabs(panels:[Layers,TextureSetSettings],active:0),second:Tabs(panels:[Properties],active:0))))),floating:[(id:387041999283132987,panels:[Display],active:0,rect:(960.0,90.0,300.0,380.0))]),hidden:[(Shader,(floating:Some((960.0,140.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(History,(floating:Some((960.0,190.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Log,(floating:Some((960.0,240.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(BakeMaps,(floating:None,anchor:Some(TextureSetList),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(BakeSettings,(floating:None,anchor:Some(TextureSetList),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(MeshMapBakers,(floating:None,anchor:Some(TextureSetList),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Assets,(floating:None,anchor:Some(Viewport),placement:Split(Left),size:Some(Ratio(0.115)),stack:None,sibling:[Viewport,TextureSetList,Layers,TextureSetSettings,Properties],group:None))],saved:None,locked:false),inactive_mode_dock:(version:2,layout:(root:Some(Split(axis:Horizontal,size:FixedFirst(536.0),first:Split(axis:Vertical,size:FixedSecond(160.0),first:Split(axis:Horizontal,size:FixedFirst(200.0),first:Split(axis:Vertical,size:Ratio(0.4),first:Tabs(panels:[TextureSetList],active:0),second:Tabs(panels:[MeshMapBakers],active:0)),second:Tabs(panels:[BakeSettings,BakeMaps],active:0)),second:Tabs(panels:[Log],active:0)),second:Tabs(panels:[Viewport],active:0))),floating:[]),hidden:[(Display,(floating:Some((960.0,90.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Shader,(floating:Some((960.0,140.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(History,(floating:Some((960.0,190.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Assets,(floating:None,anchor:Some(Viewport),placement:Split(Left),size:Some(Ratio(0.115)),stack:None,sibling:[Viewport,TextureSetList,Layers,TextureSetSettings,Properties],group:None)),(Layers,(floating:None,anchor:Some(TextureSetSettings),placement:Tab(before:Some(TextureSetSettings)),size:None,stack:None,sibling:[],group:None)),(TextureSetSettings,(floating:None,anchor:Some(Layers),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Properties,(floating:None,anchor:Some(Layers),placement:Split(Bottom),size:Some(Ratio(0.57)),stack:None,sibling:[Layers,TextureSetSettings],group:None))],saved:None,locked:false),dock_is_baking:false,bake_layout_version:1,selected_baked_map:None,hide_ui:false,windows:(export:false,new_project:false,about:false,shortcuts:false,settings:false,export_mesh:false),uv_zoom:1.0,uv_pan:(0.0,0.0),layer_channel:BaseColor,shelf_filter:"",shelf_tab:0,props_tab:Brush,text:(text:"",font:"",style:""),rename:None,new_project:(mesh:"material_ball",resolution:2048,name:"Untitled",file:None,uv_tiles:None,template:"PBR - Metallic Roughness"),uv_wireframe:true,wireframe_3d:false,render:(max_samples:256,bounces:6,denoise:true,cpu:false),prefs:(ui_scale:1.0,autosave_minutes:10,language:"en",viewport_texture:0,brightness:mediumDark,accent:copper,system_title_bar:false,start_window:true,data_folder:""),export:(dir:"/example/export",preset:"Document channels + Normal + AO",format:"",bit_depth:0,padding:"infinite",dilation:16,size:0,normal_format:"",color_space:"",skip:[],tab:0),recent:["/example/project-0.tcraft","/example/project-1.tcraft","/example/project-2.tcraft","/example/project-3.tcraft","/example/project-4.tcraft","/example/project-5.tcraft","/example/project-6.tcraft","/example/project-7.tcraft","/example/project-8.tcraft","/example/project-9.tcraft","/example/project-10.tcraft","/example/project-11.tcraft","/example/project-12.tcraft","/example/project-13.tcraft","/example/project-14.tcraft","/example/project-15.tcraft","/example/project-16.tcraft","/example/project-17.tcraft","/example/project-18.tcraft","/example/project-19.tcraft"],keymap:{},bake_paint_brush:(on:false,target:Skew,radius:0.03,value:1.0,hardness:0.5)) diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs new file mode 100644 index 00000000..1b330244 --- /dev/null +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -0,0 +1,508 @@ +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A bake-mode app with only `map` enabled and Mesh Map Settings in front +fn harness(map: Option) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake = Default::default(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64; + session.doc.project.texture_sets[0].bake.maps.select(map); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); + harness.run_steps(3); + harness +} + +/// The maps the first texture set will bake +fn enabled_maps(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets[0].bake.maps.enabled().collect() +} + +/// Click a map's row in Mesh Map Bakers, which shows its settings +fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(Role::Button, name).click(); + harness.run_steps(3); +} + +/// Click a checkbox in Mesh Map Bakers: a map's row or Check All +fn click_checkbox(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(Role::CheckBox, name).click(); + harness.run_steps(3); +} + +/// Scroll the widget labelled `label` into view and click it +fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + harness.get_by_label(label).click(); + harness.run_steps(3); +} + +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let label_row = harness.get_by_label(label).rect().center().y; + harness.get_all_by_role(Role::TextInput).find(|node| (node.rect().center().y - label_row).abs() < 4.0).unwrap() +} + +#[test] +fn mesh_map_edits_update_all_sets_without_copying_unedited_fields() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + assert_eq!(session.set_count(), 2); + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.rays = 16; + second.maps.ao.parameters.ground_plane.offset = 3.0; + second.maps.height.parameters.scaling_divisor = 2.0; + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + + click_checkbox(&mut harness, "Ground Plane"); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters.ground_plane.enabled = true; + } + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + assert_eq!(session.history_labels().len(), history_steps + 1); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, expected); +} + +#[test] +fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.maps.select([BakedMap::Height]); + let before = session.doc.project.clone(); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + click_checkbox(&mut harness, "Apply Diffusion"); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.common.apply_diffusion = false; + } + assert_eq!(harness.state().session.doc.project, expected); + + harness.get_all_by_value("64").next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "256"); + for texture_set in &mut expected.texture_sets { + texture_set.bake.common.resolution = BakeResolution::R256; + } + assert_eq!(harness.state().session.doc.project, expected); + + click_checkbox(&mut harness, "Use Low Poly Mesh as High Poly Mesh"); + for texture_set in &mut expected.texture_sets { + texture_set.bake.high_poly.use_low_as_high = true; + } + assert_eq!(harness.state().session.doc.project, expected); +} + +#[test] +fn secondary_rays_edit_from_another_set_updates_all_sets() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + session.doc.project.texture_sets[1].bake = BakeSettings::default(); + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16; + texturecraft_engine::execute(session, "textureSet.select", &serde_json::json!({"ts": 1})).unwrap(); + harness.run_steps(3); + select_map(&mut harness, "Ambient Occlusion"); + let history_steps = harness.state().session.history_labels().len(); + + number_field(&harness, "Secondary Rays").focus(); + harness.run_steps(2); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.run_steps(1); + number_field(&harness, "Secondary Rays").type_text("128"); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + let session = &harness.state().session; + assert_eq!(session.ts(), 1); + for texture_set in &session.doc.project.texture_sets { + assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 128); + } + assert_eq!(session.history_labels().len(), history_steps + 1); +} + +#[test] +fn map_selection_stays_per_set() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let second = harness.state().session.doc.project.texture_sets[1].bake.clone(); + + click_checkbox(&mut harness, "Ambient Occlusion"); + assert!(enabled_maps(&harness).is_empty()); + assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second); + + click_checkbox(&mut harness, "Check All"); + assert_eq!(enabled_maps(&harness), BakedMap::ALL); + assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second); +} + +#[test] +fn bake_texture_set_visibility_is_independent_of_bake_selection() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let before: Vec<_> = harness.state().session.doc.project.texture_sets.iter().map(|texture_set| texture_set.bake.clone()).collect(); + let active_set = harness.state().session.ts(); + + harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click(); + harness.run_steps(3); + + let session = &harness.state().session; + assert!(session.doc.project.texture_sets[0].visible); + assert!(!session.doc.project.texture_sets[1].visible); + assert_eq!(session.ts(), active_set); + for (texture_set, settings) in session.doc.project.texture_sets.iter().zip(&before) { + assert_eq!(&texture_set.bake, settings); + } + + harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click(); + harness.run_steps(3); + assert!(harness.state().session.doc.project.texture_sets[1].visible); +} + +#[test] +fn texture_set_resolution_controls_are_independent_from_bake_output() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let before = harness.state().session.doc.project.clone(); + let active_set = harness.state().session.ts(); + harness.get_all_by_value("256 × 256").nth(1).unwrap().click(); + harness.run_steps(3); + click(&mut harness, "128 × 128"); + wait_for_resolution(&mut harness, 1, 128); + + let session = &harness.state().session; + assert_eq!(session.ts(), active_set); + assert_eq!(session.doc.project.texture_sets[0], before.texture_sets[0]); + assert_eq!(session.doc.project.texture_sets[1].bake, before.texture_sets[1].bake); + harness.state_mut().session.undo().unwrap(); + assert_eq!(harness.state().session.doc.project, before); +} + +fn wait_for_resolution(harness: &mut Harness<'_, TextureCraftApp>, texture_set: usize, resolution: u32) { + for _ in 0..100 { + harness.run_steps(1); + if harness.state().session.doc.project.texture_sets[texture_set].resolution == resolution { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("texture set resize did not finish"); +} + +#[test] +fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { + let session = texturecraft_engine::Session::new_project( + "Tile resolution controls", + texturecraft_engine::geom::primitives::udim_plane(), + "builtin:udim_plane", + None, + 256, + ) + .unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let before = harness.state().session.doc.project.clone(); + + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + let resolution_position = harness.get_by_label("UV tile 1002 resolution").rect().center(); + harness.hover_at(resolution_position); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + harness.get_by_label("UV tile 1002 resolution").click(); + harness.run_steps(3); + click(&mut harness, "128 × 128"); + harness.get_by_value("128 × 128*"); + let texture_set = &harness.state().session.doc.project.texture_sets[0]; + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.tile_resolution(1001), 256); + assert_eq!(texture_set.tile_resolution(1002), 128); + assert_eq!(texture_set.bake, before.texture_sets[0].bake); + + harness.get_by_value("128 × 128*").click(); + harness.run_steps(3); + click(&mut harness, "Remove resolution override"); + assert_eq!(harness.state().session.doc.project, before); + assert!(harness.query_by_value("128 × 128*").is_none()); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + harness.get_by_value("128 × 128*"); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_value("2048").next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "64"); + let texture_set = &harness.state().session.doc.project.texture_sets[0]; + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.tile_resolution(1002), 128); + assert_eq!(texture_set.bake.common.resolution, BakeResolution::R64); +} + +#[test] +fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { + let mut session = + texturecraft_engine::Session::new_project("UV tile list", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256) + .unwrap(); + texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); + let before = session.doc.project.clone(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + harness.get_by_label("1001"); + harness.get_by_value("256 × 256"); + harness.get_by_label("1002"); + harness.get_by_value("128 × 128*"); + click_checkbox(&mut harness, "1002"); + assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); + assert!(!harness.get_by_label("Bake Selected Textures (1)").accesskit_node().is_disabled()); + click_checkbox(&mut harness, "1001"); + assert!(harness.get_by_label("Bake Selected Textures (0)").accesskit_node().is_disabled()); + harness.state_mut().session.undo().unwrap(); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + click(&mut harness, "UV tiles (UDIM) (2)"); + assert!(harness.query_by_label("1001").is_none()); + assert!(harness.query_by_label("1002").is_none()); + assert_eq!(harness.state().session.doc.project, before); +} + +#[test] +fn restoring_map_defaults_updates_other_sets_even_when_active_values_are_default() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.rays = 16; + second.maps.ao.parameters.ground_plane.offset = 3.0; + let before = session.doc.project.clone(); + + click(&mut harness, "Restore Defaults"); + + let mut expected = before.clone(); + expected.texture_sets[1].bake.maps.ao.parameters = BakeSettings::default().maps.ao.parameters; + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + session.doc.project.texture_sets[0].bake.common = Default::default(); + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.common.apply_diffusion = false; + second.maps.select([BakedMap::Height]); + second.high_poly.low_suffix = "_custom_low".into(); + let before = session.doc.project.clone(); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_role_and_label(Role::Button, "Restore Defaults").next().unwrap().click(); + harness.run_steps(3); + + let mut expected = before.clone(); + expected.texture_sets[1].bake.common = Default::default(); + expected.texture_sets[1].bake.common.is_enabled = false; + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +fn output_axes_unlock_independently_and_relock_to_width() { + let mut harness = harness(None); + harness.get_by_label("Texture Sets"); + harness.get_by_label("Mesh Map Settings"); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + let width = harness.state().session.doc.project.texture_sets[0].bake.common.resolution.pixels().to_string(); + assert!(harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); + + click(&mut harness, "Lock Output Size"); + assert!(!harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); + harness.get_all_by_value(&width).next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "128"); + let settings = &harness.state().session.doc.project.texture_sets[0].bake.common; + assert_eq!(settings.resolution, BakeResolution::R128); + assert_eq!(settings.resolution_height.map(BakeResolution::pixels), Some(width.parse().unwrap())); + + click(&mut harness, "Lock Output Size"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.common.output_size(), (128, 128)); + assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); + harness.run_steps(3); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); + + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(3); + assert!(!harness.state().ui.dock.is_open(Panel::CommonSettings)); + assert!(harness.state().ui.dock.is_open(Panel::Assets)); +} + +#[test] +fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_height() { + let mut harness = harness(None); + assert!(harness.query_by_label("Normalization").is_none()); + select_map(&mut harness, "Height"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "selecting is not enabling"); + assert!(harness.query_by_label("Scaling Divisor").is_none()); + click(&mut harness, "Normalization"); + click(&mut harness, "Manual"); + harness.get_by_label("Scaling Divisor"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); + + click_checkbox(&mut harness, "Height"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + click(&mut harness, "Restore Defaults"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "Restore Defaults keeps the map enabled"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); + assert!(harness.query_by_label("Scaling Divisor").is_none()); + click_checkbox(&mut harness, "Height"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); +} + +#[test] +fn clicking_a_row_shows_that_maps_settings_without_changing_what_bakes() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + let before = enabled_maps(&harness); + + select_map(&mut harness, "Ambient Occlusion"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); + assert!(harness.query_by_label("Method").is_none()); + select_map(&mut harness, "Opacity"); + harness.get_by_label("No Parameters"); + assert!(harness.query_by_label("Attenuation").is_none()); + assert_eq!(enabled_maps(&harness), before); + + click(&mut harness, &format!("{} Common Settings", egui_phosphor::regular::GEAR)); + assert!(harness.state().ui.dock.is_visible(Panel::CommonSettings)); + assert_eq!(enabled_maps(&harness), before); +} + +#[test] +fn check_all_enables_every_map_then_disables_them_all() { + let mut harness = harness(Some(BakedMap::Curvature)); + click_checkbox(&mut harness, "Check All"); + assert_eq!(enabled_maps(&harness), BakedMap::ALL); + click_checkbox(&mut harness, "Check All"); + assert!(enabled_maps(&harness).is_empty()); +} + +#[test] +fn the_breadcrumb_switches_the_shown_map() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.get_by_label("Sampling Radius"); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); + + let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); + let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; + map_dropdown.click(); + harness.run_steps(3); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); + + // The menu draws its items after the list rows + harness.get_all_by_role_and_label(Role::Button, "Position").last().unwrap().click(); + harness.run_steps(3); + harness.get_by_label("Normalization Scale"); + assert!(harness.query_by_label("Sampling Radius").is_none()); + assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); +} + +#[test] +fn curvature_controls_follow_the_method_and_notes_visibility_rules() { + let mut harness = harness(Some(BakedMap::Curvature)); + let curvature = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters; + + assert_eq!(curvature(&harness).method, CurvatureMethod::Mesh); + assert!(harness.query_by_label("Details").is_none()); + harness.get_by_label("Sampling Radius"); + assert!(harness.query_by_label("Value Bounds Min").is_none()); + assert!(harness.query_by_label("Value Bounds Max").is_none()); + + click(&mut harness, "Auto Tonemapping"); + harness.get_by_label("Value Bounds Min"); + harness.get_by_label("Value Bounds Max"); + assert!(!curvature(&harness).mesh.auto_tonemapping); + + click(&mut harness, "Method"); + click(&mut harness, "Generate from Normal Map"); + assert_eq!(curvature(&harness).method, CurvatureMethod::NormalMap); + assert!(harness.query_by_label("Sampling Radius").is_none()); + harness.get_by_label("Details"); + + harness.get_by_label("Seams Intensity"); + click(&mut harness, "Enable Seams"); + assert!(harness.query_by_label("Seams Intensity").is_none()); +} + +#[test] +fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + assert!(harness.query_by_label("Cage Type").is_none()); + assert!(harness.query_by_label("Skew Correction").is_none()); + + harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.run_steps(3); + harness.get_by_label("Max Frontal Distance"); + harness.get_by_label("Skew Correction"); + + click(&mut harness, "Cage Type"); + click(&mut harness, "Custom File"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); + harness.get_by_label("Cage Scene"); + assert!(harness.query_by_label("Max Frontal Distance").is_none()); + assert!(harness.query_by_label("Skew Correction").is_none()); + + for button_size in [20.0, 28.0] { + harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); + harness.run_steps(3); + for label in ["Remove", "Load Cage"] { + assert_eq!(harness.get_by_label(label).rect().size(), egui::Vec2::splat(button_size)); + } + } +} diff --git a/crates/ui-egui/tests/brush_drag.rs b/crates/ui-egui/tests/it/brush_drag.rs similarity index 100% rename from crates/ui-egui/tests/brush_drag.rs rename to crates/ui-egui/tests/it/brush_drag.rs diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs similarity index 72% rename from crates/ui-egui/tests/close_unsaved.rs rename to crates/ui-egui/tests/it/close_unsaved.rs index 9f518f18..47996530 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -56,10 +56,25 @@ fn cancel_keeps_the_app_open() { fn closing_without_changes_does_not_ask() { let mut h = harness(false); request_close(&mut h); - assert!(!sent(&h, &ViewportCommand::CancelClose)); + // macOS keeps the window for `-[NSApplication terminate:]` to close; elsewhere it closes now. + assert_eq!(sent(&h, &ViewportCommand::CancelClose), cfg!(target_os = "macos")); assert!(h.state().ui.windows.unsaved.is_none()); } +/// `ui` does not run while the window is minimized, so the close decision is made in `logic`. +#[test] +fn closing_a_minimized_window_with_changes_brings_it_back_to_ask() { + let mut h = harness(true); + let root = h.input_mut().viewports.entry(ViewportId::ROOT).or_default(); + root.minimized = Some(true); + root.events.push(ViewportEvent::Close); + h.step(); + assert!(sent(&h, &ViewportCommand::CancelClose), "the close waits for an answer"); + assert!(sent(&h, &ViewportCommand::Minimized(false)), "the window comes back"); + assert!(sent(&h, &ViewportCommand::Focus)); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); +} + /// A project picked or dropped in the browser arrives as bytes; it waits on the same dialog. #[test] fn a_dropped_project_waits_on_the_dialog() { @@ -90,3 +105,17 @@ fn closing_the_project_with_changes_asks_first() { assert_ne!(name(&h), "Edited", "Don't save closes the project"); assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified); } + +/// The dialog fits one sentence and one button row instead of growing to the screen height +#[test] +fn the_dialog_fits_its_contents() { + // The title bar, one line, one button row and margins take 119 px at 1x and the bug made it 420; the 31 px left over absorbs font and theme tweaks + const MAX_HEIGHT: f32 = 150.0; + + let mut h = harness(true); + request_close(&mut h); + h.run_steps(2); + + let dialog = h.ctx.memory(|m| m.area_rect(egui::Id::unique("unsaved"))).expect("the dialog is shown"); + assert!(dialog.height() < MAX_HEIGHT, "the dialog is {} px tall", dialog.height()); +} diff --git a/crates/ui-egui/tests/color_picker.rs b/crates/ui-egui/tests/it/color_picker.rs similarity index 100% rename from crates/ui-egui/tests/color_picker.rs rename to crates/ui-egui/tests/it/color_picker.rs diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs new file mode 100644 index 00000000..81c34868 --- /dev/null +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -0,0 +1,269 @@ +//! The color selection editor in Properties: one row per ID color, remove, and the pick mode + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, EffectKind, LayerId}; +use texturecraft_engine::{StackTarget, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +const FIRST: [f32; 3] = [200.0 / 255.0, 0.0, 0.0]; +const SECOND: [f32; 3] = [10.0 / 255.0, 1.0, 0.0]; +const THIRD: [f32; 3] = [30.0 / 255.0, 0.0, 1.0]; +const ID_PART: [u8; 3] = [90, 160, 220]; + +/// An ID map of one color, as a PNG +fn id_map_png() -> Vec { + let [red, green, blue] = ID_PART; + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([red, green, blue, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A selected color selection of three colors on a fill layer's mask +fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + if with_id_map { + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + } else { + // The sample bakes an ID map with the others + execute(&mut session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + } + + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.colorSelection", &Value::Null).unwrap(); + let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [FIRST, SECOND, THIRD]})).unwrap(); + session.target = StackTarget::Effect(effect); + (session, effect) +} + +fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let (session, effect) = color_selection_session(with_id_map); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +fn colors(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Vec<[f32; 3]> { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection { colors, .. } => colors.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.event(Event::PointerMoved(position)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Whether the last frame drew the eyedropper glyph with its tip at `pointer` +fn eyedropper_at(harness: &Harness<'_, TextureCraftApp>, pointer: Pos2) -> bool { + harness.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) => text.galley.text() == egui_phosphor::regular::EYEDROPPER && (text.pos.x - pointer.x).abs() < 1.0, + _ => false, + }) +} + +fn pick_color_label() -> String { + format!("{} Pick color", egui_phosphor::regular::EYEDROPPER) +} + +#[test] +fn each_color_gets_a_row_and_remove_sends_the_list_without_it() { + let (mut harness, effect) = app_with_color_selection(false); + for readout in ["R: 200", "R: 10", "R: 30"] { + assert!(harness.query_by_label(readout).is_some(), "{readout} row"); + } + + let second_row = harness.get_by_label("R: 10").rect().center().y; + let remove = harness + .query_all_by_label("Remove") + .find(|button| (button.rect().center().y - second_row).abs() < 8.0) + .expect("the second row's remove button") + .rect() + .center(); + click_at(&mut harness, remove); + + assert_eq!(colors(&harness, effect), vec![FIRST, THIRD]); +} + +#[test] +fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect && pick.index.is_none())); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); + + let center = harness.state().viewport_rect.center(); + harness.event(Event::PointerMoved(center)); + harness.run_steps(2); + assert!(eyedropper_at(&harness, center), "the pointer is an eyedropper"); + + click_at(&mut harness, center); + + let picked = colors(&harness, effect); + assert_eq!(picked.len(), 4, "the click adds a row"); + assert_eq!(picked[3], ID_PART.map(|channel| channel as f32 / 255.0)); + assert!(harness.state().picking_id_color.is_none(), "one click ends pick mode"); + assert_eq!(harness.state().session.view, ViewMode::Material, "the earlier view comes back"); +} + +#[test] +fn without_an_id_map_picking_is_off_and_a_warning_says_why() { + let (mut harness, _) = app_with_color_selection(false); + let warning = format!("{} Bake an ID map (F8) to pick colors from the mesh.", egui_phosphor::regular::WARNING); + assert!(harness.query_by_label(&warning).is_some()); + + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + assert!(harness.state().picking_id_color.is_none()); +} + +fn row_button(harness: &Harness<'_, TextureCraftApp>, readout: &str, label: &str) -> Pos2 { + let row_y = harness.get_by_label(readout).rect().center().y; + harness.query_all_by_label(label).find(|button| (button.rect().center().y - row_y).abs() < 8.0).unwrap().rect().center() +} + +#[test] +fn removing_a_row_cancels_a_pending_replacement() { + let (mut harness, effect) = app_with_color_selection(true); + let repick = row_button(&harness, "R: 10", "Pick color"); + click_at(&mut harness, repick); + assert_eq!(harness.state().picking_id_color.unwrap().index, Some(1)); + + let remove = row_button(&harness, "R: 200", "Remove"); + click_at(&mut harness, remove); + + assert_eq!(colors(&harness, effect), vec![SECOND, THIRD]); + assert!(harness.state().picking_id_color.is_none(), "removing a row must not leave a replacement targeting a different color"); + assert_eq!(harness.state().session.view, ViewMode::Material); +} + +#[test] +fn escape_cancels_the_pick_without_editing_colors() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.state().picking_id_color.is_none()); + assert_eq!(harness.state().session.view, ViewMode::Material); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn picking_from_the_popup_closes_it_before_the_viewport_click() { + use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; + + let (mut harness, effect) = app_with_color_selection(true); + let bounds = harness.state().viewport_rect; + harness.state_mut().properties_popup = Some(PropertiesPopup::Open { at: bounds.center() - egui::vec2(100.0, 100.0), bounds }); + harness.run_steps(4); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let pick = harness.query_all_by_label(&pick_color_label()).find(|button| popup.contains_rect(button.rect())).unwrap().rect().center(); + click_at(&mut harness, pick); + + assert!(harness.state().picking_id_color.is_some()); + let center = harness.state().viewport_rect.center(); + assert!(popup.contains(center), "pick a point the popup would otherwise cover"); + click_at(&mut harness, center); + assert_eq!(colors(&harness, effect).len(), 4, "the next viewport click must pick, even under the former popup"); + assert_eq!(harness.state().properties_popup, None); +} + +#[test] +fn a_2d_pick_replaces_the_chosen_row_and_undo_restores_it() { + use texturecraft_ui_egui::state::ViewLayout; + + let (mut harness, effect) = app_with_color_selection(true); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(3); + let center = harness.state().viewport_rect.center(); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(3); + let repick = row_button(&harness, "R: 10", "Pick color"); + click_at(&mut harness, repick); + click_at(&mut harness, center); + + assert_eq!(colors(&harness, effect), vec![FIRST, ID_PART.map(|channel| channel as f32 / 255.0), THIRD]); + assert_eq!(harness.state().session.view, ViewMode::Material); + assert!(!harness.state().session.stroke_active()); + harness.state_mut().session.undo().unwrap(); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); +} + +#[test] +fn deselection_cancels_picking_and_preserves_a_view_chosen_meanwhile() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + execute(&mut harness.state_mut().session, "viewport.view", &json!({"mode": "uvChecker"})).unwrap(); + harness.state_mut().session.target = StackTarget::Content; + harness.run_steps(3); + + assert!(harness.state().picking_id_color.is_none()); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); +} + +#[test] +#[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered views"] +fn color_selection_snapshots_and_quick_mask_pick() { + let (session, _) = color_selection_session(true); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { + let mut app = TextureCraftApp::new(context, session); + app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D; + app + }); + let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); + eprintln!("Offscreen adapter: {adapter:?}"); + + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + harness.run_steps(8); + let image = harness.render().unwrap(); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + let path = std::path::Path::new(&directory).join(format!("{name}.png")); + image.save(&path).unwrap(); + eprintln!("wrote {}", path.display()); + } + image + }; + + save(&mut harness, "color-selection-editor"); + harness.get_by_label(&pick_color_label()).click(); + let center = harness.state().viewport_rect.center(); + harness.hover_at(center + egui::vec2(80.0, 0.0)); + let expected = save(&mut harness, "color-selection-picking"); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + let with_quick_mask = save(&mut harness, "color-selection-picking-quick-mask"); + assert_eq!( + with_quick_mask.get_pixel(center.x as u32, center.y as u32), + expected.get_pixel(center.x as u32, center.y as u32), + "picking must display the ID map while quick-mask editing is enabled" + ); + + click_at(&mut harness, center); + assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing"); + save(&mut harness, "color-selection-quick-mask-restored"); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; + harness.get_by_label(&pick_color_label()).click(); + save(&mut harness, "color-selection-picking-2d"); + click_at(&mut harness, center); + assert!(harness.state().picking_id_color.is_none()); + execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + save(&mut harness, "color-selection-no-id-map"); +} diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs new file mode 100644 index 00000000..a5b321bc --- /dev/null +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -0,0 +1,86 @@ +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{CurvatureMode, EffectKind, LayerId}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + let builder = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) { + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(current.label())).unwrap().click(); + harness.run_steps(2); + harness.get_by_label(next.label()).click(); + harness.run_steps(4); +} + +#[test] +fn mode_and_detail_controls_apply_and_undo() { + let (mut harness, effect) = harness(false); + select_mode(&mut harness, CurvatureMode::Edges, CurvatureMode::Cavities); + let detail = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.detail.clone().unwrap(), + _ => panic!("expected a curvature generator"), + }; + assert_eq!(detail(&harness).mode, CurvatureMode::Cavities); + let previous = detail(&harness); + let history = harness.state().session.history_labels().len(); + harness.get_by_label("8 px").scroll_to_me(); + harness.run_steps(3); + let label = harness.get_by_label("8 px").rect(); + let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0); + let end = start + egui::vec2(100.0, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); + assert_ne!(detail(&harness).weights[4], previous.weights[4]); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(detail(&harness), previous); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn curvature_mode_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, _) = harness(true); + eprintln!("Rendering adapter: {}", harness.state().gpu.as_ref().unwrap().adapter); + let mut current = CurvatureMode::Edges; + for (mode, filename) in [ + (CurvatureMode::Edges, "curvature-edges.png"), + (CurvatureMode::Cavities, "curvature-cavities.png"), + (CurvatureMode::Both, "curvature-both.png"), + (CurvatureMode::Raw, "curvature-raw.png"), + ] { + if mode != current { + select_mode(&mut harness, current, mode); + } + current = mode; + harness.state_mut().session.update(); + harness.run_steps(12); + harness.render().unwrap().save(directory.join(filename)).unwrap(); + } +} diff --git a/crates/ui-egui/tests/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs similarity index 100% rename from crates/ui-egui/tests/effect_rows.rs rename to crates/ui-egui/tests/it/effect_rows.rs diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs similarity index 100% rename from crates/ui-egui/tests/effect_sliders.rs rename to crates/ui-egui/tests/it/effect_sliders.rs diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs new file mode 100644 index 00000000..5c13c6d8 --- /dev/null +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -0,0 +1,265 @@ +//! Native file dialogs answer on a later frame; the tests answer them without a window. + +use std::path::{Path, PathBuf}; + +use egui::{ViewportCommand, ViewportEvent, ViewportId}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::state::Unsaved; + +fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = modified; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn answer(h: &mut Harness<'_, TextureCraftApp>, answer_with: impl FnMut(&Request) -> Answer + 'static) { + h.state_mut().file_dialogs.set_override(Some(Box::new(answer_with))); +} + +fn invoke(h: &mut Harness<'_, TextureCraftApp>, id: &str) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, id); +} + +/// A path in a new temporary folder. +fn temp_file(test: &str, name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-file-dialogs-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join(name) +} + +fn project_named(name: &str, file: &PathBuf) { + let session = Session::new_project(name, texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + std::fs::write(file, session.to_project_bytes().unwrap()).unwrap(); +} + +#[test] +fn open_returns_at_once_and_the_answer_opens_the_project_later() { + let file = temp_file("open", "picked.tcraft"); + project_named("Picked", &file); + let mut h = harness(false); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + invoke(&mut h, "file.open"); + assert_ne!(h.state().session.doc.project.name, "Picked", "the menu click does not wait for the dialog"); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.name, "Picked"); + assert_eq!(h.state().ui.recent.first().map(String::as_str), Some(file.display().to_string().as_str())); +} + +#[test] +fn a_canceled_dialog_changes_nothing() { + let mut h = harness(false); + let name = h.state().session.doc.project.name.clone(); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "file.open"); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.name, name); + assert!(h.state().toasts.is_empty()); + assert_eq!(h.state().file_dialogs.pending(), 0); +} + +#[test] +fn a_dialog_that_cannot_show_is_reported() { + let mut h = harness(false); + answer(&mut h, |_| Answer::Unavailable("no portal".into())); + invoke(&mut h, "file.open"); + h.run_steps(3); + assert!(h.state().toasts.iter().any(|t| t.error && t.text.contains("no portal"))); +} + +#[test] +fn choosing_the_same_menu_item_twice_asks_once() { + let mut h = harness(false); + let asked = std::rc::Rc::new(std::cell::Cell::new(0)); + let count = asked.clone(); + answer(&mut h, move |_| { + count.set(count.get() + 1); + Answer::Cancelled + }); + invoke(&mut h, "file.open"); + invoke(&mut h, "file.open"); + assert_eq!(h.state().file_dialogs.pending(), 1); + h.run_steps(3); + assert_eq!(asked.get(), 1); +} + +#[test] +fn save_as_and_save_a_copy_are_separate_requests() { + let mut h = harness(false); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "file.saveAs"); + invoke(&mut h, "file.saveCopy"); + assert_eq!(h.state().file_dialogs.pending(), 2, "the second one does not take the first one's place"); +} + +#[test] +fn save_as_offers_the_project_format_and_a_name() { + let mut h = harness(false); + let seen = std::rc::Rc::new(std::cell::RefCell::new(None)); + let store = seen.clone(); + answer(&mut h, move |request| { + *store.borrow_mut() = Some(request.clone()); + Answer::Cancelled + }); + invoke(&mut h, "file.saveAs"); + h.run_steps(3); + let Some(Request::File(dialog)) = seen.borrow().clone() else { panic!("no file dialog was asked for") }; + assert_eq!(dialog.filters.first().map(|f| f.extensions.clone()), Some(vec![texturecraft_engine::core::PROJECT_EXT.to_string()])); + assert!(dialog.file_name.is_some_and(|name| name.ends_with(texturecraft_engine::core::PROJECT_EXT))); +} + +#[test] +fn a_save_answer_for_a_replaced_project_saves_nothing() { + let file = temp_file("replaced", "kept.tcraft"); + let mut h = harness(true); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + invoke(&mut h, "file.saveAs"); + h.state_mut().session.project_id += 1; + h.run_steps(3); + assert!(!file.exists(), "the answer belonged to the project that was open when it was asked"); + assert!(h.state().toasts.iter().any(|t| t.error)); + assert!(h.state().session.modified); +} + +const PROJECT_CHANGED: &str = "The project changed while the dialog was open"; + +/// A project-bound dialog asked by `ask`, answered after another project was opened. +fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureCraftApp>), file: &Path) -> Harness<'static, TextureCraftApp> { + let mut h = harness(false); + h.state_mut().session.doc.project.mesh_path.clear(); + let path = file.to_path_buf(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + ask(&mut h); + h.state_mut().session.project_id += 1; + h.run_steps(3); + h +} + +#[test] +fn every_project_dialog_does_nothing_for_a_replaced_project() { + let file = temp_file("replaced-actions", "chosen.obj"); + for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { + let h = answered_after_the_project_changed(|h| invoke(h, id), &file); + assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}"); + assert!(!file.exists(), "{id} wrote nothing"); + } + let bake = answered_after_the_project_changed( + |h| { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::web_files::import_bake_mesh(h.state_mut(), &ctx, false); + }, + &file, + ); + assert!(bake.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "bake meshes"); + let hdr = answered_after_the_project_changed( + |h| { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::web_files::import_environment(h.state_mut(), &ctx); + }, + &file, + ); + assert!(hdr.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "Import HDR"); +} + +#[test] +fn reimport_reads_the_remembered_file_without_asking() { + let file = temp_file("reimport", "mesh.obj"); + std::fs::write(&file, "").unwrap(); + let mut h = harness(false); + h.state_mut().session.doc.project.mesh_path = file.display().to_string(); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "file.reimportMesh"); + assert_eq!(h.state().file_dialogs.pending(), 0, "the file is still there, so no dialog was asked for"); +} + +#[test] +fn a_mesh_change_keeps_the_answer_for_the_same_project() { + let file = temp_file("mesh-change", "kept.tcraft"); + let mut h = harness(true); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + invoke(&mut h, "file.saveAs"); + h.state_mut().session.mesh_id += 1; + h.run_steps(3); + assert!(file.exists(), "a reimport or a UV layout change is still the same project"); +} + +fn request_close(h: &mut Harness<'_, TextureCraftApp>) { + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close); + h.step(); + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear(); + h.run_steps(2); +} + +/// A root viewport command sent during `frames` steps. +fn sends(h: &mut Harness<'_, TextureCraftApp>, frames: usize, cmd: &ViewportCommand) -> bool { + (0..frames).any(|_| { + h.step(); + h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(cmd)) + }) +} + +fn untitled_with_prompt(h: &mut Harness<'_, TextureCraftApp>) { + h.state_mut().session.path = None; + request_close(h); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the dialog is open"); +} + +#[test] +fn closing_during_a_stroke_finishes_it_and_asks() { + let mut h = harness(false); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + assert!(!h.state().session.modified, "the stroke is not finished yet"); + request_close(&mut h); + assert!(!h.state().session.stroke_active()); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); +} + +#[test] +fn save_in_the_prompt_goes_on_once_the_dialog_has_saved() { + let file = temp_file("prompt-save", "saved.tcraft"); + let mut h = harness(true); + untitled_with_prompt(&mut h); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + h.get_by_label("Save").click(); + assert!(sends(&mut h, 5, &ViewportCommand::Close), "the close goes on after the save"); + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none()); +} + +#[test] +fn canceling_the_save_dialog_keeps_the_prompt_and_its_buttons() { + let mut h = harness(true); + untitled_with_prompt(&mut h); + answer(&mut h, |_| Answer::Cancelled); + h.get_by_label("Save").click(); + assert!(!sends(&mut h, 5, &ViewportCommand::Close)); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the question is still open"); + assert!(h.state().session.modified); + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(h.state().ui.windows.unsaved.is_none(), "Cancel answers again after the Save dialog closed"); +} + +#[test] +fn a_save_elsewhere_does_not_answer_the_prompt() { + let file = temp_file("prompt-other", "other.tcraft"); + let mut h = harness(true); + untitled_with_prompt(&mut h); + let path = file.display().to_string(); + h.state_mut().run("file.saveAs", serde_json::json!({ "path": path })); + assert!(!h.state().session.modified); + assert!(!sends(&mut h, 3, &ViewportCommand::Close), "only the prompt's own Save goes on"); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); +} diff --git a/crates/ui-egui/tests/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs similarity index 100% rename from crates/ui-egui/tests/fill_channel_image.rs rename to crates/ui-egui/tests/it/fill_channel_image.rs diff --git a/crates/ui-egui/tests/it/fill_projection_section.rs b/crates/ui-egui/tests/it/fill_projection_section.rs new file mode 100644 index 00000000..983f1bc5 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_projection_section.rs @@ -0,0 +1,102 @@ +//! A fill's projection settings fold into a "UV transformations" section under the Projection combo + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; + +/// Tall enough that Properties shows the whole fill without scrolling +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1400.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click or selection change to reach the panel +const SETTLE_FRAMES: usize = 3; + +/// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id +fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); + + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, layer) +} + +fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_label("UV transformations").click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_uv_transformations_start_open_and_fold_away() { + let (mut harness, _) = app_with_fill("uv"); + assert!(harness.query_by_label("Rotation").is_some()); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_none()); + assert!(harness.query_by_label("Scale / tiling").is_none()); + assert!(harness.query_by_label("Projection").is_some()); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_some()); +} + +#[test] +fn hardness_and_axis_stay_outside_the_section() { + let (mut harness, _) = app_with_fill("triplanar"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Offset X").is_none()); + assert!(harness.query_by_label("Hardness").is_some()); + + let (mut harness, _) = app_with_fill("planar"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Offset X").is_none()); + assert!(harness.query_by_label("Axis").is_some()); + + let (mut harness, _) = app_with_fill("cylindrical"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Scale / tiling").is_none()); + assert!(harness.query_by_label("Axis").is_some()); +} + +#[test] +fn each_fill_keeps_its_own_open_state() { + let (mut harness, first) = app_with_fill("uv"); + toggle_section(&mut harness); + + let added = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap(); + let second = added["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": second})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Rotation").is_some(), "a new fill starts open"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": first})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); +} + +#[test] +fn a_fill_effect_keeps_a_state_apart_from_its_layer() { + let (mut harness, layer) = app_with_fill("uv"); + toggle_section(&mut harness); + + let session = &mut harness.state_mut().session; + let added = texturecraft_engine::execute(session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + texturecraft_engine::execute(session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Rotation").is_some(), "the effect's section starts open"); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_none()); +} diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs new file mode 100644 index 00000000..36abe572 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -0,0 +1,199 @@ +//! The filter slot in Properties swaps a filter through its picker, and Add filter adds one + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot +fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The kind of effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind { + harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone() +} + +/// Clicks the Invert slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Invert").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); +} + +#[test] +fn picking_from_the_slot_swaps_the_filter() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // The picker's search field has the focus as it opens + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); + + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn escape_closes_the_picker_without_changes() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // Without the search field's focus, the painting shortcuts see Escape first + harness.ctx.memory_mut(|memory| memory.stop_text_input()); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); +} + +/// Opens the wand's Add effect menu and clicks Add filter +fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + harness.run_steps(3); + + harness.get_by_label("Add filter").click(); + harness.run_steps(3); +} + +#[test] +fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); + assert!(egui::Popup::is_any_open(&harness.ctx), "the new filter's picker is open to choose the real filter"); + + // The search field has the focus, and a search brings Sharpen into view + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, added)); +} + +#[test] +fn escape_after_add_filter_keeps_the_neutral_filter() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); + assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter stays selected") }; + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + + harness.state_mut().run("edit.undo", Value::Null); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the neutral filter"); +} + +#[test] +fn add_filter_on_a_mask_adds_it_to_the_mask() { + let (mut harness, _) = app_with_invert(); + let layer = harness.state().session.selected_layer().unwrap(); + // A new mask becomes the selected target, so the wand adds to it + harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); + harness.run_steps(3); + + add_filter_from_the_wand(&mut harness); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask"); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); + assert!(harness.query_by_label("Grayscale").is_none(), "the picker leaves out content-only filters"); +} + +#[test] +fn add_filter_reopens_closed_properties_to_show_its_picker() { + let (mut harness, _) = app_with_invert(); + harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); + harness.run_steps(3); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Invert").is_none()); + + add_filter_from_the_wand(&mut harness); + + assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Add filter reveals Properties"); + assert!(harness.query_by_label("Sharpen").is_some(), "the picker opens immediately"); +} + +#[test] +fn keyboard_opens_the_slot_and_outside_click_closes_it() { + let (mut harness, effect) = app_with_invert(); + for key in [egui::Key::Enter, egui::Key::Space] { + harness.get_by_role_and_label(Role::ComboBox, "Invert").focus(); + harness.key_press(key); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx)); + + let position = harness.state().viewport_rect.center(); + harness.hover_at(position); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(3); + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); + } +} + +#[test] +#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] +fn filter_picker_snapshots_and_frame_timings() { + let output = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| { + eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); + TextureCraftApp::new(cc, session) + }); + harness.run_steps(20); + let start = std::time::Instant::now(); + open_picker(&mut harness); + eprintln!("picker open and first 3 UI frames: {:.3} ms", start.elapsed().as_secs_f64() * 1000.0); + harness.run_steps(20); + for (brightness, name) in + [(texturecraft_ui_egui::theme::Brightness::MediumDark, "filter-picker"), (texturecraft_ui_egui::theme::Brightness::Light, "filter-picker-light")] + { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); + } + let start = std::time::Instant::now(); + harness.run_steps(120); + eprintln!("warm open picker: {:.3} ms/UI frame (120 frames, excluding GPU readback)", start.elapsed().as_secs_f64() * 1000.0 / 120.0); + + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + harness.render().unwrap().save(output.join("filter-picker-search.png")).unwrap(); + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + harness.render().unwrap().save(output.join("filter-picker-selected.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs similarity index 100% rename from crates/ui-egui/tests/history_panel.rs rename to crates/ui-egui/tests/it/history_panel.rs diff --git a/crates/ui-egui/tests/layer_clipboard.rs b/crates/ui-egui/tests/it/layer_clipboard.rs similarity index 72% rename from crates/ui-egui/tests/layer_clipboard.rs rename to crates/ui-egui/tests/it/layer_clipboard.rs index 36c20ff9..efcf40c0 100644 --- a/crates/ui-egui/tests/layer_clipboard.rs +++ b/crates/ui-egui/tests/it/layer_clipboard.rs @@ -31,6 +31,34 @@ fn ctrl_x_cuts_the_clicked_layer() { assert!(h.state().session.clipboard.is_some(), "and keeps it on the layer clipboard"); } +/// Windows reports Shift+Delete and Shift+Insert as Cut and Paste with Shift held. +#[test] +fn shift_delete_cuts_and_shift_insert_pastes() { + let (mut h, layer) = harness(); + let before = count(&h); + h.event_modifiers(egui::Event::Cut, egui::Modifiers::SHIFT); + h.run_steps(3); + assert!(!h.state().session.doc.project.layers.contains_key(&layer), "Shift+Delete cuts the layer"); + h.event_modifiers(egui::Event::Paste("Layer".into()), egui::Modifiers::SHIFT); + h.run_steps(3); + assert_eq!(count(&h), before, "Shift+Insert pastes it back"); +} + +#[test] +fn a_binding_on_shift_insert_runs_instead_of_the_paste() { + let (mut h, _) = harness(); + let before = count(&h); + h.event(egui::Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some(), "there is something to paste"); + h.state_mut().ui.keymap.insert("ui.layout.3d".into(), "Shift+Insert".into()); + h.run_steps(2); + h.event_modifiers(egui::Event::Paste("Layer".into()), egui::Modifiers::SHIFT); + h.run_steps(3); + assert_eq!(h.state().ui.layout, texturecraft_ui_egui::state::ViewLayout::Only3D, "the shortcut ran"); + assert_eq!(count(&h), before, "and nothing was pasted"); +} + #[test] fn ctrl_c_then_ctrl_v_pastes_a_copy() { let (mut h, _) = harness(); diff --git a/crates/ui-egui/tests/layer_rename.rs b/crates/ui-egui/tests/it/layer_rename.rs similarity index 100% rename from crates/ui-egui/tests/layer_rename.rs rename to crates/ui-egui/tests/it/layer_rename.rs diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs new file mode 100644 index 00000000..26b1ef10 --- /dev/null +++ b/crates/ui-egui/tests/it/main.rs @@ -0,0 +1,31 @@ +//! One integration-test executable avoids linking the same dependencies for every feature. +//! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. + +mod bake_mode; +mod brush_drag; +mod close_unsaved; +mod color_picker; +mod color_selection_editor; +mod curvature_generator; +mod effect_rows; +mod effect_sliders; +mod file_dialogs; +mod fill_channel_image; +mod fill_projection_section; +mod filter_picker; +mod history_panel; +mod layer_clipboard; +mod layer_rename; +mod new_project_baked_maps; +mod path_list; +mod pen_pressure; +mod polygon_fill; +mod properties_popup; +mod shelf_drop; +mod shelf_hover_preview; +mod shift_lines_2d; +mod shortcut_keys; +mod skew_paint; +mod split_divider; +mod start_window; +mod toolbar; diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs new file mode 100644 index 00000000..39a7c813 --- /dev/null +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -0,0 +1,153 @@ +//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakedMap, NormalFormat}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(3); + h.get_by_label("Advanced settings").click(); + h.run_steps(3); + h.get_by_label("Import baked maps").click(); + h.run_steps(3); + h +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + files + .iter() + .map(|file| { + let path: PathBuf = dir.join(file); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).save(&path).unwrap(); + path.display().to_string() + }) + .collect() +} + +#[test] +fn added_files_are_listed_once_and_clear_empties_the_list() { + let mut h = harness(); + let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); + for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { + h.get_by_label(file); + } + + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.new_project.baked_maps.is_empty()); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +#[test] +fn create_imports_the_listed_maps_in_the_chosen_normal_format() { + let mut h = harness(); + let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let state = h.state(); + assert!(!state.ui.windows.new_project, "the dialog closes"); + let project = &state.session.doc.project; + assert_eq!(project.normal_format, NormalFormat::DirectX); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); + assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + let normal_green = state.session.doc.baked[&0].maps[&BakedMap::Normal][1]; + assert!(normal_green > 0.75, "the normal map is read as DirectX (green flipped): {normal_green}"); + assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); + let toast = &state.toasts.last().unwrap().text; + assert!(toast.contains("Baked maps imported: 2") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); + assert_eq!(state.session.undo_label(), Some("Import baked maps")); +} + +#[test] +fn a_failed_import_keeps_the_file_list_and_created_project() { + let mut h = harness(); + let paths = bake_files("failure", &["Ball_normal.png", "Base_ao.png"]); + std::fs::write(&paths[1], b"not an image").unwrap(); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + h.state_mut().ui.new_project.name = "Import failure".to_string(); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let app = h.state(); + assert!(!app.ui.windows.new_project); + assert_eq!(app.session.doc.project.name, "Import failure"); + assert_eq!(app.ui.new_project.baked_maps, paths); + assert!(app.session.doc.resources.is_empty() && app.session.images.is_empty()); + assert!(app.session.doc.baked.values().all(|baked| baked.maps.is_empty())); + let toast = app.toasts.last().unwrap(); + assert!(toast.error && toast.text.contains("Base_ao.png"), "{}", toast.text); +} + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn new_project_baked_maps_snapshots() { + let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| { + let adapter = cc.wgpu_render_state.as_ref().unwrap().adapter.get_info(); + eprintln!("snapshot adapter: {adapter:?}"); + TextureCraftApp::new(cc, session) + }); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(6); + h.get_by_label("Advanced settings").click(); + h.run_steps(6); + h.get_by_label("Import baked maps").click(); + h.run_steps(6); + let paths = bake_files("snapshots", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("new-project-baked-maps.png")).unwrap(); + h.set_size(egui::vec2(1024.0, 768.0)); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("new-project-baked-maps-small.png")).unwrap(); + h.set_size(egui::vec2(1600.0, 960.0)); + h.run_steps(6); + h.get_by_label("Create").click(); + h.run_steps(3); + assert!(h.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Normal)); + h.render().unwrap().save(output_dir.join("new-project-imported.png")).unwrap(); +} + +#[test] +fn normal_format_preview_uses_the_same_template_lookup_as_creation() { + let mut h = harness(); + h.state_mut().session.templates.dir = None; + h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); + h.state_mut().run("project.template.save", serde_json::json!({"name": "Custom DirectX"})).unwrap(); + h.state_mut().ui.new_project.template = "custom directx".to_string(); + h.run_steps(3); + + h.get_by_value("DirectX"); + h.get_by_label("Create").click(); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.normal_format, NormalFormat::DirectX); +} diff --git a/crates/ui-egui/tests/path_list.rs b/crates/ui-egui/tests/it/path_list.rs similarity index 100% rename from crates/ui-egui/tests/path_list.rs rename to crates/ui-egui/tests/it/path_list.rs diff --git a/crates/ui-egui/tests/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs similarity index 100% rename from crates/ui-egui/tests/pen_pressure.rs rename to crates/ui-egui/tests/it/pen_pressure.rs diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs new file mode 100644 index 00000000..d362c1a8 --- /dev/null +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -0,0 +1,143 @@ +//! Polygon fill in the views: a click fills one target and a box drag fills what the box selects, each as one undo step + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample project in the default split layout at 1600 x 960 with the polygon fill tool +fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(4); + harness +} + +/// Drag the primary button from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + + // Only the release frame runs, so the release itself must finish the drag + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(1); +} + +/// Press and release the primary button at `at` +fn click(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The undo steps recorded so far +fn history(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.history_labels() +} + +#[test] +fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() { + let mut clicked = polygon_fill_app(); + let center = clicked.state().viewport_rect.center(); + let before = history(&clicked).len(); + click(&mut clicked, center); + assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle"); + + let mut boxed = polygon_fill_app(); + drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0)); + assert_eq!(history(&boxed).len(), before + 1); + assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill")); + assert!( + painted_tiles(&boxed) > painted_tiles(&clicked), + "the box fills every triangle in it: {} tiles vs {}", + painted_tiles(&boxed), + painted_tiles(&clicked) + ); +} + +#[test] +fn a_box_drag_in_the_2d_view_is_one_fill() { + let mut harness = polygon_fill_app(); + let view_3d = harness.state().viewport_rect; + let center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + let before = history(&harness).len(); + + drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0)); + assert_eq!(history(&harness).len(), before + 1); + assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); +} + +#[test] +fn a_new_press_after_release_does_not_resume_the_previous_box() { + let mut harness = polygon_fill_app(); + let center = harness.state().viewport_rect.center(); + drag(&mut harness, center - vec2(40.0, 40.0), center + vec2(40.0, 40.0)); + let history_after_drag = history(&harness); + let tiles_after_drag = painted_tiles(&harness); + + // Start the next gesture on the frame immediately after release + let point = center - vec2(80.0, 80.0); + harness + .input_mut() + .events + .extend([Event::PointerMoved(point), Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + harness.run_steps(1); + assert_eq!(painted_tiles(&harness), tiles_after_drag, "a press alone must not refill the old rectangle"); + + harness.event(Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(1); + assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step"); +} + +#[test] +#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] +fn polygon_fill_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); + eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(6); + harness.render().unwrap().save(directory.join("polygon-fill-properties.png")).unwrap(); + + let center = harness.state().viewport_rect.center(); + let origin = center - vec2(85.0, 70.0); + let opposite = center + vec2(85.0, 70.0); + harness.hover_at(origin); + harness.event(Event::PointerButton { pos: origin, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(opposite); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("polygon-fill-drag-3d.png")).unwrap(); + harness.event(Event::PointerButton { pos: opposite, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("polygon-fill-complete-3d.png")).unwrap(); + + texturecraft_engine::execute(&mut harness.state_mut().session, "mask.add.black", &serde_json::Value::Null).unwrap(); + let view = harness.state().viewport_rect; + let center = pos2(view.right() + view.width() * 0.5, view.center().y); + drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0)); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("polygon-fill-mask-2d.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs new file mode 100644 index 00000000..8d3b413f --- /dev/null +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -0,0 +1,167 @@ +//! A plain right click in a view opens the Properties panel's contents at the cursor; right drags keep their gestures + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerKind; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +fn view_center(harness: &Harness<'_, TextureCraftApp>) -> Pos2 { + harness.state().viewport_rect.center() +} + +fn is_open(harness: &Harness<'_, TextureCraftApp>) -> bool { + matches!(harness.state().properties_popup, Some(PropertiesPopup::Open { .. })) +} + +/// Press and release `button` at `at` without moving +fn click(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, at: Pos2) { + harness.hover_at(at); + harness.event(Event::PointerButton { pos: at, button, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Drag with `button` from `from` by `by` in a few moves while `modifiers` are held +fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(3); +} + +#[test] +fn a_right_click_opens_the_popup_at_the_cursor_in_both_views() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(matches!(harness.state().properties_popup, Some(PropertiesPopup::Open { at, .. }) if at == center)); + + harness.key_press(Key::Escape); + harness.run_steps(2); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(2); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness), "the 2D view opens it too"); +} + +#[test] +fn right_drags_keep_their_gestures_and_never_open_it() { + let mut harness = harness(); + let center = view_center(&harness); + let yaw = harness.state().session.camera.yaw; + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), Modifiers::NONE); + assert_ne!(harness.state().session.camera.yaw, yaw, "a right drag orbits"); + assert!(!is_open(&harness), "an orbit doesn't open it"); + + let size = harness.state().session.tool.brush.size; + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), Modifiers::COMMAND); + assert!(harness.state().session.tool.brush.size > size, "Ctrl+right drag sets the brush"); + assert!(!is_open(&harness)); + + for modifiers in [Modifiers::ALT, Modifiers::SHIFT] { + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), modifiers); + assert!(!is_open(&harness), "{modifiers:?}"); + } +} + +#[test] +fn a_click_outside_closes_it_without_painting() { + let mut harness = harness(); + let center = view_center(&harness); + let outside = harness.state().viewport_rect.left_center() + vec2(20.0, 0.0); + let history = harness.state().session.history_labels().len(); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + + click(&mut harness, PointerButton::Primary, outside); + assert_eq!(harness.state().properties_popup, None); + assert_eq!(harness.state().session.history_labels().len(), history, "the closing click doesn't paint"); + + click(&mut harness, PointerButton::Secondary, center); + click(&mut harness, PointerButton::Secondary, outside); + assert_eq!(harness.state().properties_popup, None, "a right click outside closes it and doesn't reopen it"); +} + +#[test] +fn escape_closes_it() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + harness.key_press(Key::Escape); + harness.run_steps(2); + assert_eq!(harness.state().properties_popup, None); +} + +#[test] +fn dragging_its_size_slider_changes_the_brush() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + + // The Size section's header sits above its slider of the same name + let slider_label = harness + .query_all_by_label("Size") + .map(|node| node.rect()) + .filter(|rect| popup.contains_rect(*rect)) + .max_by(|first, second| first.top().total_cmp(&second.top())) + .unwrap(); + let track_y = slider_label.bottom() + 10.0; + let size = harness.state().session.tool.brush.size; + harness.drag_at(egui::pos2(slider_label.left() + 20.0, track_y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(popup.right() - 30.0, track_y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(popup.right() - 30.0, track_y)); + harness.run_steps(3); + assert!(harness.state().session.tool.brush.size > size, "{size} -> {}", harness.state().session.tool.brush.size); + assert!(is_open(&harness), "editing it keeps it open"); +} + +#[test] +fn it_shows_what_the_properties_panel_shows() { + let mut harness = harness(); + let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); + let selected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})); + assert!(selected.is_ok(), "{selected:?}"); + harness.run_steps(3); + + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); + assert!(in_popup("Projection"), "a selected fill shows its fill settings"); + assert!(!in_popup("Minimum size (%)"), "not the brush's"); +} + +#[test] +fn bake_and_render_modes_never_open_it() { + let mut harness = harness(); + let center = view_center(&harness); + for mode in [Mode::Baking, Mode::Rendering] { + harness.state_mut().ui.mode = mode; + harness.run_steps(3); + click(&mut harness, PointerButton::Secondary, center); + assert_eq!(harness.state().properties_popup, None, "{mode:?}"); + } +} diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs new file mode 100644 index 00000000..5b35cc06 --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -0,0 +1,72 @@ +//! A shelf material dropped on the 3D view goes to the texture set under the pointer + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + assert_eq!(harness.state().session.ts(), 0); + harness +} + +/// The first point of the 3D view showing texture set `set`, or the background when `None` +fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP); + + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + egui::vec2(x, y)) + .unwrap() +} + +/// Drop a built-in shelf material at `position`, as a drag from the shelf ends there +fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() }); + harness.hover_at(position); + harness.run_steps(2); + + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// Top-level layer count of each texture set +fn stack_sizes(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets.iter().map(|set| set.stack.len()).collect() +} + +#[test] +fn a_material_dropped_on_another_set_goes_to_that_set_and_selects_it() { + let mut harness = sample_app(); + let before = stack_sizes(&harness); + + let base = point_over(&harness, Some(1)); + drop_material(&mut harness, base); + + assert_eq!(harness.state().session.ts(), 1, "the set under the pointer is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1], "only the set under the pointer gets the material"); +} + +#[test] +fn a_material_dropped_on_the_background_changes_nothing() { + let mut harness = sample_app(); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + + let background = point_over(&harness, None); + drop_material(&mut harness, background); + + assert_eq!(harness.state().session.ts(), 0); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); +} diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs new file mode 100644 index 00000000..c7ad071a --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -0,0 +1,174 @@ +//! Shelf hover previews render after a dwell and appear above the asset name + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_preview::ShelfPreview; + +/// The shelf's Materials tab +const MATERIALS_TAB: usize = 0; +/// Popup image size in logical points, independent of display scale +const BIG_PREVIEW_SIZE: f32 = 256.0; +/// Small time steps distinguish preview scheduling from popup visibility +const STEP_SECONDS: f32 = 0.001; +/// Simulated delays in seconds for the popup and preview request +const POPUP_DELAY: f32 = 0.5; +const REST: f32 = 0.1; +/// Real time the worker gets to render +const WORKER_TIMEOUT: Duration = Duration::from_secs(60); + +/// Open the Materials tab and find two labels unique to shelf tiles +fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_step_dt(step_seconds) + .with_pixels_per_point(pixels_per_point) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.shelf_tab = MATERIALS_TAB; + h.run_steps(4); + + let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + assert_eq!(unique.len(), 2, "two materials with unique names"); + (h, unique) +} + +/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { + let textures = h.ctx.tex_manager(); + let textures = textures.read(); + h.output() + .shapes + .iter() + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) + .max() +} + +/// Check the cache without submitting a preview request +fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { + let ctx = h.ctx.clone(); + h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() +} + +#[test] +fn hovering_a_shelf_tile_shows_its_big_preview() { + let (mut h, materials) = materials_shelf(1.0 / 4.0, 1.0); + let material = materials[0]; + let tile = h.get_by_label(material.label).rect(); + assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); + h.get_by_label(material.label).hover(); + + let big_px = BIG_PREVIEW_SIZE as usize; + let start = Instant::now(); + while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { + h.run_steps(1); + std::thread::sleep(Duration::from_millis(20)); + } + + assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); + let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); + assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); +} + +#[test] +fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { + let (mut h, materials) = materials_shelf(STEP_SECONDS, 1.0); + let (first, second) = (materials[0], materials[1]); + let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); + + // Moving every frame must never satisfy the dwell delay + let sweep_frames = 40; + for frame in 0..=sweep_frames { + h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); + h.run_steps(1); + } + h.hover_at(egui::pos2(900.0, 500.0)); + h.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + h.run_steps(1); + assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); + + // A stationary pointer should start rendering before the popup opens + h.hover_at(from); + h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); + let start = Instant::now(); + let headroom_frames = ((POPUP_DELAY - REST * 1.2) / STEP_SECONDS) as usize - 1; + for _ in 0..headroom_frames { + if big_preview_ready(&mut h, first) || start.elapsed() > WORKER_TIMEOUT { + break; + } + h.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut h, first), "the preview rendered during the popup's delay"); + assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); +} + +#[test] +fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { + let (mut harness, materials) = materials_shelf(STEP_SECONDS, 1.0); + let material = materials[0]; + harness.get_by_label(material.label).hover(); + + // Scroll toward the top boundary to keep the same tile beneath the pointer + for _ in 0..(REST * 2.0 / STEP_SECONDS) as usize { + harness.input_mut().events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 10.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(1); + } + assert!(harness.ctx.input(|input| input.pointer.time_since_last_movement()) >= REST, "the pointer stayed still beyond the dwell delay"); + assert_eq!(harness.query_all_by_label(material.label).count(), 1, "scrolling suppresses the popup"); + + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + harness.run_steps(1); + assert!(!big_preview_ready(&mut harness, material), "scrolling must not submit a hover preview"); + + harness.get_by_label(material.label).hover(); + let started = Instant::now(); + while !big_preview_ready(&mut harness, material) && started.elapsed() < WORKER_TIMEOUT { + harness.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut harness, material), "the preview renders after scrolling and pointer movement stop"); +} + +#[test] +fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { + use texturecraft_engine::smart_masks::SMART_MASKS; + + check_high_dpi_orb_hover(2, SMART_MASKS[0].label); +} + +#[test] +fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() { + check_high_dpi_orb_hover(1, "Steel Painted Worn"); +} + +fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { + use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; + + let (mut harness, _) = materials_shelf(1.0 / 4.0, 3.0); + harness.state_mut().ui.shelf_tab = shelf_tab; + harness.run_steps(4); + assert_eq!(harness.ctx.pixels_per_point(), 3.0, "the test uses the native 300% display scale"); + harness.get_by_role_and_label(egui::Role::Button, label).hover(); + + let expected = Some([MAX_PREVIEW_SIZE_PX; 2]); + let started = Instant::now(); + while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < WORKER_TIMEOUT { + harness.run_steps(1); + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(largest_drawn_texture(&harness, BIG_PREVIEW_SIZE), expected, "the popup uses a bounded big preview at 300% scale"); +} diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs new file mode 100644 index 00000000..a6e6175d --- /dev/null +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -0,0 +1,247 @@ +//! Shift+click in the 2D view paints a straight line from where the last stroke ended, as in the 3D view + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// The first click, on the sample's texture in the 2D view +const FIRST_CLICK: Pos2 = pos2(700.0, 420.0); + +/// The Shift+click, on the texture of both of the sample's texture sets +const SECOND_CLICK: Pos2 = pos2(900.0, 520.0); + +/// Start of a drag cancelled with Escape, well away from the line between the two clicks +const CANCELLED_DRAG_FROM: Pos2 = pos2(760.0, 700.0); + +/// End of the cancelled drag +const CANCELLED_DRAG_TO: Pos2 = pos2(820.0, 700.0); + +/// Alpha a texel needs to count as painted +const PAINTED_ALPHA: f32 = 0.05; + +/// How far beside the line the unpainted check looks, in brush radii +const BESIDE_LINE_IN_RADII: f32 = 3.0; + +/// The sample project with only the 2D view, at 1600 x 960 +fn uv_view_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +/// A primary click at `pos`, with Shift held when `shift` is set +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, shift: bool) { + let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// Press at `from`, drag to `to`, press Escape and release: the stroke is cancelled +fn cancelled_drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(to); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!harness.state().session.stroke_active(), "Escape cancelled the stroke"); +} + +/// The selected layer's base color alpha, row by row, with the texture width +fn alpha(harness: &Harness<'_, TextureCraftApp>) -> (Vec, u32) { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return (vec![0.0; (width * height) as usize], width) }; + let texels = (0..height).flat_map(|y| (0..width).map(move |x| (x, y))); + (texels.map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).collect(), width) +} + +/// Alpha added between two snapshots +fn added(before: &[f32], after: &[f32]) -> Vec { + after.iter().zip(before).map(|(after, before)| (after - before).max(0.0)).collect() +} + +/// The alpha-weighted centre of `paint`, in texels +fn centre(paint: &[f32], width: u32) -> Vec2 { + let (sum, total) = paint.iter().enumerate().fold((Vec2::ZERO, 0.0), |(sum, total), (index, value)| { + let texel = Vec2::new((index as u32 % width) as f32, (index as u32 / width) as f32); + (sum + texel * *value, total + value) + }); + assert!(total > 0.0, "something was painted"); + sum / total +} + +/// Whether `paint` holds visible alpha at `texel` +fn painted_at(paint: &[f32], width: u32, texel: Vec2) -> bool { + let index = texel.y.round() as usize * width as usize + texel.x.round() as usize; + paint[index] > PAINTED_ALPHA +} + +/// The brush radius in texels: a 2D view stamp's radius is twice the brush size in UV units +fn brush_radius_in_texels(harness: &Harness<'_, TextureCraftApp>, width: u32) -> f32 { + harness.state().session.tool.brush.size * 2.0 * width as f32 +} + +/// Click, run `between` (zoom or pan), Shift+click; assert one straight stroke joins both dabs +fn assert_shift_click_draws_a_line(between: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) { + let mut harness = uv_view_app(); + let (blank, width) = alpha(&harness); + click(&mut harness, FIRST_CLICK, false); + let (first_dab, _) = alpha(&harness); + let start = centre(&added(&blank, &first_dab), width); + + between(&mut harness); + harness.run_steps(2); + let steps_before = harness.state().session.history_labels().len(); + click(&mut harness, SECOND_CLICK, true); + assert_eq!(harness.state().session.history_labels().len(), steps_before + 1, "the line is one undo step"); + let (with_line, _) = alpha(&harness); + let line = added(&first_dab, &with_line); + + // A plain click at the same point finds where the line should end + harness.state_mut().session.undo().unwrap(); + click(&mut harness, SECOND_CLICK, false); + let (with_dab, _) = alpha(&harness); + let end = centre(&added(&first_dab, &with_dab), width); + + let middle = (start + end) * 0.5; + let across = (end - start).perp().normalize() * brush_radius_in_texels(&harness, width) * BESIDE_LINE_IN_RADII; + assert!(painted_at(&line, width, middle), "the line passes halfway between {start} and {end}"); + assert!(!painted_at(&line, width, middle + across), "nothing is painted beside the line"); +} + +#[test] +fn shift_click_paints_a_straight_line_from_the_last_stroke() { + assert_shift_click_draws_a_line(|_| {}); +} + +#[test] +fn the_line_joins_the_same_texture_points_after_zoom_and_pan() { + assert_shift_click_draws_a_line(|harness| { + let ui_state = &mut harness.state_mut().ui; + ui_state.uv_zoom *= 1.5; + ui_state.uv_pan = [0.2, -0.1]; + }); +} + +/// Shift+click at the second point; assert it painted the same dot a plain click there paints +fn assert_shift_click_paints_only_a_dot(harness: &mut Harness<'_, TextureCraftApp>) { + let (before, _) = alpha(harness); + click(harness, SECOND_CLICK, true); + let (after_shift_click, _) = alpha(harness); + let shift_click_alpha: f32 = added(&before, &after_shift_click).iter().sum(); + + harness.state_mut().session.undo().unwrap(); + click(harness, SECOND_CLICK, false); + let (after_click, _) = alpha(harness); + let click_alpha: f32 = added(&before, &after_click).iter().sum(); + + assert!(click_alpha > 1.0, "the plain click painted: {click_alpha}"); + assert!((shift_click_alpha - click_alpha).abs() < click_alpha * 0.01, "Shift+click paints only a dot: {shift_click_alpha} vs {click_alpha}"); +} + +#[test] +fn shift_click_without_a_previous_stroke_paints_a_dot() { + assert_shift_click_paints_only_a_dot(&mut uv_view_app()); +} + +#[test] +fn a_line_does_not_start_from_a_point_on_another_texture_set() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.state_mut().run("textureSet.select", json!({"ts": 1})); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { + assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); +} + +#[test] +fn a_new_project_does_not_reuse_the_previous_projects_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 256})).unwrap(); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_project_opened_through_control_does_not_reuse_the_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + let context = harness.ctx.clone(); + let result = texturecraft_ui_egui::control::handle( + harness.state_mut(), + &context, + "command.run", + &json!({"id": "project.new", "params": {"mesh": "sphere", "resolution": 256}}), + ); + assert_eq!(result["ok"], true); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn shift_line_snapshots() { + let output_dir = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS to the output directory")); + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { + let adapter = &context.wgpu_render_state.as_ref().expect("wgpu render state").adapter; + eprintln!("Shift-line snapshot adapter: {:?}", adapter.get_info()); + TextureCraftApp::new(context, session) + }); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + click(&mut harness, FIRST_CLICK, false); + + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + harness.run_steps(4); + let path = output_dir.join(format!("{name}.png")); + harness.render().unwrap().save(&path).unwrap(); + eprintln!("wrote {}", path.display()); + }; + + harness.event(Event::ModifiersChanged(Modifiers::SHIFT)); + harness.hover_at(SECOND_CLICK); + save(&mut harness, "shift-line-preview"); + click(&mut harness, SECOND_CLICK, true); + save(&mut harness, "shift-line-painted"); + + harness.state_mut().ui.uv_zoom = 1.5; + harness.state_mut().ui.uv_pan = [0.2, -0.1]; + harness.event(Event::ModifiersChanged(Modifiers::SHIFT)); + harness.hover_at(FIRST_CLICK); + save(&mut harness, "shift-line-zoom-pan-preview"); + + harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 256})).unwrap(); + save(&mut harness, "shift-line-new-project"); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + assert_shift_click_paints_only_a_dot(&mut harness); +} diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs new file mode 100644 index 00000000..bffac25b --- /dev/null +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -0,0 +1,106 @@ +//! Key presses run the commands bound to exactly that chord. + +use egui::{Event, Key, Modifiers, OutputCommand, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::ViewLayout; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn press(key: Key, modifiers: Modifiers, repeat: bool) -> Event { + Event::Key { key, physical_key: None, pressed: true, repeat, modifiers } +} + +fn hidden(h: &Harness<'_, TextureCraftApp>) -> bool { + h.state().ui.hide_ui +} + +#[test] +fn a_bound_key_runs_its_command() { + let mut h = harness(); + h.event(press(Key::Tab, Modifiers::NONE, false)); + h.run_steps(2); + assert!(hidden(&h), "Tab hides the UI"); +} + +#[test] +fn extra_shift_or_alt_does_not_run_a_plain_key_shortcut() { + let mut h = harness(); + h.event(press(Key::Tab, Modifiers::SHIFT, false)); + h.event(press(Key::Tab, Modifiers::ALT, false)); + h.run_steps(2); + assert!(!hidden(&h)); +} + +#[test] +fn a_held_key_runs_its_command_again() { + let mut h = harness(); + // Tab also moves egui's keyboard focus, and a focused text field stops the second press. + h.state_mut().ui.keymap.insert("ui.hideUi".into(), "F7".into()); + h.run_steps(2); + h.event(press(Key::F7, Modifiers::NONE, false)); + h.run_steps(2); + assert!(hidden(&h)); + h.event(press(Key::F7, Modifiers::NONE, true)); + h.run_steps(2); + assert!(!hidden(&h), "the repeat toggled it back"); +} + +#[test] +fn a_shortcut_stored_in_the_settings_replaces_the_default() { + let mut h = harness(); + assert_ne!(h.state().ui.layout, ViewLayout::Only3D); + h.state_mut().ui.keymap.insert("ui.layout.3d".into(), "Ctrl+Shift+H".into()); + h.run_steps(2); + h.event(press(Key::F2, Modifiers::NONE, false)); + h.run_steps(2); + assert_ne!(h.state().ui.layout, ViewLayout::Only3D, "the default no longer runs it"); + h.event(press(Key::H, Modifiers::COMMAND | Modifiers::SHIFT, false)); + h.run_steps(2); + assert_eq!(h.state().ui.layout, ViewLayout::Only3D); +} + +#[test] +fn copy_with_label_text_selected_puts_that_text_on_the_clipboard() { + let mut h = harness(); + h.state_mut().session.log.push("a line to copy".into()); + h.state_mut().ui.dock.focus(Panel::Log); + h.run_steps(4); + let line = h.get_all_by_label("a line to copy").next().unwrap().rect(); + let (from, to) = (line.left_center() + egui::vec2(1.0, 0.0), line.right_center()); + h.hover_at(from); + h.step(); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.hover_at(to); + h.step(); + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + h.event(Event::Copy); + h.step(); + let last_copied = h.output().platform_output.commands.iter().rev().find_map(|c| match c { + OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }); + assert_eq!(last_copied.as_deref(), Some("a line to copy"), "the selected text is the last text copied"); +} + +#[test] +fn a_pasted_image_counts_as_the_paste_shortcut() { + let mut h = harness(); + let before = h.state().session.doc.project.layers.len(); + h.event(Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some()); + let image = std::sync::Arc::new(egui::ColorImage::filled([1, 1], egui::Color32::WHITE)); + h.event(Event::PasteImage(image)); + h.run_steps(3); + assert!(h.state().session.doc.project.layers.len() > before, "the paste ran layer.paste"); +} diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs similarity index 94% rename from crates/ui-egui/tests/skew_paint.rs rename to crates/ui-egui/tests/it/skew_paint.rs index 1fd92400..bfcc3e3e 100644 --- a/crates/ui-egui/tests/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -1,11 +1,12 @@ //! Bake mode: with the skew brush on, dragging in the 2D view paints the skew map, and the -//! brush controls are in the Bake panel. +//! brush controls are in Common Settings. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; +/// A bake-mode app with a high poly, the 2D view, and Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); @@ -13,7 +14,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { h.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); - h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::BakeSettings); + h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::CommonSettings); h.run_steps(3); h } diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs new file mode 100644 index 00000000..e0a487fc --- /dev/null +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -0,0 +1,209 @@ +//! The divider between the 3D and 2D views in the split layout resizes them and keeps the pointer from the views + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::ui_state_store::UiStateStore; + +/// Narrowest a split view may get, as in `viewport.rs` +const MIN_VIEW_WIDTH: f32 = 16.0; + +/// A press clear of the divider's 8 point grab zone and egui's 5 point interact radius +const BESIDE_DIVIDER: f32 = 16.0; + +/// App storage held in memory, saved the way the app saves its state between runs +#[derive(Default)] +struct MemoryStorage(std::collections::HashMap); + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} +} + +/// The sample project in the default split layout at 1600 x 960 +fn split_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Drag with `button` from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// The divider's x position: the 3D view ends 1 point left of it +fn divider_x(harness: &Harness<'_, TextureCraftApp>) -> f32 { + harness.state().viewport_rect.right() + 1.0 +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The 2D view's texture as drawn: its centre's offset from the view's centre and its half width and height, in pixels at 1 point per pixel +fn uv_texture_on_screen(harness: &Harness<'_, TextureCraftApp>, views_right: f32) -> [f32; 4] { + let app = harness.state(); + + // egui draws the view's frame into its rect rounded to whole pixels + let width = views_right.round() - (divider_x(harness) + 1.0).round(); + let height = app.viewport_rect.bottom().round() - app.viewport_rect.top().round(); + let texture_size = app.session.doc.project.texture_sets[app.session.ts()].size(); + let [scale_x, scale_y] = texturecraft_render::uv_view_scale(width / height, app.ui.uv_zoom, texture_size); + let [pan_x, pan_y] = app.ui.uv_pan; + [pan_x * width * 0.5, pan_y * height * 0.5, scale_x * width * 0.5, scale_y * height * 0.5] +} + +/// The 3D camera's yaw and pitch +fn camera_angles(harness: &Harness<'_, TextureCraftApp>) -> (f32, f32) { + let camera = &harness.state().session.camera; + (camera.yaw, camera.pitch) +} + +#[test] +fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { + let mut harness = split_app(); + let views_left = harness.state().viewport_rect.left(); + let start_x = divider_x(&harness); + let views_width = (start_x - views_left) * 2.0; + let views_right = views_left + views_width; + let y = harness.state().viewport_rect.center().y; + assert_eq!(harness.state().ui.split_ratio, 0.5); + + drag(&mut harness, PointerButton::Primary, pos2(start_x, y), pos2(start_x - 200.0, y)); + assert!((divider_x(&harness) - (start_x - 200.0)).abs() < 0.5, "follows the pointer: {}", divider_x(&harness)); + assert!((harness.state().ui.split_ratio - (start_x - 200.0 - views_left) / views_width).abs() < 1e-3); + + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_left + 10.0, y)); + assert!((divider_x(&harness) - views_left - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the left: {}", divider_x(&harness)); + + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_right - 10.0, y)); + assert!((views_right - divider_x(&harness) - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the right: {}", divider_x(&harness)); +} + +#[test] +fn pressing_on_the_divider_neither_paints_nor_moves_the_camera() { + let mut harness = split_app(); + + // Pan the texture's centre under the divider so a press there would paint if the 2D view got it + harness.state_mut().ui.uv_pan[0] = -1.0; + harness.run_steps(2); + let x = divider_x(&harness); + let y = harness.state().viewport_rect.center().y; + let (tiles, angles) = (painted_tiles(&harness), camera_angles(&harness)); + + harness.hover_at(pos2(x, y)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: pos2(x, y), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: pos2(x, y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(x, y + 120.0)); + drag(&mut harness, PointerButton::Secondary, pos2(x, y), pos2(x + 120.0, y)); + assert_eq!(painted_tiles(&harness), tiles, "nothing painted"); + assert_eq!(camera_angles(&harness), angles, "no orbit"); + assert_eq!(divider_x(&harness), x, "a vertical or right-button drag leaves the divider in place"); + + // Beside the divider the views get the same input again + drag(&mut harness, PointerButton::Primary, pos2(x + BESIDE_DIVIDER, y), pos2(x + BESIDE_DIVIDER, y + 40.0)); + assert!(painted_tiles(&harness) > tiles, "the 2D view paints"); + drag(&mut harness, PointerButton::Secondary, pos2(x - BESIDE_DIVIDER, y), pos2(x - BESIDE_DIVIDER - 120.0, y)); + assert_ne!(camera_angles(&harness), angles, "the 3D view orbits"); +} + +#[test] +fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { + let mut storage = MemoryStorage::default(); + let mut ui_state = UiState::default(); + ui_state.split_ratio = 0.3; + UiStateStore::default().save(&ui_state, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); + assert_eq!(restored.split_ratio, 0.3); + + // A state saved before the divider existed has no ratio + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("split_ratio").is_some(), "the saved state names the ratio: {saved}"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + let restored = UiStateStore::default().load(Some(&storage)).expect("an older saved state loads"); + assert_eq!(restored.split_ratio, 0.5); +} + +#[test] +fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { + // Zoomed in, a 2D sliver needs a zoom far past the one the view starts with + for zoom in [1.0, 4.0] { + let mut harness = split_app(); + harness.state_mut().ui.uv_zoom = zoom; + harness.state_mut().ui.uv_pan = [0.2, 0.1]; + harness.run_steps(2); + // The split starts centred, so the views end as far right of the divider as they start left of it + let views_left = harness.state().viewport_rect.left(); + let views_right = views_left + (divider_x(&harness) - views_left) * 2.0; + let y = harness.state().viewport_rect.center().y; + let before = uv_texture_on_screen(&harness, views_right); + + let assert_unchanged = |harness: &Harness<'_, TextureCraftApp>| { + let after = uv_texture_on_screen(harness, views_right); + for (was, is) in before.iter().zip(after) { + assert!((was - is).abs() < 0.5, "zoom {zoom}, divider at {}: {before:?} became {after:?}", divider_x(harness)); + } + }; + + for to in [views_left + 300.0, views_right - 150.0, views_right - 10.0, views_left + 500.0] { + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(to, y)); + assert_unchanged(&harness); + } + + // A slow drag past the right end, checked every frame for a nudge at the pixel rounding or the stop + let from = pos2(divider_x(&harness), y); + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + let mut pointer_x = from.x; + while pointer_x < views_right + 20.0 { + // Not a whole number of pixels, so the divider lands at every kind of rounding + pointer_x += 3.3; + harness.hover_at(pos2(pointer_x, y)); + harness.run_steps(1); + assert_unchanged(&harness); + } + harness.event(Event::PointerButton { pos: pos2(pointer_x, y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_unchanged(&harness); + + // Inside the wheel's 0.1 to 40 range, so the next scroll in the narrow view can't snap the zoom + let stopped_zoom = harness.state().ui.uv_zoom; + assert!((0.1..=40.0).contains(&stopped_zoom), "zoom {zoom} stopped at {stopped_zoom}"); + } +} diff --git a/crates/ui-egui/tests/start_window.rs b/crates/ui-egui/tests/it/start_window.rs similarity index 100% rename from crates/ui-egui/tests/start_window.rs rename to crates/ui-egui/tests/it/start_window.rs diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs new file mode 100644 index 00000000..7d91e558 --- /dev/null +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -0,0 +1,209 @@ +//! Toolbar layout and input coverage + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::{Session, Tool}; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; +use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; + +fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Toolbar", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let context = eframe::CreationContext::_new_kittest(egui::Context::default()); + let mut app = TextureCraftApp::new(&context, session); + app.session.tool.tool = tool; + app.session.tool.brush.lazy = 20.0; + let mut harness = Harness::builder() + .with_size(egui::vec2(width, 200.0)) + .with_context_setup(|context| { + theme::install(context); + theme::apply(context, theme::Brightness::default(), theme::Accent::default()); + }) + .build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + harness.run_steps(4); + harness +} + +fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect) { + harness + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "Size" => Some((text.pos, shape.clip_rect)), + _ => None, + }) + .unwrap() +} + +#[test] +fn narrow_toolbars_keep_scroll_arrows_and_mode_buttons_separate() { + let mut harness = toolbar_harness(700.0, Tool::Path); + for button_size in [20.0, 24.0, 28.0] { + harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); + for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { + let width = width * button_size / 24.0; + harness.set_size(egui::vec2(width, 200.0)); + harness.run_steps(4); + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let (_, clip) = size_label(&harness); + for button in [left, right, bake] { + assert_eq!(button.size(), egui::Vec2::splat(button_size)); + } + + assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); + assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); + assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); + assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + } + } +} + +#[test] +fn arrows_and_wheel_scroll_without_changing_the_brush() { + let mut harness = toolbar_harness(700.0, Tool::Path); + let brush = harness.state().session.tool.brush.clone(); + let start = size_label(&harness).0.x; + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + let scrolled = size_label(&harness).0.x; + assert!(scrolled < start - 50.0); + + harness.get_by_label("Scroll left").click(); + harness.run_steps(30); + assert!((size_label(&harness).0.x - start).abs() < 1.0); + + let (_, clip) = size_label(&harness); + harness.hover_at(clip.center()); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-100.0, 0.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(30); + assert!(size_label(&harness).0.x < start - 50.0); + assert_eq!(harness.state().session.tool.brush, brush); +} + +#[test] +fn shorter_tools_and_wider_windows_remove_the_arrows() { + let mut harness = toolbar_harness(700.0, Tool::Path); + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.state_mut().session.tool.fill_mode = texturecraft_engine::FillMode::Mesh; + harness.run_steps(4); + assert!(harness.query_by_label("Scroll right").is_none()); + let triangle = harness.get_by_label("Triangle fill").rect(); + harness.get_by_label("Triangle fill").click(); + harness.run_steps(2); + assert!(harness.ctx.content_rect().contains_rect(triangle)); + assert_eq!(harness.state().session.tool.fill_mode, texturecraft_engine::FillMode::Triangle); + + harness.state_mut().session.tool.tool = Tool::Path; + harness.set_size(egui::vec2(1600.0, 200.0)); + harness.run_steps(4); + assert!(harness.query_by_label("Scroll right").is_none()); + let (position, clip) = size_label(&harness); + assert!(clip.contains(position)); +} + +#[test] +fn compact_view_buttons_can_be_scrolled_into_view_and_clicked() { + let mut harness = toolbar_harness(400.0, Tool::Path); + for _ in 0..20 { + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let visible = harness.query_by_label("UV checker").is_some_and(|node| node.rect().left() > left.right() && node.rect().right() < right.left()); + if visible { + harness.get_by_label("UV checker").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::UvChecker); + return; + } + + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + } + + panic!("the view buttons never became accessible"); +} + +#[test] +fn mode_buttons_keep_their_order_and_dispatch_commands() { + let mut harness = toolbar_harness(700.0, Tool::Paint); + for (label, mode) in [("Bake Mesh Maps (F8)", Mode::Baking), ("Rendering (path traced) (F10)", Mode::Rendering), ("Painting (F9)", Mode::Painting)] { + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let paint = harness.get_by_label("Painting (F9)").rect(); + let render = harness.get_by_label("Rendering (path traced) (F10)").rect(); + assert!(bake.right() < paint.left() && paint.right() < render.left()); + harness.get_by_label(label).click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.mode, mode); + } +} + +#[test] +fn view_dropdowns_set_the_layout_and_projection() { + let mut harness = toolbar_harness(1600.0, Tool::Paint); + harness.get_by_label("3D/2D views (F1)").click(); + harness.run_steps(3); + harness.get_by_label_contains("3D view only").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.layout, ViewLayout::Only3D); + assert!(harness.query_by_label_contains("2D view only").is_none(), "the layout menu stays open"); + assert!(harness.query_by_label("3D view only (F2)").is_some()); + + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Orthographic").is_none(), "a second click keeps the projection menu open"); + + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + harness.get_by_label_contains("Orthographic").click(); + harness.run_steps(3); + assert!(harness.state().session.camera.ortho); + assert!(harness.query_by_label("Orthographic").is_some()); +} + +#[test] +#[ignore] +fn toolbar_frame_timing() { + for width in [1600.0, 1000.0, 400.0] { + let mut harness = toolbar_harness(width, Tool::Path); + harness.run_steps(100); + let mut timings = [0.0_f64; 5]; + for timing in &mut timings { + let start = std::time::Instant::now(); + harness.run_steps(1000); + *timing = start.elapsed().as_secs_f64() * 1000.0; + } + timings.sort_by(f64::total_cmp); + eprintln!("Path + lazy mouse, width {width}: {:.2} us/frame median, batches {timings:?}", timings[2]); + } +} + +#[test] +#[ignore] +fn toolbar_window_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { + return; + }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().session.tool.tool = Tool::Path; + harness.state_mut().session.tool.brush.lazy = 20.0; + for (width, scale) in [(1600.0, 1.0), (960.0, 1.0), (960.0, 1.5)] { + harness.set_size(egui::vec2(width, 960.0)); + harness.state_mut().ui.prefs.ui_scale = scale; + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("toolbar-{width}-{scale}.png"))).unwrap(); + } +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..fe90dda3 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -14,6 +14,12 @@ use texturecraft_ui_egui::state::Mode; use texturecraft_ui_egui::theme::Brightness; use texturecraft_ui_egui::titlebar::TitleBar; +/// Click a map's row in Mesh Map Bakers, which shows its settings +fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(egui::Role::Button, name).click(); + harness.run_steps(3); +} + fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { h.run_steps(6); let img = h.render().unwrap_or_else(|e| panic!("{name}: {e}")); @@ -58,22 +64,20 @@ fn window_snapshots() { } harness.state_mut().ui.mode = Mode::Baking; save(&mut harness, &output_dir, "mode-bake"); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.get_by_label("Ambient Occlusion").scroll_to_me(); + select_map(&mut harness, "Ambient Occlusion"); save(&mut harness, &output_dir, "mode-bake-maps"); harness.state_mut().ui.prefs.brightness = Brightness::Light; save(&mut harness, &output_dir, "mode-bake-maps-light"); harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - harness.get_by_label("Opacity").scroll_to_me(); + select_map(&mut harness, "Opacity"); save(&mut harness, &output_dir, "mode-bake-unchecked"); harness.state_mut().ui.dock.focus(Panel::TextureSetList); save(&mut harness, &output_dir, "bake-texture-sets"); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); save(&mut harness, &output_dir, "bake-settings"); harness.state_mut().session.add_high_poly_bytes("High Poly.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); save(&mut harness, &output_dir, "bake-settings-high-poly"); - harness.get_by_label("Cage").scroll_to_me(); + harness.get_by_role_and_label(egui::Role::ComboBox, "Cage Type").scroll_to_me(); save(&mut harness, &output_dir, "bake-settings-cage-skew"); harness.get_by_label("Edge Contrast").scroll_to_me(); save(&mut harness, &output_dir, "bake-settings-skew"); @@ -90,11 +94,9 @@ fn window_snapshots() { settings.maps.height.parameters.normalization = HeightNormalization::Manual; settings.maps.height.parameters.scaling_divisor = 100.0; } - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.get_by_label("Curvature").scroll_to_me(); + select_map(&mut harness, "Curvature"); save(&mut harness, &output_dir, "bake-curvature-mesh"); - harness.get_by_label("Scaling Divisor").scroll_to_me(); + select_map(&mut harness, "Height"); save(&mut harness, &output_dir, "bake-height-manual"); harness.state_mut().session.bake_meshes.high.clear(); harness.state_mut().ui.mode = Mode::Painting; @@ -158,3 +160,145 @@ fn window_snapshots() { harness.event(egui::Event::PointerButton { pos: cursor_position, button, pressed: false, modifiers }); harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } + +#[test] +#[ignore] +fn bake_uv_tiles_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the pictures"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = + texturecraft_engine::Session::new_project("UV tile baking", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256) + .unwrap(); + texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, &output_dir, "bake-uv-tiles"); + + harness.get_by_value("128 × 128*").click(); + save(&mut harness, &output_dir, "bake-tile-resolution-menu"); + harness.get_by_label("Remove resolution override").click(); + save(&mut harness, &output_dir, "bake-tile-resolution-inherited"); + assert!(harness.query_by_value("128 × 128*").is_none()); + assert!(harness.state().session.doc.project.texture_sets[0].tile_resolutions.is_empty()); + let inherited_resolution = harness.get_by_label("UV tile 1002 resolution").rect().center(); + harness.hover_at(inherited_resolution); + save(&mut harness, &output_dir, "bake-tile-resolution-hover"); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + + harness.get_by_role_and_label(egui::Role::CheckBox, "1002").click(); + save(&mut harness, &output_dir, "bake-uv-tiles-partial"); + assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); + + harness.get_by_label("Show or hide the texture set").click(); + save(&mut harness, &output_dir, "bake-uv-tiles-hidden"); + assert!(!harness.state().session.doc.project.texture_sets[0].visible); + assert!(harness.state().session.doc.project.texture_sets[0].bake.common.is_enabled); +} + +#[test] +#[ignore] +fn smart_mask_shelf_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the picture"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = + texturecraft_engine::Session::new_project("Mask previews", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = 2; + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + let thumbnails = &mut harness.state_mut().thumbs; + if texturecraft_engine::smart_masks::SMART_MASKS.iter().all(|preset| thumbnails.smart_mask(&context, preset.id).is_some()) { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(60), "smart mask thumbnails did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + eprintln!("all smart mask thumbnails ready after {:.3} s", started.elapsed().as_secs_f64()); + save(&mut harness, &output_dir, "smart-mask-shelf"); + + let mask = &texturecraft_engine::smart_masks::SMART_MASKS[0]; + harness.get_by_role_and_label(egui::Role::Button, mask.label).hover(); + let preview = texturecraft_ui_egui::shelf_preview::ShelfPreview::SmartMask(mask.id); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + if harness.state_mut().thumbs.rendered_big(&context, &preview, 256).is_some() { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(60), "smart mask hover preview did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + harness.run_steps(60); + assert_eq!(harness.query_all_by_label(mask.label).count(), 2, "the popup shows the mask name"); + save(&mut harness, &output_dir, "smart-mask-hover"); +} + +#[test] +#[ignore] +fn smart_material_shelf_snapshot() { + use texturecraft_engine::materials::MATERIALS; + use texturecraft_ui_egui::shelf_preview::ShelfPreview; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the pictures"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = + texturecraft_engine::Session::new_project("Smart material previews", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128) + .unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { + let render_state = context.wgpu_render_state.as_ref().expect("the snapshot uses wgpu"); + eprintln!("snapshot adapter: {:?}", render_state.adapter.get_info()); + TextureCraftApp::new(context, session) + }); + harness.state_mut().ui.shelf_tab = 1; + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + let thumbnails = &mut harness.state_mut().thumbs; + if MATERIALS.iter().filter(|material| material.smart).all(|material| thumbnails.material(&context, material.id).is_some()) { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(120), "smart material thumbnails did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + eprintln!("all smart material thumbnails ready after {:.3} s", started.elapsed().as_secs_f64()); + save(&mut harness, &output_dir, "smart-material-shelf"); + + let material = MATERIALS.iter().find(|material| material.id == "steel_painted_worn").unwrap(); + harness.get_by_role_and_label(egui::Role::Button, material.label).hover(); + let preview = ShelfPreview::material(material.id); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + if harness.state_mut().thumbs.rendered_big(&context, &preview, 256).is_some() { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(60), "smart material hover preview did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + harness.run_steps(60); + assert_eq!(harness.query_all_by_label(material.label).count(), 2, "the popup shows the material name"); + save(&mut harness, &output_dir, "smart-material-hover"); +} diff --git a/crates/ui-egui/tests/ui_state_persistence.rs b/crates/ui-egui/tests/ui_state_persistence.rs new file mode 100644 index 00000000..a2008864 --- /dev/null +++ b/crates/ui-egui/tests/ui_state_persistence.rs @@ -0,0 +1,106 @@ +//! App save/restart coverage, including offscreen rendering when explicitly requested + +use eframe::App as _; +use egui_kittest::Harness; +use texturecraft_ui_egui::{TextureCraftApp, docking::Panel, state::Mode}; + +#[path = "../src/ui_state_store/memory_storage.rs"] +mod memory_storage; +use memory_storage::MemoryStorage; + +fn app(storage: &MemoryStorage, render: bool) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + // Existing viewport controls lack accessible names; these tests check persistence and rendering + let builder = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false); + let builder = if render { builder.wgpu() } else { builder }; + builder.build_eframe(|context| { + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(storage); + creation.wgpu_render_state = context.wgpu_render_state.clone(); + TextureCraftApp::new(&creation, session) + }) +} + +fn customize(harness: &mut Harness<'_, TextureCraftApp>) { + harness.state_mut().ui.dock.close(Panel::Assets); + harness.state_mut().ui.split_ratio = 0.35; + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + harness.state_mut().ui.dock.close(Panel::MeshMapBakers); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(3); +} + +#[test] +fn app_save_restores_both_customized_modes() { + let mut storage = MemoryStorage::default(); + let mut original = app(&storage, false); + customize(&mut original); + original.state_mut().save(&mut storage); + let mut restarted = app(&storage, false); + restarted.run_steps(3); + assert_eq!(restarted.state().ui.dock, original.state().ui.dock); + assert_eq!(restarted.state().ui.split_ratio, 0.35); + + for harness in [&mut original, &mut restarted] { + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + } + assert_eq!(restarted.state().ui.dock, original.state().ui.dock); + assert!(!restarted.state().ui.dock.is_open(Panel::MeshMapBakers)); +} + +#[test] +fn failed_backups_show_one_persistent_warning_and_keep_the_original() { + let mut storage = MemoryStorage::default(); + storage.values.insert("ui.json".into(), "not json".into()); + for index in 1..=10 { + let key = if index == 1 { "ui.unreadable.json".into() } else { format!("ui.unreadable-{index}.json") }; + storage.values.insert(key, "previous backup".into()); + } + let mut harness = app(&storage, false); + harness.state_mut().save(&mut storage); + harness.state_mut().save(&mut storage); + assert_eq!(storage.values["ui.json"], "not json"); + let warnings = &harness.state().toasts; + assert_eq!(warnings.len(), 1); + assert!(warnings[0].error && warnings[0].until.is_infinite()); + assert!(warnings[0].text.contains("Saving is disabled")); + assert!(harness.state().session.log.iter().any(|line| line == &warnings[0].text)); +} + +#[test] +#[ignore = "requires an offscreen GPU and TC_UI_SNAPSHOTS"] +fn customized_layout_restart_snapshots() { + let output = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output).unwrap(); + let file = output.join("restart-ui.json"); + let _ = std::fs::remove_file(&file); + texturecraft_ui_egui::ui_state_store::FILE.set(file).unwrap(); + let mut storage = MemoryStorage::default(); + let mut original = app(&storage, true); + eprintln!("Rendering adapter: {}", original.state().gpu.as_ref().unwrap().adapter); + customize(&mut original); + original.state_mut().save(&mut storage); + let mut restarted = app(&storage, true); + eprintln!("Restart rendering adapter: {}", restarted.state().gpu.as_ref().unwrap().adapter); + + for (mode, name) in [(Mode::Painting, "painting"), (Mode::Baking, "baking")] { + for (harness, suffix) in [(&mut original, "before"), (&mut restarted, "after")] { + harness.state_mut().ui.mode = mode; + harness.run_steps(8); + harness.render().unwrap().save(output.join(format!("restart-{name}-{suffix}.png"))).unwrap(); + } + assert_eq!(restarted.state().ui.dock, original.state().ui.dock); + assert_eq!(restarted.state().ui.split_ratio, original.state().ui.split_ratio); + } + + let file = texturecraft_ui_egui::ui_state_store::FILE.get().unwrap(); + std::fs::remove_file(file).unwrap(); + std::fs::create_dir(file).unwrap(); + let mut unreadable = app(&storage, true); + assert!(unreadable.state().toasts.iter().any(|toast| toast.text.contains("Saving is disabled"))); + unreadable.run_steps(8); + unreadable.render().unwrap().save(output.join("settings-read-warning.png")).unwrap(); + std::fs::remove_dir(file).unwrap(); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..0c2c9a1b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -19,11 +19,53 @@ index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate { one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. +`effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its +stack position, blend, opacity and visibility. Replacement filters start from defaults plus +the supplied parameters; naming the current filter instead edits it without resetting omitted +parameters. Default effect names follow the new filter, custom names remain, and an explicit +`name` overrides either. Only filter effects can be replaced this way, and masks reject +content-only filters. `filter.list` lists the available IDs; levels and material finishes +must be added separately with `effect.add.filter`. A successful replacement is one undo step; +a rejected replacement changes nothing. + `edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far as the history reaches); `edit.history` lists the steps done and the undone ones, next first. Any command takes `merge: true` to fold its edit into the previous undo step when that step has the same label: a drag that applies a value on every frame stays one step. +Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each +set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the +changed fields; Restore Defaults resets the whole parameter section across all sets. + +`bake.settings {ts: "all", patch: {maps: {ao: {parameters: {rays: {rays: 128}}}}}}` changes +only AO secondary rays. A `patch` uses the nested `BakeSettings` field names and named enum +values returned in the command's `model` result; omitted fields retain each set's values, and +`null` clears optional fields such as `common.resolution_height`. All targeted sets are validated +before the edit is applied as one undo step. `model` still replaces the complete settings; +when combined, `patch` follows `model`, then the flat command parameters apply. Omitting `ts` +still targets the active set for scripts that need individual control. + +The bake texture-set list shows visibility eyes and expandable UV tile rows. Visibility affects +the viewport independently of bake inclusion. Its resolution menus edit the texture-set size +(`textureSet.resolution`) and individual tile overrides (`textureSet.tile.resolution`), independently +of Common Settings' bake Output Size. Overridden tiles display a resolution marked with an asterisk; +inherited tile resolutions appear only on hover or while their menu is open. Remove resolution +override hides the number and restores inheritance from the set, including when their current +sizes happen to match. + +Baked maps use a uniform UV tile atlas: every selected tile receives the full bake Output Size, +including rectangular output sizes. Changing a texture-set or tile working resolution preserves +the stored bake pixels. Materials, mesh-map previews, and exports sample those pixels through +the working tile layout. Older project files load their baked pixels as-is without layout +conversion; rebaking restores correct mapping and detail. + +`bake.tile.set {ts?, tile: 1002, enabled: false}` +excludes one UV tile; `textureSet.inspect` / `session.inspect` expose each tile's `bakeEnabled`. +Tile choices are saved and undoable. Unchecked tiles retain their previous baked pixels, resampled +if output size changes, or neutral values when no previous map exists. A running bake uses the +tile selection captured when its worker started. Sets with no checked tiles are skipped; their +geometry still contributes to occlusion when baking other tiles. + ## Control channel (desktop app) ```sh @@ -120,8 +162,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, -`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` +`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. | Tool | Params | Notes | @@ -137,7 +179,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | @@ -223,6 +265,15 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## Camera bookmarks + +Saved cameras (`Project.cameras`, stored in the `.tcraft` file) are the camera bookmarks. +`camera.add {name?}` saves the current view, `camera.list` lists them (`current` is the one the view +is at), `camera.select {index? | name?}` restores one, `camera.rename {index? | name?, to}` and +`camera.remove {index? | name?}` edit them. `camera.bookmark1` … `camera.bookmark9` (Ctrl+1 … Ctrl+9) +go to the first nine. Commands jump straight to the view; the desktop UI glides there over about a third +of a second. + ## MaterialCraft materials A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md new file mode 100644 index 00000000..6580c84f --- /dev/null +++ b/docs/helpful-pr-review-guidelines.md @@ -0,0 +1,99 @@ +# My PR review standards + +Use these preferences when reviewing and improving a PR. Follow repository requirements for implementation and validation, and my explicit task instructions for the scope and authorized actions. + +## Review scope + +- Read the PR description, relevant issue discussion, and existing review threads; compare the diff against the intended base +- Review-only requests call for findings; requests to fix or improve also authorize focused local edits +- A review may conclude that no changes are needed. If the PR meets the applicable standards and no actionable issues are found, leave it unchanged. Do not invent findings, add unnecessary tests, or make edits merely to produce a diff. Report what was checked and any remaining validation limits +- Apply all review standards across the entire affected method, including existing code and relevant tests +- Complete naming, spacing, and comment cleanup throughout it +- Make additional correctness or performance changes when supported by evidence and appropriate validation +- Separate substantial changes that address an independent problem, explaining why +- Apply the same scope to standalone functions and inspect relevant callers when verifying behavior +- Distinguish problems introduced by the PR from pre-existing problems, and avoid repeating findings already covered by an unresolved review thread + +## Correctness + +- Verify the claimed fix against the actual definitions, code paths, and callers before proposing a change +- Identify a concrete trigger, expected behavior, actual behavior, and practical impact for each suspected defect +- Look for missed edge cases, incomplete fixes, and regressions, including malformed input, numeric boundaries, and partial failures where relevant +- Check compatibility with affected public interfaces, saved data, and supported platforms +- Reproduce suspicious behavior locally when practical; distinguish a reproduction from a conclusion based on code inspection +- Make regression tests fail before the fix and pass afterward; verify that the earlier failure demonstrates the defect rather than a broken build or test setup +- Confirm tests exercise the intended path, especially fallbacks and error handling, and assert observable behavior + +## Optimization and simplicity + +- Prefer the smallest complete solution that is efficient and easy to understand +- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- Consider caching, batching, and parallelism when measurements justify their complexity and memory cost +- Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads +- Compare before and after with the same inputs, build settings, and environment; account for measurement variation and cold or warm state where relevant +- Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations +- Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity + +## Clarity, naming, and spacing + +- Clean up the functions or methods being changed and their relevant tests within the scope above +- Use descriptive names that explain purpose; include units where useful +- Avoid cryptic abbreviations, misleading names, and unexplained production constants +- Keep control flow direct and share repeated logic when it makes the code simpler +- Use a single blank line to separate logical steps, such as input preparation, validation, computation, mutation, and result construction, when those steps are distinct +- Keep closely related statements together; avoid spacing that fragments a single operation or inserts a blank line after every declaration +- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before the next statement +- Keep comments attached to the code they explain; put a blank line before a comment introducing a new step, with no blank line between the comment and that step +- Keep documentation and attributes attached to their declarations +- Separate function definitions with one blank line; avoid extra empty lines immediately inside braces or between every field, argument, or statement +- Group tests into preparation, action, and verification with blank lines where those phases are distinct; keep related assertions together +- Apply this spacing consistently throughout affected functions, methods, and tests, and follow the repository's formatter for mechanical formatting + +## Source organization + +- Keep each class, enum, or struct in its own source file, with its implementation beside it +- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust +- Use singular folder names, such as `map`, `setting`, or `tracing` +- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file +- Apply these preferences to new types and source organization changes within scope; follow mandatory repository layout rules and leave unrelated existing structure alone + +## Comments + +- Use short, single-line comments; adjacent comment lines should each express a concise point +- Avoid block comments and wrapped prose in ordinary implementation comments +- Explain intent or a non-obvious constraint rather than narrating the code +- No trailing punctuation on ordinary code comments +- Preserve explanations of guards and invariants; remove stale or redundant comments without losing necessary rationale +- API documentation, required license headers, and examples may use their conventional multiline formatting and punctuation +- Apply these standards to both production code and tests + +## Validation and reporting + +- Run relevant tests and required repository checks with the project's expected toolchain +- For ordinary comments or spacing alone, verify formatting and that executable code is unchanged; validate documentation examples or tool directives if they changed +- Report the commands actually run and their results; identify checks not run and why +- Distinguish existing failures from new ones using a baseline check when practical; otherwise state that the cause is unverified +- For behavioral defects, report the location, trigger, expected and actual behavior, practical impact, and supporting evidence +- For naming, spacing, or organization findings, identify the location and the specific standard being missed +- Order findings by severity and distinguish confirmed problems, hypotheses needing verification, and optional improvements +- Give measured optimization results with workload, build, and environment details; do not describe an unmeasured change as faster +- State remaining limitations and coverage gaps; if no actionable problems were found, say so without implying complete correctness +- Before handing back edits, review the final diff for unintended behavior changes, unrelated edits, and claims unsupported by validation + +## Review and commit workflow + +- Preserve unrelated work and leave changes unstaged for my manual review unless I ask otherwise +- Stage only when requested +- Wait for my explicit commit command before committing +- Do not post reviews or comments without explicit instructions; a request to review, fix, or improve alone does not authorize these actions +- When requested, provide a simple ready-to-post Markdown summary outside the repository and exclude it from the commit + +## Push safety + +- Default to no pushes; permission to edit, stage, commit, test, review, or prepare a PR never implies permission to push +- Push only on my explicit instruction to push, within the authorized remote, destination branch or tag, and scope of changes; permission for one task does not authorize unrelated pushes +- Before an authorized push, verify the remote URL, destination ref, and complete outgoing commits and diff; stop and ask if the destination or included changes are ambiguous or exceed my authorization +- Run an authorized push as a standalone command with an explicit remote and destination ref; never bundle it into commit, validation, or cleanup commands +- Check helpers, aliases, scripts, and hooks for automatic pushes before running them when they may publish; IDE sync or publish actions and APIs that update remote Git refs require the same explicit authorization +- Do not use broad pushes such as `--all`, `--mirror`, or `--tags`, force pushes, remote ref deletion, or hook bypasses without separate explicit authorization for that operation +- Never bypass repository branch protection or push directly to a branch that the repository requires to change through pull requests diff --git a/docs/parity.md b/docs/parity.md index d6543d54..75f6fd30 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**55 of 55 menu items live (100%).** +**59 of 59 menu items live (100%).** ## File @@ -46,13 +46,16 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Item | Id | Shortcut | Status | |---|---|---|---| | Views ▸ Assets | `ui.view.assets` | | live | +| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | | Views ▸ Display Settings | `ui.view.display` | | live | | Views ▸ History | `ui.view.history` | | live | | Views ▸ Layers | `ui.view.layers` | | live | | Views ▸ Log | `ui.view.log` | | live | +| Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | +| Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | | Views ▸ Properties | `ui.view.properties` | | live | | Views ▸ Shader Settings | `ui.view.shader` | | live | -| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | +| Views ▸ Texture Sets | `ui.view.textureSetList` | | live | | Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | | Save UI Layout ▸ Save current layout... | `ui.layout.save` | | live | | Load UI Layout | `ui.layout.load` | | live | @@ -87,5 +90,6 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | ArtCraft website... | `ui.help.website` | | live | | Report a bug... | `ui.help.bug` | | live | | Show log... | `ui.view.log` | | live | +| Check for Updates... | `ui.help.checkForUpdates` | | live | | About TextureCraft... | `ui.about` | | live | diff --git a/docs/releasing.md b/docs/releasing.md index c387a5f3..2658af20 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,20 +1,19 @@ # Releasing TextureCraft -The recipe is craftrules' [release playbook](release-playbook.md); this page covers what is +The recipe is the [release playbook](release-playbook.md); this page covers what is specific to TextureCraft. The pipeline is [`.github/workflows/release.yml`](../.github/workflows/release.yml). ## Release manager checklist The steps below are the release manager's; agents never create the `release` branch, tags or -GitHub Releases. The shared runbook with copy-paste `gh` commands is craftrules -`release/cut-a-release.md`. +GitHub Releases. Follow the checklist below and the linked release playbook. ### 1. One-time repository setup (org admin) Status on 2026-10-23: `storytold/texturecraft` has the `release` environment (deployable from `release` only) and the `release` ruleset (steps 1 and 2 below). Still to do before the first run: the secrets (step 3) and the runner group (step 4); the `release` branch is created by the first -release push. An org admin runs craftrules `release/signing-setup.md` steps 1-2 for this repo: +release push. An org admin completes the following setup for this repo: 1. Create the **`release` environment**, with deployment branches limited to `release`. 2. Add the **ruleset on `refs/heads/release`** (restrict creations, updates and deletions, block @@ -38,15 +37,21 @@ release push. An org admin runs craftrules `release/signing-setup.md` steps 1-2 ### 2. Set the version -On `main`: +Start from an up-to-date `main` and create a version-bump branch: ```sh +git switch main +git pull --ff-only +git switch -c bump-version-0.2.0 cargo xtask version # prints the current version cargo xtask version set 0.2.0 # or 0.2.0-rc.1 for a pre-release ``` `set` rewrites `[workspace.package] version` in the root `Cargo.toml` (the single source of truth) -and refreshes `Cargo.lock`. Commit, push, and wait for CI on `main` to pass. +and refreshes `Cargo.lock`. Commit the version bump on that branch, push the branch, and open +a pull request into `main`. Wait for the applicable checks to pass and for review, then merge +the pull request. Do not push changes directly to `main`. Wait for CI on the merged `main` +commit to pass before cutting the release below. ### 3. Cut the release @@ -160,7 +165,7 @@ unsigned artifact and a `::warning::`, never a failed build. ## Icons `assets/app-icon/texturecraft.svg` is the engraved zebra (the owner's original drawing, vectorised -to three colours, craftrules `standards/icon-design.md`); `texturecraft-small.svg` is a lighter +to three colours); `texturecraft-small.svg` is a lighter trace for the hicolor scalable icon. `packaging/icons.sh` renders everything else with resvg and `cargo xtask ico|icns`: the hicolor PNGs (16-512 px) and scalable SVG, `texturecraft-1024.png`, `texturecraft.ico` and `texturecraft.icns`. The outputs are committed; rerun it after changing the diff --git a/docs/testing-ci.md b/docs/testing-ci.md new file mode 100644 index 00000000..7db9ae07 --- /dev/null +++ b/docs/testing-ci.md @@ -0,0 +1,24 @@ +# Integration tests and CI + +The engine and UI integration tests share one `it` executable per crate. This +avoids compiling and linking the same crate dependencies into a separate +executable for every feature. Feature modules keep their own helpers and tests. +When adding a file under `tests/it/`, register it with `mod name;` in that +folder's `main.rs` so Cargo runs it. + +Run a feature module with a test-name filter, for example: + +```sh +cargo test -p texturecraft-engine --test it bake:: +``` + +The standalone engine `session` target and UI `ui_snapshots` target remain +available for the commands in `AGENTS.md`. Existing ignore attributes are +unchanged. Tests in the shared executable can run concurrently across modules; +keep temporary paths unique and avoid changing process-wide state. + +CI continues to use the shared gate workflow and `cargo xtask ci` on Ubuntu and +Windows: formatting, Clippy, workspace tests (including doctests), layering and +isolated per-package WebAssembly checks. The caller disables the shared +workflow's optional tool installation because this gate uses `cargo test` and +does not use nextest.